text:
/**
 * @author Julian Gautier
 */

/**
 * Module Dependencies
 */

var util = require('util'),
    events = require('events'),
    chrome = chrome || undefined,
    Encoder7Bit = require('./encoder7bit'),
    OneWireUtils = require('./onewireutils'),
    SerialPort = null;

try {
    if (process.browser) {
        SerialPort = require('browser-serialport').SerialPort;
    } else {
        SerialPort = require('serialport').SerialPort;
    }
} catch (err) {
    SerialPort = null;
}

if (SerialPort == null) {
    console.log("It looks like serialport didn't compile properly. This is a common problem and its fix is well documented here https://github.com/voodootikigod/node-serialport#to-install");
    throw "Missing serialport dependency";
}

/**
 * constants
 */

var PIN_MODE = 0xF4,
    REPORT_DIGITAL = 0xD0,
    REPORT_ANALOG = 0xC0,
    DIGITAL_MESSAGE = 0x90,
    START_SYSEX = 0xF0,
    END_SYSEX = 0xF7,
    QUERY_FIRMWARE = 0x79,
    REPORT_VERSION = 0xF9,
    ANALOG_MESSAGE = 0xE0,
    EXTENDED_ANALOG = 0x6F,
    CAPABILITY_QUERY = 0x6B,
    CAPABILITY_RESPONSE = 0x6C,
    PIN_STATE_QUERY = 0x6D,
    PIN_STATE_RESPONSE = 0x6E,
    ANALOG_MAPPING_QUERY = 0x69,
    ANALOG_MAPPING_RESPONSE = 0x6A,
    I2C_REQUEST = 0x76,
    I2C_REPLY = 0x77,
    I2C_CONFIG = 0x78,
    STRING_DATA = 0x71,
    SYSTEM_RESET = 0xFF,
    PULSE_OUT = 0x73,
    PULSE_IN = 0x74,
    SAMPLING_INTERVAL = 0x7A,
    STEPPER = 0x72,
    ONEWIRE_DATA = 0x73,

    ONEWIRE_CONFIG_REQUEST = 0x41,
    ONEWIRE_SEARCH_REQUEST = 0x40,
    ONEWIRE_SEARCH_REPLY = 0x42,
    ONEWIRE_SEARCH_ALARMS_REQUEST = 0x44,
    ONEWIRE_SEARCH_ALARMS_REPLY = 0x45,
    ONEWIRE_READ_REPLY = 0x43,
    ONEWIRE_RESET_REQUEST_BIT = 0x01,
    ONEWIRE_READ_REQUEST_BIT = 0x08,
    ONEWIRE_DELAY_REQUEST_BIT = 0x10,
    ONEWIRE_WRITE_REQUEST_BIT = 0x20,
    ONEWIRE_WITHDATA_REQUEST_BITS = 0x3C;

/**
* MIDI_RESPONSE contains functions to be called when we receive a MIDI message from the arduino.
* used as a switch object as seen here http://james.padolsey.com/javascript/how-to-avoid-switch-case-syndrome/
* @private
*/

var MIDI_RESPONSE = {};

/**
 * Handles a REPORT_VERSION response and emits the reportversion event.  Also turns on all pins to start reporting
 * @private
 * @param {Board} board the current arduino board we are working with.
 */

MIDI_RESPONSE[REPORT_VERSION] = function (board) {
    board.version.major = board.currentBuffer[1];
    board.version.minor = board.currentBuffer[2];
    for (var i = 0; i < 16; i++) {
        board.sp.write(new Buffer([REPORT_DIGITAL | i, 1]));
        board.sp.write(new Buffer([REPORT_ANALOG | i, 1]));
    }
    board.emit('reportversion');
};

/**
 * Handles a ANALOG_MESSAGE response and emits 'analog-read' and 'analog-read-'+n events where n is the pin number.
 * @private
 * @param {Board} board the current arduino board we are working with.
 */

MIDI_RESPONSE[ANALOG_MESSAGE] = function (board) {
    var value = board.currentBuffer[1] | (board.currentBuffer[2] << 7);
    var port = board.currentBuffer[0] & 0x0F;
    if (board.pins[board.analogPins[port]]) {
        board.pins[board.analogPins[port]].value = value;
    }
    board.emit('analog-read-' + port, value);
    board.emit('analog-read', {
        pin: port,
        value: value
    });
};

/**
 * Handles a DIGITAL_MESSAGE response and emits a 'digital-read' and 'digital-read-'+n events where n is the pin number.
 * @private
 * @param {Board} board the current arduino board we are working with.
 */

MIDI_RESPONSE[DIGITAL_MESSAGE] = function (board) {
    var port = (board.currentBuffer[0] & 0x0F);
    var portValue = board.currentBuffer[1] | (board.currentBuffer[2] << 7);
    for (var i = 0; i < 8; i++) {
        var pinNumber = 8 * port + i;
        var pin = board.pins[pinNumber];
        if (pin && (pin.mode === board.MODES.INPUT)) {
            pin.value = (portValue >> (i & 0x07)) & 0x01;
            board.emit('digital-read-' + pinNumber, pin.value);
            board.emit('digital-read', {
                pin: pinNumber,
                value: pin.value
            });
        }
    }
};

/**
 * SYSEX_RESPONSE contains functions to be called when we receive a SYSEX message from the arduino.
 * used as a switch object as seen here http://james.padolsey.com/javascript/how-to-avoid-switch-case-syndrome/
 * @private
 */

var SYSEX_RESPONSE = {};

/**
 * Handles a QUERY_FIRMWARE response and emits the 'queryfirmware' event
 * @private
 * @param {Board} board the current arduino board we are working with.
 */

SYSEX_RESPONSE[QUERY_FIRMWARE] = function (board) {
    var firmwareBuf = [];
    board.firmware.version = {};
    board.firmware.version.major = board.currentBuffer[2];
    board.firmware.version.minor = board.currentBuffer[3];
    for (var i = 4, length = board.currentBuffer.length - 2; i < length; i += 2) {
        firmwareBuf.push((board.currentBuffer[i] & 0x7F) | ((board.currentBuffer[i + 1] & 0x7F) << 7));
    }

    board.firmware.name = new Buffer(firmwareBuf).toString('utf8', 0, firmwareBuf.length);
    board.emit('queryfirmware');
};

/**
 * Handles a CAPABILITY_RESPONSE response and emits the 'capability-query' event
 * @private
 * @param {Board} board the current arduino board we are working with.
 */

SYSEX_RESPONSE[CAPABILITY_RESPONSE] = function (board) {
    var supportedModes = 0;

    function pushModes(modesArray, mode) {
        if (supportedModes & (1 << board.MODES[mode])) {
            modesArray.push(board.MODES[mode]);
        }
    }

    for (var i = 2, n = 0; i < board.currentBuffer.length - 1; i++) {
        if (board.currentBuffer[i] === 127) {
            var modesArray = [];
            Object.keys(board.MODES).forEach(pushModes.bind(null, modesArray));
            board.pins.push({
                supportedModes: modesArray,
                mode: board.MODES.UNKNOWN,
                value : 0,
                report: 1
            });
            supportedModes = 0;
            n = 0;
            continue;
        }
        if (n === 0) {
            supportedModes |= (1 << board.currentBuffer[i]);
        }
        n ^= 1;
    }
    board.emit('capability-query');
};

/**
 * Handles a PIN_STATE response and emits the 'pin-state-'+n event where n is the pin number
 * @private
 * @param {Board} board the current arduino board we are working with.
 */

SYSEX_RESPONSE[PIN_STATE_RESPONSE] = function (board) {
    var pin = board.currentBuffer[2];
    board.pins[pin].mode = board.currentBuffer[3];
    board.pins[pin].value = board.currentBuffer[4];
    if (board.currentBuffer.length > 6) {
        board.pins[pin].value |= (board.currentBuffer[5] << 7);
    }
    if (board.currentBuffer.length > 7) {
        board.pins[pin].value |= (board.currentBuffer[6] << 14);
    }
    board.emit('pin-state-' + pin);
};

/**
 * Handles a ANALOG_MAPPING_RESPONSE response and emits the 'analog-mapping-query' event.
 * @private
 * @param {Board} board the current arduino board we are working with.
 */

SYSEX_RESPONSE[ANALOG_MAPPING_RESPONSE] = function (board) {
    var pin = 0;
    var currentValue;
    for (var i = 2; i < board.currentBuffer.length - 1; i++) {
        currentValue = board.currentBuffer[i];
        board.pins[pin].analogChannel = currentValue;
        if (currentValue !== 127) {
            board.analogPins.push(pin);
        }
        pin++;
    }
    board.emit('analog-mapping-query');
};

/**
 * Handles a I2C_REPLY response and emits the 'I2C-reply-'+n event where n is the slave address of the I2C device.
 * The event is passed the buffer of data sent from the I2C Device
 * @private
 * @param {Board} board the current arduino board we are working with.
 */

SYSEX_RESPONSE[I2C_REPLY] = function (board) {
    var replyBuffer = [];
    var slaveAddress = (board.currentBuffer[2] & 0x7F) | ((board.currentBuffer[3] & 0x7F) << 7);
    var register = (board.currentBuffer[4] & 0x7F) | ((board.currentBuffer[5] & 0x7F) << 7);
    for (var i = 6, length = board.currentBuffer.length - 1; i < length; i += 2) {
        replyBuffer.push(board.currentBuffer[i] | (board.currentBuffer[i + 1] << 7));
    }
    board.emit('I2C-reply-' + slaveAddress, replyBuffer);
};

SYSEX_RESPONSE[ONEWIRE_DATA] = function(board) {
    var subCommand = board.currentBuffer[2];

    if(!SYSEX_RESPONSE[subCommand]) {
        return;
    }

    SYSEX_RESPONSE[subCommand](board);
};

SYSEX_RESPONSE[ONEWIRE_SEARCH_REPLY] = function(board) {
    var pin = board.currentBuffer[3];
    var replyBuffer = board.currentBuffer.slice(4, board.currentBuffer.length -1);

    board.emit('1-wire-search-reply-' + pin, OneWireUtils.readDevices(replyBuffer));
};

SYSEX_RESPONSE[ONEWIRE_SEARCH_ALARMS_REPLY] = function(board) {
    var pin = board.currentBuffer[3];
    var replyBuffer = board.currentBuffer.slice(4, board.currentBuffer.length -1);

    board.emit('1-wire-search-alarms-reply-' + pin, OneWireUtils.readDevices(replyBuffer));
};

SYSEX_RESPONSE[ONEWIRE_READ_REPLY] = function(board) {
    var encoded = board.currentBuffer.slice(4, board.currentBuffer.length -1);
    var decoded = Encoder7Bit.from7BitArray(encoded);
    var correlationId = (decoded[1] << 8) | decoded[0];

    board.emit('1-wire-read-reply-' + correlationId, decoded.slice(2));
};

/**
 * Handles a STRING_DATA response and logs the string to the console.
 * @private
 * @param {Board} board the current arduino board we are working with.
 */

SYSEX_RESPONSE[STRING_DATA] = function (board) {
    var string = new Buffer(board.currentBuffer.slice(2, -1)).toString('utf8').replace(/\0/g, '');
    board.emit('string', string);
};

/**
 * Response from pulseIn
 */

SYSEX_RESPONSE[PULSE_IN] = function (board){
    var pin = (board.currentBuffer[2] & 0x7F) | ((board.currentBuffer[3] & 0x7F) << 7);
    var durationBuffer = [
        (board.currentBuffer[4] & 0x7F) | ((board.currentBuffer[5] & 0x7F) << 7),
        (board.currentBuffer[6] & 0x7F) | ((board.currentBuffer[7] & 0x7F) << 7),
        (board.currentBuffer[8] & 0x7F) | ((board.currentBuffer[9] & 0x7F) << 7),
        (board.currentBuffer[10] & 0x7F) | ((board.currentBuffer[11] & 0x7F) << 7)
    ];
    var duration = ( (durationBuffer[0] << 24) +
                     (durationBuffer[1] << 16) +
                     (durationBuffer[2] << 8) +
                     (durationBuffer[3] ) );
    board.emit('pulse-in-'+pin,duration);
};

/**
 * Handles the message from a stepper completing move
 * @param {Board} board
 */

SYSEX_RESPONSE[STEPPER] = function (board) {
    var deviceNum = board.currentBuffer[2];
    board.emit('stepper-done-'+deviceNum, true);
};

/**
 * @class The Board object represents an arduino board.
 * @augments EventEmitter
 * @param {String} port This is the serial port the arduino is connected to.
 * @param {function} function A function to be called when the arduino is ready to communicate.
 * @property MODES All the modes available for pins on this arduino board.
 * @property I2C_MODES All the I2C modes available.
 * @property HIGH A constant to set a pins value to HIGH when the pin is set to an output.
 * @property LOW A constant to set a pins value to LOW when the pin is set to an output.
 * @property pins An array of pin object literals.
 * @property analogPins An array of analog pins and their corresponding indexes in the pins array.
 * @property version An object indicating the major and minor version of the firmware currently running.
 * @property firmware An object indicateon the name, major and minor version of the firmware currently running.
 * @property currentBuffer An array holding the current bytes received from the arduino.
 * @property {SerialPort} sp The serial port object used to communicate with the arduino.
 */
var Board = function(port, options, callback) {
    events.EventEmitter.call(this);
    if (typeof options === 'function' || typeof options === 'undefined') {
        callback = options;
        options = {
            reportVersionTimeout: 5000
        };
    }
    var board = this;
    this.MODES = {
        INPUT: 0x00,
        OUTPUT: 0x01,
        ANALOG: 0x02,
        PWM: 0x03,
        SERVO: 0x04,
        SHIFT: 0x05,
        I2C: 0x06,
        ONEWIRE: 0x07,
        STEPPER: 0x08,
        IGNORE: 0x7F,
        UNKOWN: 0x10
    };

    this.I2C_MODES = {
        WRITE: 0x00,
        READ: 1,
        CONTINUOUS_READ: 2,
        STOP_READING: 3
    };

    this.STEPPER = {
        TYPE: {
            DRIVER: 1,
            TWO_WIRE: 2,
            FOUR_WIRE: 4
        },
        RUNSTATE: {
            STOP: 0,
            ACCEL: 1,
            DECEL: 2,
            RUN: 3
        },
        DIRECTION: {
            CCW: 0,
            CW: 1
        }
    };

    this.HIGH = 1;
    this.LOW = 0;
    this.pins = [];
    this.analogPins = [];
    this.version = {};
    this.firmware = {};
    this.currentBuffer = [];
    this.versionReceived = false;

    if(typeof port === 'object'){
        this.sp = port;
    } else {
        this.sp = new SerialPort(port, {
            baudrate: 57600,
            buffersize: 1
        });
    }

    this.sp.on('error', function(string) {
        if (typeof callback === 'function') {
            callback(string);
        }
    });

    this.sp.on('data', function(data) {
        var byt, cmd;

        if (!board.versionReceived && data[0] !== REPORT_VERSION) {
            return;
        } else {
            board.versionReceived = true;
        }

        for (var i = 0; i < data.length; i++) {
            byt = data[i];
            // we dont want to push 0 as the first byte on our buffer
            if (board.currentBuffer.length === 0 && byt === 0) {
                continue;
            } else {
                board.currentBuffer.push(byt);

                // [START_SYSEX, ... END_SYSEX]
                if (board.currentBuffer[0] === START_SYSEX &&
                    SYSEX_RESPONSE[board.currentBuffer[1]] &&
                    board.currentBuffer[board.currentBuffer.length - 1] === END_SYSEX) {

                    SYSEX_RESPONSE[board.currentBuffer[1]](board);
                    board.currentBuffer.length = 0;
                }

                // Check if data gets out of sync (first byte in buffer must be a valid command if not START_SYSEX)
                else if (board.currentBuffer[0] !== START_SYSEX) {
                    // Identify command on first byte
                    cmd = board.currentBuffer[0] < 240 ? board.currentBuffer[0] & 0xF0 : board.currentBuffer[0];

                    // Check if it is not a valid command
                    if (cmd !== REPORT_VERSION && cmd !== ANALOG_MESSAGE && cmd !== DIGITAL_MESSAGE) {
                        // console.log("OUT OF SYNC - CMD: "+cmd);
                        // Clean buffer
                        board.currentBuffer.length = 0;
                    }
                }

                // There are 3 bytes in the buffer and the first is not START_SYSEX:
                // Might have a MIDI Command
                if (board.currentBuffer.length === 3 && board.currentBuffer[0] !== START_SYSEX) {
                    //commands under 0xF0 we have a multi byte command
                    if (board.currentBuffer[0] < 240) {
                        cmd = board.currentBuffer[0] & 0xF0;
                    } else {
                        cmd = board.currentBuffer[0];
                    }

                    if (MIDI_RESPONSE[cmd]) {
                        MIDI_RESPONSE[cmd](board);
                        board.currentBuffer.length = 0;
                    } else {
                        // A bad serial read must have happened.
                        // Reseting the buffer will allow recovery.
                        board.currentBuffer.length = 0;
                    }
                }
            }
        }
    });
    // if we have not received the version in the timeout  ask for it
    this.reportVersionTimeoutId = setTimeout(function () {
        if (this.versionReceived === false) {
            this.reportVersion(function () {});
            this.queryFirmware(function () {});
        }
    }.bind(this), options.reportVersionTimeout);
    board.once('reportversion', function () {
        clearTimeout(board.reportVersionTimeoutId);
        board.versionReceived = true;
        board.once('queryfirmware', function () {
            if(options.skipCapabilities) {
                board.emit('ready');
                if (typeof callback === 'function') {
                    callback();
                }
                return;
            }
            board.queryCapabilities(function() {
                board.queryAnalogMapping(function() {
                    board.emit('ready');
                    if(typeof callback === 'function') {
                        callback();
                    }
                });
            });
        });
    });
};

util.inherits(Board, events.EventEmitter);

/**
 * Asks the arduino to tell us its version.
 * @param {function} callback A function to be called when the arduino has reported its version.
 */

Board.prototype.reportVersion = function(callback) {
    this.once('reportversion', callback);
    this.sp.write(new Buffer([REPORT_VERSION]));
};

/**
 * Asks the arduino to tell us its firmware version.
 * @param {function} callback A function to be called when the arduino has reported its firmware version.
 */

Board.prototype.queryFirmware = function (callback) {
    this.once('queryfirmware', callback);
    this.sp.write(new Buffer([START_SYSEX, QUERY_FIRMWARE, END_SYSEX]));
};

/**
 * Asks the arduino to read analog data.
 * @param {number} pin The pin to read analog data
 * @param {function} callback A function to call when we have the analag data.
 */

Board.prototype.analogRead = function (pin, callback) {
    this.addListener('analog-read-' + pin, callback);
};

/**
 * Asks the arduino to write an analog message.
 * @param {number} pin The pin to write analog data to.
 * @param {nubmer} value The data to write to the pin between 0 and 255.
 */

Board.prototype.analogWrite = function (pin, value) {
    var data = [];

    this.pins[pin].value = value;

    if (pin > 15) {
        data[0] = START_SYSEX;
        data[1] = EXTENDED_ANALOG;
        data[2] = pin;
        data[3] = value & 0x7F;
        data[4] = (value >> 7) & 0x7F;

        if (value > 0x00004000) {
            data[data.length] = (value >> 14) & 0x7F;
        }

        if (value > 0x00200000) {
            data[data.length] = (value >> 21) & 0x7F;
        }

        if (value > 0x10000000) {
            data[data.length] = (value >> 28) & 0x7F;
        }

        data[data.length] = END_SYSEX;
    } else {
        data.push(ANALOG_MESSAGE | pin, value & 0x7F, (value >> 7) & 0x7F);
    }

    this.sp.write(new Buffer(data));
};

/**
 * Asks the arduino to move a servo
 * @param {number} pin The pin the servo is connected to
 * @param {number} value The degrees to move the servo to.
 */

Board.prototype.servoWrite = function (pin, value) {
    this.analogWrite.apply(this, arguments);
};

/**
 * Asks the arduino to set the pin to a certain mode.
 * @param {number} pin The pin you want to change the mode of.
 * @param {number} mode The mode you want to set. Must be one of board.MODES
 */

Board.prototype.pinMode = function (pin, mode) {
    this.pins[pin].mode = mode;
    this.sp.write(new Buffer([PIN_MODE, pin, mode]));
};

/**
 * Asks the arduino to write a value to a digital pin
 * @param {number} pin The pin you want to write a value to.
 * @param {value} value The value you want to write. Must be board.HIGH or board.LOW
 */

Board.prototype.digitalWrite = function (pin, value) {
    var port = Math.floor(pin / 8);
    var portValue = 0;
    this.pins[pin].value = value;
    for (var i = 0; i < 8; i++) {
        if (this.pins[8 * port + i]) {
            if (this.pins[8 * port + i].value) {
                portValue |= (1 << i);
            }
        }
    }
    this.sp.write(new Buffer([DIGITAL_MESSAGE | port, portValue & 0x7F, (portValue >> 7) & 0x7F]));
};

/**
 * Asks the arduino to read digital data
 * @param {number} pin The pin to read data from
 * @param {function} callback The function to call when data has been received
 */

Board.prototype.digitalRead = function (pin, callback) {
    this.addListener('digital-read-' + pin, callback);
};

/**
 * Asks the arduino to tell us its capabilities
 * @param {function} callback A function to call when we receive the capabilities
 */

Board.prototype.queryCapabilities = function(callback) {
    this.once('capability-query', callback);
    this.sp.write(new Buffer([START_SYSEX, CAPABILITY_QUERY, END_SYSEX]));
};

/**
 * Asks the arduino to tell us its analog pin mapping
 * @param {function} callback A function to call when we receive the pin mappings.
 */

Board.prototype.queryAnalogMapping = function (callback) {
    this.once('analog-mapping-query', callback);
    this.sp.write(new Buffer([START_SYSEX, ANALOG_MAPPING_QUERY, END_SYSEX]));
};

/**
 * Asks the arduino to tell us the current state of a pin
 * @param {number} pin The pin we want to the know the state of
 * @param {function} callback A function to call when we receive the pin state.
 */

Board.prototype.queryPinState = function (pin, callback) {
    this.once('pin-state-' + pin, callback);
    this.sp.write(new Buffer([START_SYSEX, PIN_STATE_QUERY, pin, END_SYSEX]));
};

/**
 * Sends a I2C config request to the arduino board with an optional
 * value in microseconds to delay an I2C Read.  Must be called before
 * an I2C Read or Write
 * @param {number} delay in microseconds to set for I2C Read
 */

Board.prototype.sendI2CConfig = function(delay){
    delay = delay || 0;
    this.sp.write(new Buffer([START_SYSEX,I2C_CONFIG,(delay & 0xFF),((delay >> 8) & 0xFF),END_SYSEX]));
};

/**
 * Sends a string to the arduino
 * @param {String} string to send to the device
 */

Board.prototype.sendString = function(string) {
    var bytes = new Buffer(string + '\0', 'utf8');
    var data = [];
    data.push(START_SYSEX);
    data.push(STRING_DATA);
    for (var i = 0, length = bytes.length; i < length; i++) {
        data.push(bytes[i] & 0x7F);
        data.push((bytes[i] >> 7) & 0x7F);
    }
    data.push(END_SYSEX);
    this.sp.write(data);
};

/**
 * Asks the arduino to send an I2C request to a device
 * @param {number} slaveAddress The address of the I2C device
 * @param {Array} bytes The bytes to send to the device
 */

Board.prototype.sendI2CWriteRequest = function (slaveAddress, bytes) {
    var data = [];
    bytes = bytes || [];
    data.push(START_SYSEX);
    data.push(I2C_REQUEST);
    data.push(slaveAddress);
    data.push(this.I2C_MODES.WRITE << 3);
    for (var i = 0, length = bytes.length; i < length; i++) {
        data.push(bytes[i] & 0x7F);
        data.push((bytes[i] >> 7) & 0x7F);
    }
    data.push(END_SYSEX);
    this.sp.write(new Buffer(data));
};

/**
 * Asks the arduino to request bytes from an I2C device
 * @param {number} slaveAddress The address of the I2C device
 * @param {number} numBytes The number of bytes to receive.
 * @param {function} callback A function to call when we have received the bytes.
 */

Board.prototype.sendI2CReadRequest = function (slaveAddress, numBytes, callback) {
    this.sp.write(new Buffer([START_SYSEX, I2C_REQUEST, slaveAddress, this.I2C_MODES.READ << 3, numBytes & 0x7F, (numBytes >> 7) & 0x7F, END_SYSEX]));
    this.once('I2C-reply-' + slaveAddress, callback);
};

/**
 * Configure the passed pin as the controller in a 1-wire bus.
 * Pass as enableParasiticPower true if you want the data pin to power the bus.
 * @param pin
 * @param enableParasiticPower
 */
Board.prototype.sendOneWireConfig = function(pin, enableParasiticPower) {
    this.sp.write(new Buffer([START_SYSEX, ONEWIRE_DATA, ONEWIRE_CONFIG_REQUEST, pin, enableParasiticPower ? 0x01 : 0x00, END_SYSEX]));
};

/**
 * Searches for 1-wire devices on the bus.  The passed callback should accept
 * and error argument and an array of device identifiers.
 * @param pin
 * @param callback
 */
Board.prototype.sendOneWireSearch = function(pin, callback) {
    this._sendOneWireSearch(ONEWIRE_SEARCH_REQUEST, '1-wire-search-reply-' + pin, pin, callback);
};

/**
 * Searches for 1-wire devices on the bus in an alarmed state.  The passed callback
 * should accept and error argument and an array of device identifiers.
 * @param pin
 * @param callback
 */
Board.prototype.sendOneWireAlarmsSearch = function(pin, callback) {
    this._sendOneWireSearch(ONEWIRE_SEARCH_ALARMS_REQUEST, '1-wire-search-alarms-reply-' + pin, pin, callback);
};

Board.prototype._sendOneWireSearch = function(type, event, pin, callback) {
    this.sp.write(new Buffer([START_SYSEX, ONEWIRE_DATA, type, pin, END_SYSEX]));

    var searchTimeout = setTimeout(function() {
        callback(new Error("1-Wire device search timeout - are you running ConfigurableFirmata?"));
    }, 5000);
    this.once(event, function(devices) {
        clearTimeout(searchTimeout);

        callback(null, devices);
    });
};

/**
 * Reads data from a device on the bus and invokes the passed callback.
 *
 * N.b. ConfigurableFirmata will issue the 1-wire select command internally.
 * @param pin
 * @param device
 * @param numBytesToRead
 * @param callback
 */
Board.prototype.sendOneWireRead = function(pin, device, numBytesToRead, callback) {
    var correlationId = Math.floor(Math.random() * 255);
    var readTimeout = setTimeout(function() {
        callback(new Error("1-Wire device read timeout - are you running ConfigurableFirmata?"));
    }, 5000);
    this._sendOneWireRequest(pin, ONEWIRE_READ_REQUEST_BIT, device, numBytesToRead, correlationId, null, null, '1-wire-read-reply-' + correlationId, function(data) {
        clearTimeout(readTimeout);

        callback(null, data);
    });
};

/**
 * Resets all devices on the bus.
 * @param pin
 */
Board.prototype.sendOneWireReset = function(pin) {
    this._sendOneWireRequest(pin, ONEWIRE_RESET_REQUEST_BIT);
};

/**
 * Writes data to the bus to be received by the passed device.  The device
 * should be obtained from a previous call to sendOneWireSearch.
 *
 * N.b. ConfigurableFirmata will issue the 1-wire select command internally.
 * @param pin
 * @param device
 * @param data
 */
Board.prototype.sendOneWireWrite = function(pin, device, data) {
    this._sendOneWireRequest(pin, ONEWIRE_WRITE_REQUEST_BIT, device, null, null, null, Array.isArray(data) ? data : [data]);
};

/**
 * Tells firmata to not do anything for the passed amount of ms.  For when you
 * need to give a device attached to the bus time to do a calculation.
 * @param pin
 */
Board.prototype.sendOneWireDelay = function(pin, delay) {
    this._sendOneWireRequest(pin, ONEWIRE_DELAY_REQUEST_BIT, null, null, null, delay);
};

/**
 * Sends the passed data to the passed device on the bus, reads the specified
 * number of bytes and invokes the passed callback.
 *
 * N.b. ConfigurableFirmata will issue the 1-wire select command internally.
 * @param pin
 * @param device
 * @param data
 * @param numBytesToRead
 * @param callback
 */
Board.prototype.sendOneWireWriteAndRead = function(pin, device, data, numBytesToRead, callback) {
    var correlationId = Math.floor(Math.random() * 255);
    var readTimeout = setTimeout(function() {
        callback(new Error("1-Wire device read timeout - are you running ConfigurableFirmata?"));
    }, 5000);
    this._sendOneWireRequest(pin, ONEWIRE_WRITE_REQUEST_BIT | ONEWIRE_READ_REQUEST_BIT, device, numBytesToRead, correlationId, null, Array.isArray(data) ? data : [data], '1-wire-read-reply-' + correlationId, function(data) {
        clearTimeout(readTimeout);

        callback(null, data);
    });
};

// see http://firmata.org/wiki/Proposals#OneWire_Proposal
Board.prototype._sendOneWireRequest = function(pin, subcommand, device, numBytesToRead, correlationId, delay, dataToWrite, event, callback) {
    var bytes = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

    if(device || numBytesToRead || correlationId || delay || dataToWrite) {
        subcommand = subcommand | ONEWIRE_WITHDATA_REQUEST_BITS;
    }

    if(device) {
        bytes.splice.apply(bytes, [0, 8].concat(device));
    }

    if(numBytesToRead) {
        bytes[8] = numBytesToRead & 0xFF;
        bytes[9] = (numBytesToRead >> 8) & 0xFF;
    }

    if(correlationId) {
        bytes[10] = correlationId & 0xFF;
        bytes[11] = (correlationId >> 8) & 0xFF;
    }

    if(delay) {
        bytes[12] = delay & 0xFF;
        bytes[13] = (delay >> 8) & 0xFF;
        bytes[14] = (delay >> 16) & 0xFF;
        bytes[15] = (delay >> 24) & 0xFF;
    }

    if(dataToWrite) {
        dataToWrite.forEach(function(byte) {
            bytes.push(byte);
        });
    }

    var output = [START_SYSEX, ONEWIRE_DATA, subcommand, pin];
    output = output.concat(Encoder7Bit.to7BitArray(bytes));
    output.push(END_SYSEX);

    this.sp.write(new Buffer(output));

    if(event && callback) {
        this.once(event, callback);
    }
};

/**
 * Set sampling interval in millis. Default is 19 ms
 * @param {number} interval The sampling interval in ms > 10
 */

Board.prototype.setSamplingInterval = function (interval) {
    var safeint = interval < 10 ? 10 : (interval > 65535 ? 65535 : interval); // constrained
    this.sp.write(new Buffer([START_SYSEX, SAMPLING_INTERVAL, (safeint & 0xFF),((safeint >> 8) & 0xFF), END_SYSEX]));
};

/**
 * Set reporting on pin
 * @param {number} pin The pin to turn on/off reporting
 * @param {number} value Binary value to turn reporting on/off
 */

Board.prototype.reportAnalogPin = function (pin, value) {
    if(value === 0 || value === 1) {
        this.pins[this.analogPins[pin]].report = value;
        this.sp.write(new Buffer([REPORT_ANALOG | pin, value]));
    }
};

/**
 * Set reporting on pin
 * @param {number} pin The pin to turn on/off reporting
 * @param {number} value Binary value to turn reporting on/off
 */

Board.prototype.reportDigitalPin = function (pin, value) {
    if(value === 0 || value === 1) {
        this.pins[pin].report = value;
        this.sp.write(new Buffer([REPORT_DIGITAL | pin, value]));
    }
};

/**
 *
 *
 */

Board.prototype.pulseIn = function (opts, callback) {
    var pin = opts.pin;
    var value = opts.value;
    var pulseOut = opts.pulseOut || 0;
    var timeout = opts.timeout || 1000000;
    var pulseOutArray = [
        ((pulseOut >> 24) & 0xFF),
        ((pulseOut >> 16) & 0xFF),
        ((pulseOut >> 8) & 0XFF),
        ((pulseOut & 0xFF))
    ];
    var timeoutArray = [
        ((timeout >> 24) & 0xFF),
        ((timeout >> 16) & 0xFF),
        ((timeout >> 8) & 0XFF),
        ((timeout & 0xFF))
    ];
    var data = [
        START_SYSEX,
        PULSE_IN,
        pin,
        value,
        pulseOutArray[0] & 0x7F,
        (pulseOutArray[0] >> 7) & 0x7F,
        pulseOutArray[1] & 0x7F,
        (pulseOutArray[1] >> 7) & 0x7F,
        pulseOutArray[2] & 0x7F,
        (pulseOutArray[2] >> 7) & 0x7F,
        pulseOutArray[3] & 0x7F,
        (pulseOutArray[3] >> 7) & 0x7F,
        timeoutArray[0] & 0x7F,
        (timeoutArray[0] >> 7) & 0x7F,
        timeoutArray[1] & 0x7F,
        (timeoutArray[1] >> 7) & 0x7F,
        timeoutArray[2] & 0x7F,
        (timeoutArray[2] >> 7) & 0x7F,
        timeoutArray[3] & 0x7F,
        (timeoutArray[3] >> 7) & 0x7F,
        END_SYSEX
    ];
    this.sp.write(new Buffer(data));
    this.once('pulse-in-' + pin,callback);
};

/**
 * Stepper functions to support AdvancedFirmata's asynchronous control of stepper motors
 * https://github.com/soundanalogous/AdvancedFirmata
 */

/**
 * Asks the arduino to configure a stepper motor with the given config to allow asynchronous control of the stepper
 * @param {number} deviceNum Device number for the stepper (range 0-5, expects steppers to be setup in order from 0 to 5)
 * @param {number} type One of this.STEPPER.TYPE.*
 * @param {number} stepsPerRev Number of steps motor takes to make one revolution
 * @param {number} dirOrMotor1Pin If using EasyDriver type stepper driver, this is direction pin, otherwise it is motor 1 pin
 * @param {number} stepOrMotor2Pin If using EasyDriver type stepper driver, this is step pin, otherwise it is motor 2 pin
 * @param {number} [motor3Pin] Only required if type == this.STEPPER.TYPE.FOUR_WIRE
 * @param {number} [motor4Pin] Only required if type == this.STEPPER.TYPE.FOUR_WIRE
 */

Board.prototype.stepperConfig = function (deviceNum, type, stepsPerRev, dirOrMotor1Pin, stepOrMotor2Pin, motor3Pin, motor4Pin) {
    var data = [
        START_SYSEX,
        STEPPER,
        0x00,       // STEPPER_CONFIG from firmware
        deviceNum,
        type,
        stepsPerRev & 0x7F,
        (stepsPerRev >> 7) & 0x7F,
        dirOrMotor1Pin,
        stepOrMotor2Pin
    ];
    if(type === this.STEPPER.TYPE.FOUR_WIRE) {
        data.push(motor3Pin, motor4Pin);
    }
    data.push(END_SYSEX);
    this.sp.write(new Buffer(data));
};

/**
 * Asks the arduino to move a stepper a number of steps at a specific speed
 * (and optionally with and acceleration and deceleration)
 * speed is in units of .01 rad/sec
 * accel and decel are in units of .01 rad/sec^2
 * TODO: verify the units of speed, accel, and decel
 * @param {number} deviceNum Device number for the stepper (range 0-5)
 * @param {number} direction One of this.STEPPER.DIRECTION.*
 * @param {number} steps Number of steps to make
 * @param {number} speed
 * @param {number|function} accel Acceleration or if accel and decel are not used, then it can be the callback
 * @param {number} [decel]
 * @param {function} [callback]
 */

Board.prototype.stepperStep = function (deviceNum, direction, steps, speed, accel, decel, callback) {
    if (typeof accel === 'function') {
        callback = accel;
        accel = 0;
        decel = 0;
    }

    var data = [
        START_SYSEX,
        STEPPER,
        0x01,       // STEPPER_STEP from firmware
        deviceNum,
        direction,  // one of this.STEPPER.DIRECTION.*
        steps & 0x7F,
        (steps >> 7) & 0x7F,
        (steps >> 14) & 0x7f,
        speed & 0x7F,
        (speed >> 7) & 0x7F
    ];
    if(accel > 0 || decel > 0) {
        data.push(
            accel & 0x7F,
            (accel >> 7) & 0x7F,
            decel & 0x7F,
            (decel >> 7) & 0x7F
        );
    }
    data.push(END_SYSEX);
    this.sp.write(new Buffer(data));
    this.once('stepper-done-'+deviceNum, callback);
};

/**
 * Send SYSTEM_RESET to arduino
 */

Board.prototype.reset = function () {
    this.sp.write(new Buffer([SYSTEM_RESET]));
};

module.exports = {
    Board: Board,
    SYSEX_RESPONSE: SYSEX_RESPONSE,
    MIDI_RESPONSE: MIDI_RESPONSE
};


text:
package org.elasticsearch.action.admin.indices.rollover;

import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.test.ESTestCase;

import java.util.Set;

import static org.hamcrest.Matchers.equalTo;

public class RolloverRequestTests extends ESTestCase {

    public void testConditionsParsing() throws Exception {
        final RolloverRequest request = new RolloverRequest(randomAlphaOfLength(10), randomAlphaOfLength(10));
        final XContentBuilder builder = XContentFactory.jsonBuilder()
            .startObject()
                .startObject("conditions")
                    .field("max_age", "10d")
                    .field("max_docs", 100)
                .endObject()
            .endObject();
        RolloverRequest.PARSER.parse(createParser(builder), request, null);
        Set<Condition> conditions = request.getConditions();
        assertThat(conditions.size(), equalTo(2));
        for (Condition condition : conditions) {
            if (condition instanceof MaxAgeCondition) {
                MaxAgeCondition maxAgeCondition = (MaxAgeCondition) condition;
                assertThat(maxAgeCondition.value.getMillis(), equalTo(TimeValue.timeValueHours(24 * 10).getMillis()));
            } else if (condition instanceof MaxDocsCondition) {
                MaxDocsCondition maxDocsCondition = (MaxDocsCondition) condition;
                assertThat(maxDocsCondition.value, equalTo(100L));
            } else {
                fail("unexpected condition " + condition);
            }
        }
    }

    public void testParsingWithIndexSettings() throws Exception {
        final RolloverRequest request = new RolloverRequest(randomAlphaOfLength(10), randomAlphaOfLength(10));
        final XContentBuilder builder = XContentFactory.jsonBuilder()
            .startObject()
                .startObject("conditions")
                    .field("max_age", "10d")
                    .field("max_docs", 100)
                .endObject()
                .startObject("mappings")
                    .startObject("type1")
                        .startObject("properties")
                            .startObject("field1")
                                .field("type", "string")
                                .field("index", "not_analyzed")
                            .endObject()
                        .endObject()
                    .endObject()
                .endObject()
                .startObject("settings")
                    .field("number_of_shards", 10)
                .endObject()
                .startObject("aliases")
                    .startObject("alias1").endObject()
                .endObject()
            .endObject();
        RolloverRequest.PARSER.parse(createParser(builder), request, null);
        Set<Condition> conditions = request.getConditions();
        assertThat(conditions.size(), equalTo(2));
        assertThat(request.getCreateIndexRequest().mappings().size(), equalTo(1));
        assertThat(request.getCreateIndexRequest().aliases().size(), equalTo(1));
        assertThat(request.getCreateIndexRequest().settings().getAsInt("number_of_shards", 0), equalTo(10));
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.flipkart.hydra.composer.exception;

public class ComposerInstantiationException extends Exception {

    public ComposerInstantiationException() {
        super();
    }

    public ComposerInstantiationException(String message) {
        super(message);
    }

    public ComposerInstantiationException(String message, Throwable cause) {
        super(message, cause);
    }

    public ComposerInstantiationException(Throwable cause) {
        super(cause);
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Revis. gen. pl. (Leipzig) 3: 446 (1898)

#### Original name
Dasyscyphus variegatus Fuckel, 1874

### Remarks
null


text:
<!DOCTYPE html>

        <meta charset="utf-8"/>
        <title>jsBind · Tabs Example</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
        <meta name="description" content=""/>
        <meta name="author" content="Ben Voss"/>

        <link href="css/bootstrap.css" rel="stylesheet"/>

        <link href="css/bootstrap-responsive.css" rel="stylesheet"/>

Tab 1

Tab 2

Tab 3


text:
module GeographyClient
  VERSION = "0.0.1"
end


text:
<?php

namespace Ekyna\Component\Commerce\Invoice\Model;

/**
 * Interface InvoiceSubjectInterface
 * @package Ekyna\Component\Commerce\Invoice\Model
 * @author  Etienne Dauvergne <contact@ekyna.com>
 */
interface InvoiceSubjectInterface
{
    /**
     * Returns the invoice total.
     *
     * @return float
     */
    public function getInvoiceTotal();

    /**
     * Sets the invoice total.
     *
     * @param float $total
     *
     * @return InvoiceSubjectTrait
     */
    public function setInvoiceTotal($total);

    /**
     * Returns the credits total.
     *
     * @return float
     */
    public function getCreditTotal();

    /**
     * Sets the credit total.
     *
     * @param float $total
     *
     * @return $this|InvoiceSubjectInterface
     */
    public function setCreditTotal($total);

    /**
     * Returns the invoice state.
     *
     * @return string
     */
    public function getInvoiceState();

    /**
     * Sets the invoice state.
     *
     * @param string $state
     *
     * @return $this|InvoiceSubjectInterface
     */
    public function setInvoiceState($state);

    /**
     * Returns whether the order has invoices or not.
     *
     * @return bool
     */
    public function hasInvoices();

    /**
     * Returns the invoices.
     *
     * @param bool $filter TRUE for invoices, FALSE for credits, NULL for all
     *
     * @return \Doctrine\Common\Collections\Collection|InvoiceInterface[]
     */
    public function getInvoices($filter = null);

    /**
     * Returns whether the order has the invoice or not.
     *
     * @param InvoiceInterface $invoice
     *
     * @return bool
     */
    public function hasInvoice(InvoiceInterface $invoice);

    /**
     * Adds the invoice.
     *
     * @param InvoiceInterface $invoice
     *
     * @return $this|InvoiceSubjectInterface
     */
    public function addInvoice(InvoiceInterface $invoice);

    /**
     * Removes the invoice.
     *
     * @param InvoiceInterface $invoice
     *
     * @return $this|InvoiceSubjectInterface
     */
    public function removeInvoice(InvoiceInterface $invoice);

    /**
     * Returns the invoice date.
     *
     * @param bool $latest Whether to return the last invoice date instead of the first.
     *
     * @return \DateTime|null
     */
    public function getInvoicedAt($latest = false);

    /**
     * Returns whether the sale has been fully invoiced (ignoring credits).
     *
     * @return bool
     */
    public function isFullyInvoiced(): bool;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EmptyKeys.UserInterface.Data;
using EmptyKeys.UserInterface.Input;
using EmptyKeys.UserInterface.Mvvm;

namespace GameData
{
    public class CustomWindow : WindowViewModel
    {
        private string textData;

        public string TextData
        {
            get { return textData; }
            set { SetProperty(ref textData, value); }
        }

        private ICommand hideCommand;

        public ICommand HideCommand
        {
            get { return hideCommand; }
            set { hideCommand = value; }
        }

        public CustomWindow()
            : base("CustomWindowTemplate")
        {
            TextData = "Custom Window";

            Top = 10;
            Left = 700;
            Height = 100;
            Width = 200;
            MinHeight = 100;
            MinWidth = 200;
            Opacity = 0.9f;
            IsHitTestVisible = true;
            IsOnTop = true;
            Title = "Title";
            IsVisible = true;
            CanResize = true;

            HideCommand = new RelayCommand(new Action<object>(OnHide));

            GeneratedPropertyInfo.RegisterGeneratedProperty(this.GetType(), "ManualBinding", typeof(ManualBindingProperty));
        }

        private void OnHide(object obj)
        {
            IsVisible = false;
        }
    }
}


text:
package erjang;

/**
 * Used in erlang when an thread receives an untrapped exit signal
 */
public class ErlangExitSignal extends Error {

	private final EObject exitReason;

	/**
	 * @param exitReason
	 */
	public ErlangExitSignal(EObject exitReason, Throwable killer) {
		super(killer);
		this.exitReason = exitReason;
	}

	/**
	 * @return
	 */
	public EObject reason() {
		return exitReason;
	}

	/* (non-Javadoc)
	 * @see java.lang.Throwable#getMessage()
	 */
	@Override
	public String getMessage() {
		return exitReason.toString();
	}
}


text:
package com.nhl.link.rest.it.fixture.cayenne;

import com.nhl.link.rest.it.fixture.cayenne.auto._Datamap;

public class Datamap extends _Datamap {

    private static Datamap instance;

    private Datamap() {}

    public static Datamap getInstance() {
        if(instance == null) {
            instance = new Datamap();
        }

        return instance;
    }
}


text:
package com.cloudibpm.eso.om.organization;

import com.cloudibpm.core.officecalendar.Holiday;
import com.cloudibpm.core.officecalendar.OfficeCalendar;
import com.cloudibpm.core.officecalendar.OfficeDay;
import com.cloudibpm.core.officecalendar.OfficeHours;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Titel: 标题
 * @Description: 日历操作类
 * @Author: 作者
 * @CreateDate: 2019/4/15 11:22
 * @Version: 1.0
 */
@Repository
public class CalenderEso {

    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public CalenderEso(JdbcTemplate jdbcTemplate){
        this.jdbcTemplate = jdbcTemplate;
    }

    /**
     * 创建一个日历
     *
     * @param calender
     */
    public int addCalender(OfficeCalendar calender) {
        String sql = "insert into om_office_calendar (Pk_Calendar,CalendarName,DefaultCalendar,Fk_Parent,Fk_Owner ) " +
                "values(?,?,?,?,?)";
        return jdbcTemplate.update(sql,calender.getId(),calender.getName(),calender.isDefault(),
                calender.getParent(),calender.getOwner());
    }

    /**
     * 根据组织ID 查询所有日历
     * @param oid
     * @return
     */
    public List<OfficeCalendar> queryAllCalender(String oid){
        String sql = "select * from om_office_calendar where Fk_Owner = ?";
        return jdbcTemplate.query(sql, new Object[]{ oid},
                (resultSet, i) -> getOfficeCalender(resultSet, new OfficeCalendar()));
    }

    /**
     * 设置某一天是否是假期  2019-09-10 是周几,今天是假期
     *
     * @param holiday
     */
    public int setIsHoliday(Holiday holiday) {
        String sql = "insert into om_holiday_arrangement (Pk_Holiday_Arrangement,Holiday,Fk_Parent,Fk_Owner)" +
                "values(?,?,?,?)";
        return jdbcTemplate.update(sql,holiday.getId(),holiday.getHoliday(),
                holiday.getParent(),holiday.getOwner());
    }

    /**
     * 修改某一天是否是假期  2019-09-10 是周几,今天是假期
     *
     * @param holiday
     */
    public int updateIsHoliday(Holiday holiday) {
        String sql = "UPDATE om_holiday_arrangement set IsHoliday = ? where Pk_Holiday_Arrangement = ? and Fk_Parent = ? and Fk_Owner = ?";
        return jdbcTemplate.update(sql,holiday.getIsHoliday(),holiday.getId(),holiday.getParent(),holiday.getOwner());
    }

    /**
     * 设置周一 是否是工作日   周一 是工作日
     *
     * @param officeDay
     */
    public int setYIsWorkDay(OfficeDay officeDay) {
        String sql = "insert into om_office_day (Pk_OfficeDay,Weekday,Working,Fk_Parent,Fk_Owner)" +
                "values(?,?,?,?,?)";
        return jdbcTemplate.update(sql,officeDay.getId(),officeDay.getWeekkDay(),officeDay.getIsWorkDay(),
                officeDay.getParent(),officeDay.getOwner());
    }

    /**
     * 设置周一对应的工作时间段  8:00-12:00
     *
     * @param officeHours
     */
    public int setYPeriod(OfficeHours officeHours) {
        String sql = "insert into om_office_hours (Pk_Tradinghours,FormTime,ToTime,Fk_Parent,Fk_Owner) values (?,?,?,?,?)";
        return jdbcTemplate.update(sql,officeHours.getId(),officeHours.getFromTime(),officeHours.getToTime()
                ,officeHours.getParent(),officeHours.getOwner());
    }

    /**
     * 通过一个日期查询日期表是否存在数据
     * @param date
     * @param oid
     * @return
     */
    public Holiday queryIsHoliday(Date date, String oid){
        String sql = "select * from om_holiday_arrangement where Holiday = ? and Fk_Owner = ?";
        return jdbcTemplate.queryForObject(sql, new Object[]{date, oid},
                (rs, i) -> CalenderEso.this.getHolidad(rs, new Holiday()));
    }

    /**
     *根据周几查询对应OfficeDay
     * @param weekday
     */
    public OfficeDay queryIdByDayOfWeek(int weekday,String parentId,String oid){
        String sql = "select * from om_office_day where Weekday = ? and Fk_Parent = ? and Fk_Owner = ? ";
        return jdbcTemplate.queryForObject(sql, new Object[]{weekday,parentId,oid},
                (rs, i) -> CalenderEso.this.getOfficeDay(rs, new OfficeDay()));
    }

    /**
     * 列出某个日历下星期列表
     * @param parentId
     * @param oid
     * @return
     */
    public List<OfficeDay> getWeekList(String parentId, String oid){
        String sql = "select * from om_office_day where Fk_Parent = ? and Fk_Owner = ?";
        return jdbcTemplate.query(sql, new Object[]{parentId, oid},
                (resultSet, i) -> getOfficeDay(resultSet,new OfficeDay()));
    }

    /**
     * 列出某个公司下假期表数据
     * @param oid
     * @return
     */
    public List<Holiday> getHolidayList(String oid){
        String sql = "select * from om_holiday_arrangement where Fk_Owner = ? order by Holiday DESC";
        return jdbcTemplate.query(sql, new Object[]{ oid},
                (resultSet, i) -> getHolidad(resultSet,new Holiday()));
    }

    /**
     * 删除某公司假期表下的某个数据
     * @param ownerId  组织ID
     * @param date  日期
     * @return
     */
    public void delHoliday(String ownerId, String id) {
        String sql = "Delete from om_holiday_arrangement where Fk_Owner = ? and Pk_Holiday_Arrangement = ?";
        jdbcTemplate.update(sql,ownerId,id);
    }

    /**
     * 条件查询假期表数据
     * @param startTime 开始时间
     * @param toTime    结束时间
     * @param oid
     * @return
     */
    public List<Holiday> searchHoliday(Date startTime, Date toTime, String oid){
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("select * from om_holiday_arrangement where 1=1 ");
        List list = new ArrayList<>();
        if(startTime != null){
            stringBuilder.append(" and Holiday >= ? ");
            list.add(startTime);
        }
        if(toTime != null){
            stringBuilder.append(" and Holiday <= ? ");
            list.add(toTime);
        }
        stringBuilder.append(" and Fk_Owner = ? order by Holiday asc");
        list.add(oid);
        return jdbcTemplate.query(stringBuilder.toString(), list.toArray(),
                (resultSet, i) -> getHolidad(resultSet,new Holiday()));
    }

    /**
     * 查询日历对应的周期   升序 1 - 7
     * @param cid  日历id
     * @param oid
     * @return
     */
    public List<OfficeDay> getCalenderOfficeDay(String cid, String oid){
       String sql = "select * from om_office_day where Fk_Parent = ? and Fk_Owner = ? order by Weekday asc";
       return jdbcTemplate.query(sql,new Object[]{cid, oid},
               ((resultSet, i) -> getOfficeDay(resultSet,new OfficeDay())));
    }

    /**
     * 根据日历周期id  周一id 查询周一对应时间段
     * @param officeDayId  周几id
     * @param oid
     * @return
     */
    public List<OfficeHours> getCalenderOfficeDayHours(String officeDayId, String oid){
        String sql = "select * from om_office_hours where Fk_Parent = ? and Fk_Owner = ? order by FormTime asc";
        return jdbcTemplate.query(sql,new Object[]{officeDayId, oid},
                ((resultSet, i) -> getOfficeHours(resultSet,new OfficeHours())));
    }

    /**
     * 查询日历下周一对应的时间段
     * @param cid  日历id
     * @param oid
     * @return
     */
    public List<OfficeHours> getOnMondayTime(String cid, String oid){
        //1.根据日历id 查询周一id
        String sql = "select * from om_office_day where Weekday = ? and Fk_Parent = ? and Fk_Owner = ?";
        List<OfficeDay> officeDays = jdbcTemplate.query(sql, new Object[]{1, cid, oid},
                ((resultSet, i) -> getOfficeDay(resultSet, new OfficeDay())));
        if(officeDays != null & officeDays.size() > 0){
            //2.根据周一id 查询对应时间段
            sql = "select * from om_office_hours where Fk_Parent = ? and Fk_Owner = ? order by FormTime asc";
            return jdbcTemplate.query(sql,new Object[]{officeDays.get(0).getId(), oid},
                    ((resultSet, i) -> getOfficeHours(resultSet,new OfficeHours())));
        }else {
            return null;
        }
    }

    /**
     * 根据时间段id删除对应时间段
     * @param pid  日时间段id
     */
    public void delPeriod(String pid){
        String sql = "Delete from om_office_hours where Pk_Tradinghours = ? ";
        jdbcTemplate.update(sql,pid);
    }

    /**
     * 重命名日历 根据日历id
     * @param cid  日历id
     * @param cname  日历名字
     * @param oid
     */
    public void renameCalender(String cid,String cname,String oid){
        String sql = "UPDATE om_office_calendar set CalendarName = ? where Pk_Calendar = ? and Fk_Owner = ?";
        jdbcTemplate.update(sql,cname,cid,oid);
    }

    /**
     * 根据日历id 删除日历
     * @param cid  日历id
     * @param oid
     */
    public void delCalender(String cid,String oid){
        String sql = "Delete from om_office_calendar where Pk_Calendar = ? and Fk_Owner = ?";
        jdbcTemplate.update(sql,cid,oid);
    }

    /**
     * 根据日历id 删除对应周期
     * @param cid  日历id
     * @param oid
     */
    public void delOfficeDay(String cid,String oid){
        String sql = "Delete from om_office_day where Fk_Parent = ? and Fk_Owner = ?";
        jdbcTemplate.update(sql,cid,oid);
    }

    /**
     * 根据日历id 删除对应周期
     * @param officeDayId  周期id
     * @param oid
     */
    public void delOfficeHours(String officeDayId,String oid){
        String sql = "Delete from om_office_hours where Fk_Parent = ? and Fk_Owner = ?";
        jdbcTemplate.update(sql,officeDayId,oid);
    }

    /**
     * 查询公司下所有日历
     * @param oid   组织id
     */
    public List<OfficeCalendar> getAllCalender(String oid){
        String sql = "Select * from om_office_calendar where Fk_Owner = ?";
        return jdbcTemplate.query(sql,new Object[]{oid},
                ((resultSet, i) -> getOfficeCalender(resultSet,new OfficeCalendar())));
    }

    //处理结果集  日历
    public OfficeCalendar getOfficeCalender(ResultSet rs,OfficeCalendar officeCalendar) throws SQLException {
        officeCalendar.setId(rs.getString("Pk_Calendar"));
        officeCalendar.setName(rs.getString("CalendarName"));
        officeCalendar.setDefault(rs.getInt("DefaultCalendar"));
        officeCalendar.setParent(rs.getString("Fk_Parent"));
        officeCalendar.setOwner(rs.getString("Fk_Owner"));
        return officeCalendar;
    }

    //处理结果集  周期
    public OfficeDay getOfficeDay(ResultSet rs,OfficeDay officeDay) throws SQLException {
        officeDay.setId(rs.getString("Pk_OfficeDay"));
        officeDay.setWeekkDay(rs.getInt("Weekday"));
        officeDay.setIsWorkDay(rs.getInt("Working"));
        officeDay.setParent(rs.getString("Fk_Parent"));
        officeDay.setOwner(rs.getString("Fk_Owner"));
        return officeDay;
    }

    //处理结果集  假期
    public Holiday getHolidad(ResultSet rs,Holiday holiday)throws SQLException{
        holiday.setId(rs.getString("Pk_Holiday_Arrangement"));
        holiday.setIsHoliday(rs.getInt("IsHoliday"));
        holiday.setHoliday(rs.getDate("Holiday"));
        holiday.setParent(rs.getString("Fk_Parent"));
        holiday.setOwner(rs.getString("Fk_Owner"));
        return holiday;
    }

    //处理结果集  时间段
    public OfficeHours getOfficeHours(ResultSet rs,OfficeHours officeHours)throws SQLException{
        officeHours.setId(rs.getString("Pk_Tradinghours"));
        officeHours.setFromTime(rs.getString("FormTime"));
        officeHours.setToTime(rs.getString("ToTime"));
        officeHours.setParent(rs.getString("Fk_Parent"));
        officeHours.setOwner(rs.getString("Fk_Owner"));
        return officeHours;
    }

}


text:
class RemoveCharLimitFromPspReference < SolidusSupport::Migration[4.2]
  def up
    change_column :adyen_notifications, :psp_reference, :string, limit: nil
  end

  def down
    change_column :adyen_notifications, :psp_reference, :string, limit: 50
  end
end


text:
package org.apache.flink.table.descriptors.python;

import org.apache.flink.annotation.Internal;
import org.apache.flink.table.descriptors.DescriptorProperties;
import org.apache.flink.table.descriptors.FormatDescriptor;

import java.util.Map;

/** Describes the custom format of data. */
@Internal
public class CustomFormatDescriptor extends FormatDescriptor {

    private final DescriptorProperties properties;

    /**
     * Constructs a {@link CustomFormatDescriptor}.
     *
     * @param type String that identifies this format.
     * @param version Property version for backwards compatibility.
     */
    public CustomFormatDescriptor(String type, int version) {
        super(type, version);
        properties = new DescriptorProperties();
    }

    /**
     * Adds a configuration property for the format.
     *
     * @param key The property key to be set.
     * @param value The property value to be set.
     */
    public CustomFormatDescriptor property(String key, String value) {
        properties.putString(key, value);
        return this;
    }

    /**
     * Adds a set of properties for the format.
     *
     * @param properties The properties to add.
     */
    public CustomFormatDescriptor properties(Map<String, String> properties) {
        this.properties.putProperties(properties);
        return this;
    }

    @Override
    protected Map<String, String> toFormatProperties() {
        return properties.asMap();
    }
}


text:
package org.apache.asterix.runtime.base;

import org.apache.asterix.om.types.ATypeTag;
import org.apache.asterix.om.util.container.IObjectFactory;
import org.apache.asterix.runtime.evaluators.common.ListAccessor;

public class ListAccessorFactory implements IObjectFactory<ListAccessor, ATypeTag> {

    @Override
    public ListAccessor create(ATypeTag arg) {
        return new ListAccessor();
    }
}


text:
Tang.setup do |config|
  # config.unauthorized_url = '/users/sign_up'
end


text:
Template.cropUploader.onCreated(function(){
	var template = this;
	_.map(template.data, function(val,key){
		if(['thumbnailWidth', 'thumbnailHeight', 'canvasID', 'thumbnailID','allowURL','hideUpload'].indexOf(key) < 0)
		{
			if(template.addons == undefined) template.addons = {};
			template.addons[key] = val;
		}
	});
	if(CropUploader.debug) console.debug(template.view.name+'.created addons: ', template.addons, template.data);
	template.allowURL = template.data.allowURL === true;
	template.reader = new FileReader();
	template.imagePresent = new ReactiveVar(false);
	template.thumbnailID = template.data.thumbnailID || undefined;
	if(template.thumbnailID == undefined) template.thumbnailID = 'thumbnail_img';
	CropUploader.instance[template.thumbnailID] = template;
	template.processFile = function(file) {
		EXIF.getData(file,function() {
			// this = file
			if(CropUploader.debug) console.info('processFile EXIF',EXIF.pretty(this));
			template.orientation = EXIF.getTag(this,"Orientation");
			template.make = EXIF.getTag(this,"Make");
			//
			// pass our template.thumbnail_img into the reader.onload
			// so we can determine the md5hash
			//
			template.reader.onload = (function(aImg) { return function(e) {
				template.md5hash = MD5(e.target.result);
				console.log(`processFile ${file.name}`);
				// this will trigger image.onload in onRendered
				aImg.src = e.target.result;
				// template.$('input[type="url"]').val();
			}; })(template.thumbnail_img);
			template.reader.readAsDataURL(this);
		});
	}
});
Template.cropUploader.onRendered(function() {
	var template = this;
	template.orientation = 0;
	template.make = '';
	template.md5hash = null;
	template.thumbnailWidth = template.data.thumbnailWidth || undefined;
	template.thumbnailHeight = template.data.thumbnailHeight || undefined;
	template.canvasID = template.data.canvasID || undefined;
	// template.thumbnailID = template.data.thumbnailID || undefined;
	if(template.canvasID == undefined) template.canvasID = 'thumbnail_canvas';
	// if(template.thumbnailID == undefined) template.thumbnailID = 'thumbnail_img';

	if(template.thumbnailHeight == undefined)
		template.thumbnailHeight = 100;
	if(template.thumbnailWidth == undefined)
		template.thumbnailWidth = 100;

	template.preview = template.data.previewID ? template.find('#'+template.data.previewID) : template.find('#preview');

	if(!template.preview)
	{
		if(CropUploader.debug) console.debug('cropUploader added div#preview');
		template.preview = document.createElement('div');
		template.preview.id = 'preview';
		document.body.appendChild(template.preview);
	}

	template.thumbnail_img = template.find('#'+template.thumbnailID);
	if(!template.thumbnail_img)
	{
		if(CropUploader.debug) console.debug('creating #thumbnail_img');
		template.thumbnail_img = document.createElement('img');
		template.thumbnail_img.id = template.thumbnailID;
		template.thumbnail_img.classList.add('hidden');
		template.thumbnail_img.classList.add('thumbnail');
		// template.thumbnail_img.setAttribute('crossOrigin', 'anonymous');
		template.preview.appendChild(template.thumbnail_img);
	}

	template.thumbnailCanvas = template.find('#'+template.canvasID);
	if(!template.thumbnailCanvas)
	{
		template.thumbnailCanvas = document.createElement('canvas');
		template.thumbnailCanvas.id = template.canvasID;
		template.thumbnailCanvas.width = template.data.previewWidth ? template.data.previewWidth : template.thumbnailWidth;
		template.thumbnailCanvas.height = template.data.previewHeight ? template.data.previewHeight : template.thumbnailHeight;
		template.thumbnailCanvas.classList.add('hidden');
		template.thumbnailCanvas.classList.add('preview');
		template.preview.appendChild(template.thumbnailCanvas);
		if(CropUploader.debug) console.debug('created canvas '+template.canvasID);
	}
	// else
	// {
	// 	template.thumbnailCanvas.width = template.data.previewWidth ? template.data.previewWidth : template.thumbnailWidth;
	// 	template.thumbnailCanvas.height = template.data.previewHeight ? template.data.previewHeight : template.thumbnailHeight;
	// }
	//
	// everything will get loaded into the originalCanvas
	//
	template.originalCanvas = template.find('#'+template.canvasID+'_original');
	if(!template.originalCanvas)
	{
		template.originalCanvas = document.createElement('canvas');
		template.originalCanvas.id = template.canvasID+'_original';
		template.originalCanvas.setAttribute('imagePresent', false);
		template.originalCanvas.classList.add('hidden');
		template.preview.appendChild(template.originalCanvas);
		// $('.preview-canvas')[0].appendChild(template.originalCanvas);
		if(CropUploader.debug) console.debug('created canvas '+template.canvasID+'_original');
	}
	//
	// thumbnail_img.onload will handle the thumbnailification and orientation
	//
	template.thumbnail_img.onload = function cropUploaderImageOnload(e) {
	var thumbnail_dataUrl = template.thumbnail_img.src;
	if(CropUploader.debug) console.debug('cropUploaderImageOnload',e);
		var cc = {
			x: 0,
			y: 0,
			width: template.thumbnailCanvas.width,
			height: template.thumbnailCanvas.height
		};
		// console.log('thumbnailping', cc);
		template.originalCanvas.width = template.thumbnail_img.width;
		template.originalCanvas.height = template.thumbnail_img.height;

		template.original_ctx = template.originalCanvas.getContext('2d');
		if ( template.orientation ) {
			var orientation = template.orientation;
			template.original_ctx.save();
			var width  = template.originalCanvas.width;  var styleWidth  = template.originalCanvas.style.width;
			var height = template.originalCanvas.height; var styleHeight = template.originalCanvas.style.height;

		  if (orientation > 4) {
		    template.originalCanvas.width  = height; template.originalCanvas.style.width  = styleHeight;
		    template.originalCanvas.height = width;  template.originalCanvas.style.height = styleWidth;
		  }
		  switch (orientation) {
			  case 2: template.original_ctx.translate(width, 0);     template.original_ctx.scale(-1,1); break;
			  case 3: template.original_ctx.translate(width,height); template.original_ctx.rotate(Math.PI); break;
			  case 4: template.original_ctx.translate(0,height);     template.original_ctx.scale(1,-1); break;
			  case 5: template.original_ctx.rotate(0.5 * Math.PI);   template.original_ctx.scale(1,-1); break;
			  case 6: template.original_ctx.rotate(0.5 * Math.PI);   template.original_ctx.translate(0,-height); break;
			  case 7: template.original_ctx.rotate(0.5 * Math.PI);   template.original_ctx.translate(width,-height); template.original_ctx.scale(-1,1); break;
			  case 8: template.original_ctx.rotate(-0.5 * Math.PI);  template.original_ctx.translate(-width,0); break;
		  }
		}
		template.original_ctx.drawImage(template.thumbnail_img,0,0);
		//
		// check if we want to make it square
		//
		var sWidth = template.originalCanvas.width, sHeight = template.originalCanvas.height;
		//
		// are we requesting a square image
		//
		if(cc.width == cc.height) {
			//
			// make source square
			//
			if(sWidth>sHeight) sWidth=sHeight;
			else sHeight = sWidth;
		} else {
			//
			// make source same aspect ratio as cc (422 x 243) vs (2576 x 1932)
			//
			if(cc.width>cc.height) {
				// horizontal
				var d = cc.width / cc.height;
				sHeight = sHeight / d;
			} else {
				// vertical
				var d = cc.height / cc.width;
				sWidth = sWidth / d;
			}
		}
		//
		// get context for thumbnail
		//
		template.thumbnail_ctx = template.thumbnailCanvas.getContext("2d");
		//
		// resize/crop the adjusted original canvas
		// cc.width/height needs to be adjusted to the ascpect ratio of thumbnailCanvas
		// void ctx.drawImage(image, dx, dy);
		// void ctx.drawImage(image, dx, dy, dWidth, dHeight);
		// void ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);
		//
		template.thumbnail_ctx.drawImage(
			template.originalCanvas,// template.thumbnail_img,
			// source x/y w/h
			0,0,
			sWidth, sHeight,
			// reduce to canvas x/y w/h
			cc.x, cc.y,
			cc.width, cc.height
		);

		if(true || template.addons['previewShow'])
		{
			$('#'+template.thumbnailCanvas.id).trigger('onload');
		}
		// thumbnail_ctx = template.originalCanvas.getContext("2d");
		// thumbnail_ctx.drawImage(template.thumbnail_img,0,0);
		template.originalCanvas.setAttribute('imagePresent', true);
		template.imagePresent.set(true);
		CropUploader.processing.set(false);
	}
});
Template.cropUploader.onDestroyed(function() {
	var template = this;
	// console.log(template.view.name+'.onDestroyed', template);
	delete CropUploader.instance[template.thumbnailID];
	$(template.thumbnailCanvas).remove();
	$(template.originalCanvas).remove();
	$(template.thumbnail_img).remove();
});
Template.cropUploader.events({
	// 'drop input.crop-uploader-file': function(e, template) {
	// 	console.log(e);
	// },
	'change input.crop-uploader-file': function(e, template) {
		template.$('input[type="url"]').val('');
		var file = template.$('input[type="file"]')[0].files[0];
		template.processFile(file);
		// EXIF.getData(file,function() {
		// 	// this = file
		// 	if(CropUploader.debug) console.info(EXIF.pretty(this));
		// 	template.orientation = EXIF.getTag(this,"Orientation");
		// 	template.make = EXIF.getTag(this,"Make");
		// 	//
		// 	// pass our template.thumbnail_img into the reader.onload
		// 	// so we can determine the md5hash
		// 	//
		// 	template.reader.onload = (function(aImg) { return function(e) {
		// 		template.md5hash = MD5(e.target.result);
		// 		// this will trigger image.onload in onRendered
		// 		aImg.src = e.target.result;
		// 		// template.$('input[type="url"]').val();
		// 	}; })(template.thumbnail_img);
		// 	template.reader.readAsDataURL(this);
		// });
	},
	'click button.crop-uploader-reset': function(e,template) {
		template.imagePresent.set(false);
		template.$('#'+template.canvasID).addClass('hidden');
		template.originalCanvas.setAttribute('imagePresent', false);
	},
	'click button.crop-uploader-upload': function(e,template) {
		// use the originalCanvas attribute because we do not want reactivity here
		var imagePresent = template.originalCanvas.getAttribute('imagePresent') == "true";
		var uuid = Random.id();

		e.preventDefault();

		CropUploader.errorMessage.set(null);
		//
		// this is not working because the canvas gets tainted when copying using the URL
		//
		if(imagePresent)
		{
			CropUploader.uploader = new Slingshot.Upload(CropUploader.name, {uuid: uuid });
			var thumbnailCanvas = template.thumbnailCanvas;// template.find('#'+template.canvasID);
			var originalCanvas = template.originalCanvas;
			if( thumbnailCanvas && thumbnailCanvas.toBlob && originalCanvas && originalCanvas.toBlob )
			{
				//
				// first save the blob (thumbnail)
				//
				thumbnailCanvas.toBlob(function(blob) {
					//
					// set the name which will get used in the uploader/key function
					//
					blob.name = 'derivative/thumbnail/';
					CropUploader.uploadingMessage.set('Thumbnail');
					CropUploader.uploading.set(true);
					CropUploader.uploader.send(blob, function (error, thumbnailUrl) {
						if (error) {
							console.error('Error uploading', CropUploader.uploader.xhr.response);
							// console.error(error);
							CropUploader.errorMessage.set('Error uploading:'+error.reason);
							CropUploader.uploading.set(false);
						} else {
							//
							// we have uploaded the thumbnail, so now upload original
							//
							originalCanvas.toBlob(function(blob){
								blob.name = uuid+'.png';
								var image = {
									name: blob.name
								};
								CropUploader.uploadingMessage.set('Original');
								CropUploader.uploader.send(blob, function(error, originalUrl){
									if(error)
									{
										// Log service detailed response
										console.error('Error uploading', uploader.xhr.response);
										console.error(error);
										CropUploader.errorMessage.set('Error uploading:'+error.reason);
										// we need to delete the derivative
										Meteor.call('cropUploaderS3Delete', thumbnailUrl, function(err, res){
											if(err) console.err(err);
										});
										CropUploader.uploading.set(false);
									}
									else
									{
										// console.log('uploaded blob: '+originalUrl);
										//
										// add uuid and md5hash to image object
										//
										image.uuid = uuid;
										image.md5hash = template.md5hash;
										image.url = originalUrl;
										//
										// add our derivatives
										//
										image.derivatives = {
											thumbnail: thumbnailUrl
										};
										if(template.addons)
										{
											image = _.extend(image, template.addons);
										}
										//
										// finally add it to the collection
										//
										CropUploader.insert(image);
										//
										// clear the thumbnailCanvas
										//
										var thumbnail_ctx = template.thumbnailCanvas.getContext("2d");
										thumbnail_ctx.clearRect(0, 0, template.thumbnailCanvas.width, template.thumbnailCanvas.height);
										//
										// trigger onclear on thumbnailCanvas
										//
										$('#'+template.thumbnailCanvas.id).trigger('onclear');
										//
										// trigger uploaded so client can act on it
										//
										$('#'+template.canvasID).trigger('uploaded', image);

										CropUploader.errorMessage.set('');
										CropUploader.uploading.set(false);
										template.imagePresent.set(false);
										template.originalCanvas.setAttribute('imagePresent', false);
									}
								});
							},'image/png');
						}
					});
				}, 'image/png');
			} else console.log('canvas no blob');
		} else CropUploader.errorMessage.set('Please select file first');
	},
});
Template.cropUploader.helpers({
	allowedURL: function() {
		var instance = Template.instance();
		// console.log('allowedURL '+instance.allowURL);
		return instance.allowURL;
	},
	hideUpload: function() {
		var instance = Template.instance();
		return instance.hideUpload;
	},
	cropUploaderTemplate: function() {
		// console.log(this);
		var template = 'cropUploaderPlain';
		var request = this.template || '';
		switch(request.toLowerCase()) {
			case 'dropbox':
				template = 'cropUploaderDropbox';
				break;
			case 'bootstrap':
				template = 'cropUploaderBootstrap';
				break;
			break;
		}
		return template;
	},
	data: function() {
		var data = Template.currentData();
		data.parentInstance = Template.instance();
		return data;
	}
});
Template.cropUploaderURL.onCreated(function(){
	var template = this;
	if(CropUploader.debug) console.debug(template.view.name+'.created: ', template.data);
	template.imagePresent = CropUploader.instance[template.data.thumbnailID].imagePresent;
})
Template.cropUploaderURL.events({
	'change input.crop-uploader-url': function(e, template) {
		// var url = template.$('input[type="url"]').val();
		var url = e.currentTarget.value;
		console.log(`crop-uploader-url ${url}`);
		var thumbnailID = template.data && template.data.thumbnailID ? template.data.thumbnailID : null;
		// template.$('input[type="file"]').val('');
		if(thumbnailID) {
			CropUploader.processing.set(true);
			template.md5hash = MD5(url);
			// CropUploader.instance[thumbnailID].thumbnail_img.src = '/loading.gif';
			Meteor.call('cropUploaderUrl',url, function(err,src){
				if(!err) {
					CropUploader.instance[thumbnailID].thumbnail_img.src = src;
				} else {
					console.error(err);
					CropUploader.errorMessage.set(err.details);
				}
			});
		}
	},
});
Template.cropUploaderURL.helpers({
	imagePresent: function(){
		var template = Template.instance();
		// console.log(template.view.name+'.imagePresent', template);
		return template.imagePresent.get();
	}
});
Template.cropUploaderDropbox.onCreated(function(){
	var template = this;
	if(CropUploader.debug) console.debug(template.view.name+'.created: ', template.data);
	// template.imagePresent = CropUploader.instance[template.data.thumbnailID].imagePresent;
});
Template.cropUploaderDropbox.onRendered(function(){
	var template = this;
	var canvasID = template.data.canvasID;

	if(template.data.dropboxImage)
	{
		template.$('#dropboxImage').attr('src',template.data.dropboxImage);
	}
});
Template.cropUploaderDropbox.events({
	'onload canvas': function(e,t) {
		// console.log('onload canvas');
	    // t.$('#dropboxImage').addClass('hidden');
		t.$('#'+t.data.canvasID).removeClass('hidden');
		// t.$('input[type="url"]').addClass('hidden');
	},
	'uploaded canvas': function(e, t, payload) {
		// console.log('uploaded canvas');
		t.$('#'+t.data.canvasID).addClass('hidden');
	    // t.$('#dropboxImage').removeClass('hidden');
		// t.$('input[type="url"]').removeClass('hidden');
	}
});
Template.cropUploaderDropbox.helpers({
	width: function() {
		var template = Template.instance();
		return template.data.previewWidth ? template.data.previewWidth : template.data.thumbnailWidth;
	},
	height: function() {
		var template = Template.instance();
		return template.data.previewHeight ? template.data.previewHeight : template.data.thumbnailHeight;
	},
	imagePresent: function(){
		var template = Template.instance();
		return template.data.parentInstance.imagePresent.get();
	},
});
Template.cropUploaderFile.onRendered(function(){
	var template = this;
	var dropfile = template.find('#crop-uploader-label-'+template.data.thumbnailID);
	if(CropUploader.debug) console.info(template.view.name+'.rendered', dropfile);
	dropfile.addEventListener('dragover', function(e) {
	  e.preventDefault();
	  e.stopPropagation();
	  dropfile.classList.add('dragover');
	});
	dropfile.addEventListener('dragleave', function(e) {
	  e.preventDefault();
	  e.stopPropagation();
	  dropfile.classList.remove('dragover');
	});
	dropfile.addEventListener('drop', function(e) {
	  e.preventDefault();
	  e.stopPropagation();
	  dropfile.classList.remove('dragover');
	  var files;
      if(e.dataTransfer) {
        files = e.dataTransfer.files;
      } else if(e.target) {
        files = e.target.files;
      }
      template.data.parentInstance.processFile(files[0]);
	});
	if(WebApp.isMobile)
		dropfile.addEventListener('click', function() {
		  template.$('#crop-uploader-file-'+template.data.thumbnailID).click();
		});
});
Template.cropUploaderFile.helpers({
	width() {
		var template = Template.instance();
		return template.data.previewWidth ? template.data.previewWidth : template.data.thumbnailWidth;
	},
	height() {
		var template = Template.instance();
		return template.data.previewHeight ? template.data.previewHeight : template.data.thumbnailHeight;
	},
	processing(){
		return CropUploader.processing.get();
	},
});
Template.cropUploaderProgressBar.onDestroyed(function(){
	CropUploader.uploading.set(false);
});
Template.cropUploaderProgressBar.helpers({
	progress: function () {
		return CropUploader.uploader ? Math.round(CropUploader.uploader.progress() * 100) : 0;
	}
})
Template.cropUploaderImages.onRendered(function(){
	var template = this;
	template.subscribe('cropUploaderImages');
});
Template.cropUploaderImages.helpers({
	images: function() {
		return CropUploader.images.find();
	}
});
Template.cropUploaderCropper.onCreated(function () {
	var template = this;
	CropUploader.crop.template = template;
	//
	template.imageid = template.data.imageid;
	template.original = CropUploader.images.findOne({_id: template.data.imageid});
	template.uuid = template.original.url.split('/').pop().split('.').shift();
	template.thumbnailWidth = template.data.thumbnailWidth || undefined;
	template.thumbnailHeight = template.data.thumbnailHeight || undefined;
	template.aspectRatio = template.data.aspectRatio || 1.0;

	if(template.thumbnailHeight == undefined && template.thumbnailWidth == undefined)
	{
		template.thumbnailHeight = 100;
		template.thumbnailWidth = 100;
	}

	CropUploader.crop.options.aspectRatio = template.aspectRatio;
	CropUploader.crop.options.checkImageOrigin = navigator.userAgent.match(/9.*Safari/)!==null;
	CropUploader.crop.options.data.width = template.thumbnailWidth;
	CropUploader.crop.options.data.height = template.thumbnailHeight;

	// var options = {
	// 	aspectRatio: template.aspectRatio,
	// 	resizable: true,
	// 	rotatable: true,
	// 	scalable: true,
	// 	checkOrientation: true,
	// 	// minCanvasHeight: 500,
	// 	preview: ".img-preview",
	// 	data: {
	// 		x: 10,
	// 		y: 10,
	// 		width: template.thumbnailWidth,
	// 		height: template.thumbnailHeight
	// 	},
	// 	// dragend: function() {
	// 	//   console.log('dragend');
	// 	// },
	// 	built: function() {
	// 		// this is image
	// 		if(CropUploader.debug)
	// 			console.debug(template.view.name+'.onCreated built', CropUploader.crop.options);
	// 		template.$('button.hidden').removeClass('hidden');
	// 		template.$('#crop-image-loading').fadeOut();
	// 	}
	// };
	$.fn.cropper.setDefaults(CropUploader.crop.options);

	template.canvas = null;
	//
	//
	template.initCropper = function(template) {
		// if(!template.view.isRendered) return;
		if(CropUploader.debug) console.debug('initCropper');
		if(!template.original) throw new Meteor.Error(403, 'image not found');
		// console.log(template.data.exif);
		// save the cropper handle in the template
		// template.cropimage = template.$(".image-container > img");
		template.cropimage = template.$("#crop-image");
		//
		// initialize the cropper
		//
		template.cropimage.cropper(CropUploader.crop.options);
	}
});
Template.cropUploaderCropper.onRendered(function () {
	var template = this;
	var canvas = document.createElement("canvas"),
			ctx = canvas.getContext("2d"),
			src = template.data.url, // insert image url here
			img = new Image
	 ;
	img.crossOrigin = "Anonymous";
	//
	// this is the key for fucking Safari cache, which
	// reports cross domain issues
	//
	src += '?safariCacheFix='+Date.now();

	template.cropimage = template.$('#crop-image');

	Tracker.afterFlush(function () {
		// template.initCropper(template);
		img.onload = function() {
			if(CropUploader.debug) console.debug('img loaded');
			canvas.width = img.width;
			canvas.height = img.height;
			ctx.drawImage( img, 0, 0 );
			var dataUrl = canvas.toDataURL("image/png");
			template.cropimage.attr('src', dataUrl ).cropper();
			// template.initCropper(template);
		};
		img.src = src;
	});
});
Template.cropUploaderCropper.onDestroyed( function () {
	var template = this;
	CropUploader.crop.template = null;
	template.cropimage = undefined;
});


text:
<!DOCTYPE html>

        <title>IndexedDB Jquery Plugin</title>
        <meta charset="utf-8">

JQuery IndexedDB Plugin- API Demo


text:
package refund

import (
	stripe "github.com/stripe/stripe-go"
	"github.com/stripe/stripe-go/form"
)

const (
	RefundFraudulent          stripe.RefundReason = "fraudulent"
	RefundDuplicate           stripe.RefundReason = "duplicate"
	RefundRequestedByCustomer stripe.RefundReason = "requested_by_customer"
)

// Client is used to invoke /refunds APIs.
type Client struct {
	B   stripe.Backend
	Key string
}

// New refunds a charge previously created.
// For more details see https://stripe.com/docs/api#refund_charge.
func New(params *stripe.RefundParams) (*stripe.Refund, error) {
	return getC().New(params)
}

func (c Client) New(params *stripe.RefundParams) (*stripe.Refund, error) {
	body := &form.Values{}
	form.AppendTo(body, params)

	refund := &stripe.Refund{}
	err := c.B.Call("POST", "/refunds", c.Key, body, &params.Params, refund)

	return refund, err
}

// Get returns the details of a refund.
// For more details see https://stripe.com/docs/api#retrieve_refund.
func Get(id string, params *stripe.RefundParams) (*stripe.Refund, error) {
	return getC().Get(id, params)
}

func (c Client) Get(id string, params *stripe.RefundParams) (*stripe.Refund, error) {
	var body *form.Values
	var commonParams *stripe.Params

	if params != nil {
		commonParams = &params.Params
		body = &form.Values{}
		form.AppendTo(body, params)
	}

	refund := &stripe.Refund{}
	err := c.B.Call("GET", "/refunds/"+id, c.Key, body, commonParams, refund)

	return refund, err
}

// Update updates a refund's properties.
// For more details see https://stripe.com/docs/api#update_refund.
func Update(id string, params *stripe.RefundParams) (*stripe.Refund, error) {
	return getC().Update(id, params)
}

func (c Client) Update(id string, params *stripe.RefundParams) (*stripe.Refund, error) {
	body := &form.Values{}
	form.AppendTo(body, params)

	refund := &stripe.Refund{}
	err := c.B.Call("POST", "/refunds/"+id, c.Key, body, &params.Params, refund)

	return refund, err
}

// List returns a list of refunds.
// For more details see https://stripe.com/docs/api#list_refunds.
func List(params *stripe.RefundListParams) *Iter {
	return getC().List(params)
}

func (c Client) List(params *stripe.RefundListParams) *Iter {
	body := &form.Values{}
	var lp *stripe.ListParams
	var p *stripe.Params

	form.AppendTo(body, params)
	lp = &params.ListParams
	p = params.ToParams()

	return &Iter{stripe.GetIter(lp, body, func(b *form.Values) ([]interface{}, stripe.ListMeta, error) {
		list := &stripe.RefundList{}
		err := c.B.Call("GET", "/refunds", c.Key, b, p, list)

		ret := make([]interface{}, len(list.Values))
		for i, v := range list.Values {
			ret[i] = v
		}

		return ret, list.ListMeta, err
	})}
}

// Iter is an iterator for lists of Refunds.
// The embedded Iter carries methods with it;
// see its documentation for details.
type Iter struct {
	*stripe.Iter
}

// Refund returns the most recent Refund
// visited by a call to Next.
func (i *Iter) Refund() *stripe.Refund {
	return i.Current().(*stripe.Refund)
}

func getC() Client {
	return Client{stripe.GetBackend(stripe.APIBackend), stripe.Key}
}


text:
package com.example;

import org.springframework.data.repository.CrudRepository;

public interface EmployeeRepository extends CrudRepository<Employee, Long> {

}


text:
layout: about
---

Hello, my name is Yurek Xu. I am a self proclaimed web developer who likes the internet, hip hop, and fancy yo-yos.

# What do you do?
I make website and stuff. All the code I write is on my [Github](https://github.com/Tim-Burbank).

# What programming languages do you use?
When making websites I like using Javascript and Sass. I also like Python and making linux scripts.