<commit_before>import {findTarget} from "./basic"

const dialogTemplate = ({id, classes, title, height, width, icon, buttons, zIndex, body, scroll}) =>
`<div tabindex="-1" role="dialog"
        class="ui-dialog ui-corner-all ui-widget ui-widget-content ui-front ui-dialog-buttons"
        ${id ? `aria-describedby="${id}"` : ''} style="z-index: ${zIndex};">

        ${icon ? `<i class="fa fa-${icon}" aria-hidden="true"></i>` : ''}
        ${title}
        <button type="button" class="ui-button ui-corner-all ui-widget ui-button-icon-only ui-dialog-titlebar-close" title="${gettext('Close')}">

            ${gettext('Close')}
        </button>

    <div ${id ? `id="${id}"` : ''} class="ui-dialog-content ui-widget-content${classes ? ` ${classes}` : ''}${scroll ? ` ui-scrollable` : ''}" style="width: ${width}; height: ${height};">
        ${body}

${buttonsTemplate({buttons})}

`

const buttonsTemplate = ({buttons}) => buttons.map(button => buttonTemplate(button)).join('')

const buttonTemplate = ({text, classes, icon}) => `<button type="button" class="${classes ? classes : 'fw-light'} fw-button ui-button ui-corner-all ui-widget">
    ${icon ? `<i class="fa fa-${icon}" aria-hidden="true"></i>` : ''}
    ${text}
</button>`

const BUTTON_TYPES = {
    close: {
        text: gettext('Close'),
        classes: 'fw-orange',
        click: dialog => () => dialog.close()
    },
    cancel: {
        text: gettext('Cancel'),
        classes: 'fw-orange',
        click: dialog => () => dialog.close()
    },
    ok: {
        text: gettext('OK'),
        classes: 'fw-dark',
        click: dialog => () => dialog.close()
    }
}

export class Dialog {
    constructor(options) {
        this.eventAddress = this.scrollevent.bind(this)
        this.id = options.id || false
        this.classes = options.classes || false
        this.title = options.title || ''
        this.body = options.body || ''
        this.height = options.height ? `${options.height}px` : 'auto'
        this.width = options.width ? `${options.width}px` : 'auto'
        this.buttons = []
        if (options.buttons) {
            this.setButtons(options.buttons)
        }
        this.beforeClose = options.onClose || false
        this.onClose = options.onClose || false
        this.icon = options.icon || false
        this.scroll = options.scroll || false
        this.dialogEl = false
        this.backdropEl = false
    }

    setButtons(buttons) {
        this.buttons = buttons.map(button => ({
            text: button.text ? button.text : button.type ? BUTTON_TYPES[button.type].text : '',
            classes: button.classes ? button.classes : button.type ? BUTTON_TYPES[button.type].classes : false,
            click: button.click ? button.click : button.type ? BUTTON_TYPES[button.type].click(this) : '',
            icon: button.icon ? button.icon : false
        }))
    }

    open() {
        if (this.dialogEl) {
            return
        }
        document.body.insertAdjacentHTML(
            'beforeend',
            dialogTemplate({
                id: this.id,
                classes: this.classes,
                title: this.title,
                height: this.height,
                width: this.width,
                icon: this.icon,
                buttons : this.buttons,
                zIndex: this.getHighestDialogZIndex() + 2,
                body: this.body,
                scroll: this.scroll
            })
        )
        this.backdropEl = document.body.lastElementChild
        this.dialogEl = this.backdropEl.previousElementSibling
        this.centerDialog()
        this.bind()
    }

    refreshButtons() {
        this.dialogEl.querySelector('.ui-dialog-buttonset').innerHTML = buttonsTemplate({buttons: this.buttons})
    }

    centerDialog() {
        const totalWidth = window.innerWidth,
            totalHeight = window.innerHeight,
            dialogWidth = this.dialogEl.clientWidth,
            dialogHeight = this.dialogEl.clientHeight,
            scrollTopOffset = window.pageYOffset,
            scrollLeftOffset = window.pageXOffset

        this.dialogEl.style.top = `${(totalHeight - dialogHeight)/2 + scrollTopOffset}px`
        this.dialogEl.style.left = `${(totalWidth - dialogWidth)/2 + scrollLeftOffset}px`
    }

    scrollevent() {
        this.centerDialog()
    }

    bind() {
        window.addEventListener('scroll', this.eventAddress, false)
        this.dialogEl.addEventListener('click', event => {
            const el = {}
            let buttonNumber, seekItem
            switch (true) {
                case findTarget(event, '.ui-dialog-buttonpane button', el):
                    event.preventDefault()
                    buttonNumber = 0
                    seekItem = el.target
                    while (seekItem.previousElementSibling) {
                        buttonNumber++
                        seekItem = seekItem.previousElementSibling
                    }
                    this.buttons[buttonNumber].click()
                    break
                case findTarget(event, '.ui-dialog-titlebar-close', el):
                    event.preventDefault()
                    this.close()
                    break
                default:
                    break
            }
        })
    }

    getHighestDialogZIndex() {
        let zIndex = 100
        document.querySelectorAll('div.ui-dialog').forEach(dialogEl => zIndex = Math.max(zIndex, dialogEl.style.zIndex))
        return zIndex
    }

    close() {
        if (!this.dialogEl) {
            return
        }
        window.removeEventListener("scroll",  this.eventAddress, false)
        if (this.beforeClose) {
            this.beforeClose()
        }
        this.dialogEl.parentElement.removeChild(this.dialogEl)
        this.backdropEl.parentElement.removeChild(this.backdropEl)
        if (this.onClose) {
            this.onClose()
        }
    }
}
<commit_msg>fix: dialog.beforeClose<commit_after>import {findTarget} from "./basic"

const dialogTemplate = ({id, classes, title, height, width, icon, buttons, zIndex, body, scroll}) =>
`<div tabindex="-1" role="dialog"
        class="ui-dialog ui-corner-all ui-widget ui-widget-content ui-front ui-dialog-buttons"
        ${id ? `aria-describedby="${id}"` : ''} style="z-index: ${zIndex};">

        ${icon ? `<i class="fa fa-${icon}" aria-hidden="true"></i>` : ''}
        ${title}
        <button type="button" class="ui-button ui-corner-all ui-widget ui-button-icon-only ui-dialog-titlebar-close" title="${gettext('Close')}">

            ${gettext('Close')}
        </button>

    <div ${id ? `id="${id}"` : ''} class="ui-dialog-content ui-widget-content${classes ? ` ${classes}` : ''}${scroll ? ` ui-scrollable` : ''}" style="width: ${width}; height: ${height};">
        ${body}

${buttonsTemplate({buttons})}

`

const buttonsTemplate = ({buttons}) => buttons.map(button => buttonTemplate(button)).join('')

const buttonTemplate = ({text, classes, icon}) => `<button type="button" class="${classes ? classes : 'fw-light'} fw-button ui-button ui-corner-all ui-widget">
    ${icon ? `<i class="fa fa-${icon}" aria-hidden="true"></i>` : ''}
    ${text}
</button>`

const BUTTON_TYPES = {
    close: {
        text: gettext('Close'),
        classes: 'fw-orange',
        click: dialog => () => dialog.close()
    },
    cancel: {
        text: gettext('Cancel'),
        classes: 'fw-orange',
        click: dialog => () => dialog.close()
    },
    ok: {
        text: gettext('OK'),
        classes: 'fw-dark',
        click: dialog => () => dialog.close()
    }
}

export class Dialog {
    constructor(options) {
        this.eventAddress = this.scrollevent.bind(this)
        this.id = options.id || false
        this.classes = options.classes || false
        this.title = options.title || ''
        this.body = options.body || ''
        this.height = options.height ? `${options.height}px` : 'auto'
        this.width = options.width ? `${options.width}px` : 'auto'
        this.buttons = []
        if (options.buttons) {
            this.setButtons(options.buttons)
        }
        this.beforeClose = options.beforeClose || false
        this.onClose = options.onClose || false
        this.icon = options.icon || false
        this.scroll = options.scroll || false
        this.dialogEl = false
        this.backdropEl = false
    }

    setButtons(buttons) {
        this.buttons = buttons.map(button => ({
            text: button.text ? button.text : button.type ? BUTTON_TYPES[button.type].text : '',
            classes: button.classes ? button.classes : button.type ? BUTTON_TYPES[button.type].classes : false,
            click: button.click ? button.click : button.type ? BUTTON_TYPES[button.type].click(this) : '',
            icon: button.icon ? button.icon : false
        }))
    }

    open() {
        if (this.dialogEl) {
            return
        }
        document.body.insertAdjacentHTML(
            'beforeend',
            dialogTemplate({
                id: this.id,
                classes: this.classes,
                title: this.title,
                height: this.height,
                width: this.width,
                icon: this.icon,
                buttons : this.buttons,
                zIndex: this.getHighestDialogZIndex() + 2,
                body: this.body,
                scroll: this.scroll
            })
        )
        this.backdropEl = document.body.lastElementChild
        this.dialogEl = this.backdropEl.previousElementSibling
        this.centerDialog()
        this.bind()
    }

    refreshButtons() {
        this.dialogEl.querySelector('.ui-dialog-buttonset').innerHTML = buttonsTemplate({buttons: this.buttons})
    }

    centerDialog() {
        const totalWidth = window.innerWidth,
            totalHeight = window.innerHeight,
            dialogWidth = this.dialogEl.clientWidth,
            dialogHeight = this.dialogEl.clientHeight,
            scrollTopOffset = window.pageYOffset,
            scrollLeftOffset = window.pageXOffset

        this.dialogEl.style.top = `${(totalHeight - dialogHeight)/2 + scrollTopOffset}px`
        this.dialogEl.style.left = `${(totalWidth - dialogWidth)/2 + scrollLeftOffset}px`
    }

    scrollevent() {
        this.centerDialog()
    }

    bind() {
        window.addEventListener('scroll', this.eventAddress, false)
        this.dialogEl.addEventListener('click', event => {
            const el = {}
            let buttonNumber, seekItem
            switch (true) {
                case findTarget(event, '.ui-dialog-buttonpane button', el):
                    event.preventDefault()
                    buttonNumber = 0
                    seekItem = el.target
                    while (seekItem.previousElementSibling) {
                        buttonNumber++
                        seekItem = seekItem.previousElementSibling
                    }
                    this.buttons[buttonNumber].click()
                    break
                case findTarget(event, '.ui-dialog-titlebar-close', el):
                    event.preventDefault()
                    this.close()
                    break
                default:
                    break
            }
        })
    }

    getHighestDialogZIndex() {
        let zIndex = 100
        document.querySelectorAll('div.ui-dialog').forEach(dialogEl => zIndex = Math.max(zIndex, dialogEl.style.zIndex))
        return zIndex
    }

    close() {
        if (!this.dialogEl) {
            return
        }
        window.removeEventListener("scroll",  this.eventAddress, false)
        if (this.beforeClose) {
            this.beforeClose()
        }
        this.dialogEl.parentElement.removeChild(this.dialogEl)
        this.backdropEl.parentElement.removeChild(this.backdropEl)
        if (this.onClose) {
            this.onClose()
        }
    }
}
<|endoftext|>


<commit_before>import convert from './convert';
import CryptoHelpers from '../crypto/cryptoHelpers';
import TransactionTypes from '../model/transactionTypes';

/**
 * Check if wallet already present in an array
 *
 * @param {string} walletName - A wallet name
 * @param {array} array - A wallets array
 *
 * @return {boolean} - True if present, false otherwise
 */
let haveWallet = function(walletName, array) {
    let i = null;
    for (i = 0; array.length > i; i++) {
        if (array[i].name === walletName) {
            return true;
        }
    }
    return false;
}

/**
 * Check if a multisig transaction needs signature
 *
 * @param {object} multisigTransaction - A multisig transaction
 * @param {object} data - An account data
 *
 * @return {boolean} - True if it needs signature, false otherwise
 */
let needsSignature = function(multisigTransaction, data) {
    if (multisigTransaction.transaction.signer === data.account.publicKey) {
        return false;
    }
    if (multisigTransaction.transaction.otherTrans.signer === data.account.publicKey) {
        return false;
    }
    // Check if we're already on list of signatures
    for (let i = 0; i < multisigTransaction.transaction.signatures.length; i++) {
        if (multisigTransaction.transaction.signatures[i].signer === data.account.publicKey) {
            return false;
        }
    }

    if (!data.meta.cosignatoryOf.length) {
        return false;
    } else {
        for (let k = 0; k < data.meta.cosignatoryOf.length; k++) {
            if (data.meta.cosignatoryOf[k].publicKey === multisigTransaction.transaction.otherTrans.signer) {
                return true;
            } else if (k === data.meta.cosignatoryOf.length - 1) {
                return false;
            }
        }
    }
    return true;
}

/**
 * Return the name of a transaction type id
 *
 * @param {number} id - A transaction type id
 *
 * @return {string} - The transaction type name
 */
let txTypeToName = function(id) {
    switch (id) {
        case TransactionTypes.Transfer:
            return 'Transfer';
        case TransactionTypes.ImportanceTransfer:
            return 'ImportanceTransfer';
        case TransactionTypes.MultisigModification:
            return 'MultisigModification';
        case TransactionTypes.ProvisionNamespace:
            return 'ProvisionNamespace';
        case TransactionTypes.MosaicDefinition:
            return 'MosaicDefinition';
        case TransactionTypes.MosaicSupply:
            return 'MosaicSupply';
        default:
            return 'Unknown_' + id;
    }
}

/**
 * Check if a transaction is already present in an array of transactions
 *
 * @param {string} hash - A transaction hash
 * @param {array} array - An array of transactions
 *
 * @return {boolean} - True if present, false otherwise
 */
let haveTx = function(hash, array) {
    let i = null;
    for (i = 0; array.length > i; i++) {
        if (array[i].meta.hash.data === hash) {
            return true;
        }
    }
    return false;
};

/**
 * Gets the index of a transaction in an array of transactions.
 * It must be present in the array.
 *
 * @param {string} hash - A transaction hash
 * @param {array} array - An array of transactions
 *
 * @return {number} - The index of the transaction
 */
let getTransactionIndex = function(hash, array) {
    let i = null;
    for (i = 0; array.length > i; i++) {
        if (array[i].meta.hash.data === hash) {
            return i;
        }
    }
    return 0;
};

/**
 * Return mosaic name from mosaicId object
 *
 * @param {object} mosaicId - A mosaicId object
 *
 * @return {string} - The mosaic name
 */
let mosaicIdToName = function(mosaicId) {
    if (!mosaicId) return mosaicId;
    return mosaicId.namespaceId + ":" + mosaicId.name;
}

/**
 * Parse uri to get hostname
 *
 * @param {string} uri - An uri string
 *
 * @return {string} - The uri hostname
 */
let getHostname = function(uri) {
    let _uriParser = document.createElement('a');
    _uriParser.href = uri;
    return _uriParser.hostname;
}

/**
 * Check if a cosignatory is already present in modifications array
 *
 * @param {string} address - A cosignatory address
 * @param {string} pubKey - A cosignatory public key
 * @param {array} array - A modifications array
 *
 * @return {boolean} - True if present, false otherwise
 */
let haveCosig = function(address, pubKey, array) {
    let i = null;
    for (i = 0; array.length > i; i++) {
        if (array[i].address === address || array[i].pubKey === pubKey) {
            return true;
        }
    }
    return false;
};

/**
 * Remove extension of a file name
 *
 * @param {string} filename - A file name with extension
 *
 * @return {string} - The file name without extension
 */
let getFileName = function(filename) {
    return filename.replace(/\.[^/.]+$/, "");
};

/**
 * Gets extension of a file name
 *
 * @param {string} filename - A file name with extension
 *
 * @return {string} - The file name extension
 */
let getExtension = function(filename) {
    return filename.split('.').pop();
}

/***
 * NEM epoch time
 *
 * @type {number}
 */
let NEM_EPOCH = Date.UTC(2015, 2, 29, 0, 6, 25, 0);

/**
 * Create a time stamp for a NEM transaction
 *
 * @return {number} - The NEM transaction time stamp in milliseconds
 */
let createNEMTimeStamp = function() {
    return Math.floor((Date.now() / 1000) - (NEM_EPOCH / 1000));
}

/**
 * Fix a private key
 *
 * @param {string} privatekey - An hex private key
 *
 * @return {string} - The fixed hex private key
 */
let fixPrivateKey = function(privatekey) {
    return ("0000000000000000000000000000000000000000000000000000000000000000" + privatekey.replace(/^00/, '')).slice(-64);
}

/**
 * Build a message object
 *
 * @param {object} common - An object containing wallet private key
 * @param {object} tx - A transaction object containing the message
 *
 * @return {object} - The message object
 */
let prepareMessage = function(common, tx) {
    if (tx.encryptMessage && common.privateKey) {
        return {
            'type': 2,
            'payload': CryptoHelpers.encode(common.privateKey, tx.recipientPubKey, tx.message.toString())
        };
    } else {
        return {
            'type': 1,
            'payload': convert.utf8ToHex(tx.message.toString())
        };
    }
}

/**
 * Check and format an url
 *
 * @param {string} node - A custom node from user input
 * @param {number} defaultWebsocketPort - A default websocket port
 *
 * @return {string|number} - The formatted node as string or 1
 */
let checkAndFormatUrl = function (node, defaultWebsocketPort) {
    // Detect if custom node doesn't begin with "http://"
        var pattern = /^((http):\/\/)/;
        if (!pattern.test(node)) {
            node = "http://" + node;
            let _uriParser = document.createElement('a');
            _uriParser.href = node;
            // If no port we add it
            if (!_uriParser.port) {
                node = node + ":" + defaultWebsocketPort;
            } else if (_uriParser.port !== defaultWebsocketPort) {
                // Port is not default websocket port
                return 1;
            }
        } else {
            // Start with "http://""
            let _uriParser = document.createElement('a');
            _uriParser.href = node;
            // If no port we add it
            if (!_uriParser.port) {
                node = node + ":" + defaultWebsocketPort;
            } else if (_uriParser.port !== defaultWebsocketPort) {
                // Port is not default websocket port
                return 1;
            }
        }
        return node;
}

/**
 * Create a time stamp
 *
 * @return {object} - A date object
 */
let createTimeStamp = function() {
    return new Date();
}

/**
 * Date object to YYYY-MM-DD format
 *
 * @param {object} date - A date object
 *
 * @return {string} - The short date
 */
let getTimestampShort = function(date) {
    let dd = date.getDate();
    let mm = date.getMonth() + 1; //January is 0!
    let yyyy = date.getFullYear();

    if (dd < 10) {
        dd = '0' + dd
    }

    if (mm < 10) {
        mm = '0' + mm
    }

    return yyyy + '-' + mm + '-' + dd;
};

/**
 * Date object to date string
 *
 * @param {object} date - A date object
 *
 * @return {string} - The date string
 */
let convertDateToString = function(date) {
    return date.toDateString();
};

/**
 * Mimics jQuery's extend function
 *
 * http://stackoverflow.com/a/11197343
 */
let extendObj = function(){
    for(var i=1; i<arguments.length; i++) {
        for(var key in arguments[i]) {
            if(arguments[i].hasOwnProperty(key)) {
                arguments[0][key] = arguments[i][key];
            }
        }
    }
    return arguments[0];
}

/**
 * Test if a string is hexadecimal
 *
 * @param {string} str - A string to test
 *
 * @return {boolean} - True if correct, false otherwise
 */
let isHexadecimal = function(str) {
    return str.match('^(0x|0X)?[a-fA-F0-9]+$') !== null;
}

/**
 * Search for mosaic definition(s) into an array of mosaicDefinition objects
 *
 * @param {array} mosaicDefinitionArray - An array of mosaicDefinition objects
 * @param {array} keys - Array of strings with names of the mosaics to find (['eur', 'usd',...])
 *
 * @return {object} - An object of mosaicDefinition objects
 */
let searchMosaicDefinitionArray = function(mosaicDefinitionArray, keys) {
    let result = {}
    for (let i = 0; i < keys.length; i++) {
        for(let k = 0; k < mosaicDefinitionArray.length; k++) {
            if(mosaicDefinitionArray[k].mosaic.id.name === keys[i]) {
                result[mosaicIdToName(mosaicDefinitionArray[k].mosaic.id)] = mosaicDefinitionArray[k].mosaic;
            }
        }
    }
    return result;
}

/**
 * Mimics jQuery's grep function
 */
let grep = function(items, callback) {
    var filtered = [],
        len = items.length,
        i = 0;
    for (i; i < len; i++) {
        var item = items[i];
        var cond = callback(item);
        if (cond) {
            filtered.push(item);
        }
    }

    return filtered;
};

/**
 * Check if a text input amount is valid
 *
 * @param {string} n - The number as a string
 *
 * @return {boolean} - True if valid, false otherwise
 */
let isTextAmountValid = function(n) {
    // Force n as a string and replace decimal comma by a dot if any
    var nn = Number(n.toString().replace(/,/g, '.'));
    return !Number.isNaN(nn) && Number.isFinite(nn) && nn >= 0;
}

/**
 * Clean a text input amount and return it as number
 *
 * @param {string} n - The number as a string
 *
 * @return {number} - The clean amount
 */
let cleanTextAmount = function(n) {
    return Number(n.toString().replace(/,/g, '.'));
}

/**
 * Convert an endpoint object to an endpoint url
 *
 * @param {object} endpoint - An endpoint object
 *
 * @return {String} - An endpoint url
 */
let formatEndpoint = function(endpoint) {
    return endpoint.host + ':' + endpoint.port;
}

module.exports = {
    haveWallet,
    needsSignature,
    txTypeToName,
    haveTx,
    getTransactionIndex,
    mosaicIdToName,
    getHostname,
    haveCosig,
    getFileName,
    getExtension,
    createNEMTimeStamp,
    fixPrivateKey,
    prepareMessage,
    checkAndFormatUrl,
    createTimeStamp,
    getTimestampShort,
    convertDateToString,
    extendObj,
    isHexadecimal,
    searchMosaicDefinitionArray,
    grep,
    isTextAmountValid,
    cleanTextAmount,
    formatEndpoint
}<commit_msg>Fix circular dependency injection, add isPrivateKeyValid, remove prepareMessage<commit_after>import convert from './convert';
import TransactionTypes from '../model/transactionTypes';

/**
 * Check if wallet already present in an array
 *
 * @param {string} walletName - A wallet name
 * @param {array} array - A wallets array
 *
 * @return {boolean} - True if present, false otherwise
 */
let haveWallet = function(walletName, array) {
    let i = null;
    for (i = 0; array.length > i; i++) {
        if (array[i].name === walletName) {
            return true;
        }
    }
    return false;
}

/**
 * Check if a multisig transaction needs signature
 *
 * @param {object} multisigTransaction - A multisig transaction
 * @param {object} data - An account data
 *
 * @return {boolean} - True if it needs signature, false otherwise
 */
let needsSignature = function(multisigTransaction, data) {
    if (multisigTransaction.transaction.signer === data.account.publicKey) {
        return false;
    }
    if (multisigTransaction.transaction.otherTrans.signer === data.account.publicKey) {
        return false;
    }
    // Check if we're already on list of signatures
    for (let i = 0; i < multisigTransaction.transaction.signatures.length; i++) {
        if (multisigTransaction.transaction.signatures[i].signer === data.account.publicKey) {
            return false;
        }
    }

    if (!data.meta.cosignatoryOf.length) {
        return false;
    } else {
        for (let k = 0; k < data.meta.cosignatoryOf.length; k++) {
            if (data.meta.cosignatoryOf[k].publicKey === multisigTransaction.transaction.otherTrans.signer) {
                return true;
            } else if (k === data.meta.cosignatoryOf.length - 1) {
                return false;
            }
        }
    }
    return true;
}

/**
 * Return the name of a transaction type id
 *
 * @param {number} id - A transaction type id
 *
 * @return {string} - The transaction type name
 */
let txTypeToName = function(id) {
    switch (id) {
        case TransactionTypes.Transfer:
            return 'Transfer';
        case TransactionTypes.ImportanceTransfer:
            return 'ImportanceTransfer';
        case TransactionTypes.MultisigModification:
            return 'MultisigModification';
        case TransactionTypes.ProvisionNamespace:
            return 'ProvisionNamespace';
        case TransactionTypes.MosaicDefinition:
            return 'MosaicDefinition';
        case TransactionTypes.MosaicSupply:
            return 'MosaicSupply';
        default:
            return 'Unknown_' + id;
    }
}

/**
 * Check if a transaction is already present in an array of transactions
 *
 * @param {string} hash - A transaction hash
 * @param {array} array - An array of transactions
 *
 * @return {boolean} - True if present, false otherwise
 */
let haveTx = function(hash, array) {
    let i = null;
    for (i = 0; array.length > i; i++) {
        if (array[i].meta.hash.data === hash) {
            return true;
        }
    }
    return false;
};

/**
 * Gets the index of a transaction in an array of transactions.
 * It must be present in the array.
 *
 * @param {string} hash - A transaction hash
 * @param {array} array - An array of transactions
 *
 * @return {number} - The index of the transaction
 */
let getTransactionIndex = function(hash, array) {
    let i = null;
    for (i = 0; array.length > i; i++) {
        if (array[i].meta.hash.data === hash) {
            return i;
        }
    }
    return 0;
};

/**
 * Return mosaic name from mosaicId object
 *
 * @param {object} mosaicId - A mosaicId object
 *
 * @return {string} - The mosaic name
 */
let mosaicIdToName = function(mosaicId) {
    if (!mosaicId) return mosaicId;
    return mosaicId.namespaceId + ":" + mosaicId.name;
}

/**
 * Parse uri to get hostname
 *
 * @param {string} uri - An uri string
 *
 * @return {string} - The uri hostname
 */
let getHostname = function(uri) {
    let _uriParser = document.createElement('a');
    _uriParser.href = uri;
    return _uriParser.hostname;
}

/**
 * Check if a cosignatory is already present in modifications array
 *
 * @param {string} address - A cosignatory address
 * @param {string} pubKey - A cosignatory public key
 * @param {array} array - A modifications array
 *
 * @return {boolean} - True if present, false otherwise
 */
let haveCosig = function(address, pubKey, array) {
    let i = null;
    for (i = 0; array.length > i; i++) {
        if (array[i].address === address || array[i].pubKey === pubKey) {
            return true;
        }
    }
    return false;
};

/**
 * Remove extension of a file name
 *
 * @param {string} filename - A file name with extension
 *
 * @return {string} - The file name without extension
 */
let getFileName = function(filename) {
    return filename.replace(/\.[^/.]+$/, "");
};

/**
 * Gets extension of a file name
 *
 * @param {string} filename - A file name with extension
 *
 * @return {string} - The file name extension
 */
let getExtension = function(filename) {
    return filename.split('.').pop();
}

/***
 * NEM epoch time
 *
 * @type {number}
 */
let NEM_EPOCH = Date.UTC(2015, 2, 29, 0, 6, 25, 0);

/**
 * Create a time stamp for a NEM transaction
 *
 * @return {number} - The NEM transaction time stamp in milliseconds
 */
let createNEMTimeStamp = function() {
    return Math.floor((Date.now() / 1000) - (NEM_EPOCH / 1000));
}

/**
 * Fix a private key
 *
 * @param {string} privatekey - An hex private key
 *
 * @return {string} - The fixed hex private key
 */
let fixPrivateKey = function(privateKey) {
    return ("0000000000000000000000000000000000000000000000000000000000000000" + privateKey.replace(/^00/, '')).slice(-64);
}

/**
 * Check if a private key is valid
 *
 * @param {string} privatekey - A private key
 *
 * @return {boolean} - True if valid, false otherwise
 */
let isPrivateKeyValid = function(privateKey) {
    if (privateKey.length !== 64 && privateKey.length !== 66) {
        console.error('Private key length must be 64 or 66 characters !');
        return false;
    } else if (!isHexadecimal(privateKey)) {
        console.error('Private key must be hexadecimal only !');
        return false;
    } else {
        return true;
    }
}

/**
 * Check if a public key is valid
 *
 * @param {string} publicKey - A public key
 *
 * @return {boolean} - True if valid, false otherwise
 */
let isPublicKeyValid = function(publicKey) {
    if (publicKey.length !== 64) {
        console.error('Public key length must be 64 or 66 characters !');
        return false;
    } else if (!isHexadecimal(publicKey)) {
        console.error('Public key must be hexadecimal only !');
        return false;
    } else {
        return true;
    }
}

/**
 * Check and format an url
 *
 * @param {string} node - A custom node from user input
 * @param {number} defaultWebsocketPort - A default websocket port
 *
 * @return {string|number} - The formatted node as string or 1
 */
let checkAndFormatUrl = function (node, defaultWebsocketPort) {
    // Detect if custom node doesn't begin with "http://"
        var pattern = /^((http):\/\/)/;
        if (!pattern.test(node)) {
            node = "http://" + node;
            let _uriParser = document.createElement('a');
            _uriParser.href = node;
            // If no port we add it
            if (!_uriParser.port) {
                node = node + ":" + defaultWebsocketPort;
            } else if (_uriParser.port !== defaultWebsocketPort) {
                // Port is not default websocket port
                return 1;
            }
        } else {
            // Start with "http://""
            let _uriParser = document.createElement('a');
            _uriParser.href = node;
            // If no port we add it
            if (!_uriParser.port) {
                node = node + ":" + defaultWebsocketPort;
            } else if (_uriParser.port !== defaultWebsocketPort) {
                // Port is not default websocket port
                return 1;
            }
        }
        return node;
}

/**
 * Create a time stamp
 *
 * @return {object} - A date object
 */
let createTimeStamp = function() {
    return new Date();
}

/**
 * Date object to YYYY-MM-DD format
 *
 * @param {object} date - A date object
 *
 * @return {string} - The short date
 */
let getTimestampShort = function(date) {
    let dd = date.getDate();
    let mm = date.getMonth() + 1; //January is 0!
    let yyyy = date.getFullYear();

    if (dd < 10) {
        dd = '0' + dd
    }

    if (mm < 10) {
        mm = '0' + mm
    }

    return yyyy + '-' + mm + '-' + dd;
};

/**
 * Date object to date string
 *
 * @param {object} date - A date object
 *
 * @return {string} - The date string
 */
let convertDateToString = function(date) {
    return date.toDateString();
};

/**
 * Mimics jQuery's extend function
 *
 * http://stackoverflow.com/a/11197343
 */
let extendObj = function(){
    for(var i=1; i<arguments.length; i++) {
        for(var key in arguments[i]) {
            if(arguments[i].hasOwnProperty(key)) {
                arguments[0][key] = arguments[i][key];
            }
        }
    }
    return arguments[0];
}

/**
 * Test if a string is hexadecimal
 *
 * @param {string} str - A string to test
 *
 * @return {boolean} - True if correct, false otherwise
 */
let isHexadecimal = function(str) {
    return str.match('^(0x|0X)?[a-fA-F0-9]+$') !== null;
}

/**
 * Search for mosaic definition(s) into an array of mosaicDefinition objects
 *
 * @param {array} mosaicDefinitionArray - An array of mosaicDefinition objects
 * @param {array} keys - Array of strings with names of the mosaics to find (['eur', 'usd',...])
 *
 * @return {object} - An object of mosaicDefinition objects
 */
let searchMosaicDefinitionArray = function(mosaicDefinitionArray, keys) {
    let result = {}
    for (let i = 0; i < keys.length; i++) {
        for(let k = 0; k < mosaicDefinitionArray.length; k++) {
            if(mosaicDefinitionArray[k].mosaic.id.name === keys[i]) {
                result[mosaicIdToName(mosaicDefinitionArray[k].mosaic.id)] = mosaicDefinitionArray[k].mosaic;
            }
        }
    }
    return result;
}

/**
 * Mimics jQuery's grep function
 */
let grep = function(items, callback) {
    var filtered = [],
        len = items.length,
        i = 0;
    for (i; i < len; i++) {
        var item = items[i];
        var cond = callback(item);
        if (cond) {
            filtered.push(item);
        }
    }

    return filtered;
};

/**
 * Check if a text input amount is valid
 *
 * @param {string} n - The number as a string
 *
 * @return {boolean} - True if valid, false otherwise
 */
let isTextAmountValid = function(n) {
    // Force n as a string and replace decimal comma by a dot if any
    var nn = Number(n.toString().replace(/,/g, '.'));
    return !Number.isNaN(nn) && Number.isFinite(nn) && nn >= 0;
}

/**
 * Clean a text input amount and return it as number
 *
 * @param {string} n - The number as a string
 *
 * @return {number} - The clean amount
 */
let cleanTextAmount = function(n) {
    return Number(n.toString().replace(/,/g, '.'));
}

/**
 * Convert an endpoint object to an endpoint url
 *
 * @param {object} endpoint - An endpoint object
 *
 * @return {String} - An endpoint url
 */
let formatEndpoint = function(endpoint) {
    return endpoint.host + ':' + endpoint.port;
}

module.exports = {
    haveWallet,
    needsSignature,
    txTypeToName,
    haveTx,
    getTransactionIndex,
    mosaicIdToName,
    getHostname,
    haveCosig,
    getFileName,
    getExtension,
    createNEMTimeStamp,
    fixPrivateKey,
    isPrivateKeyValid,
    isPublicKeyValid,
    checkAndFormatUrl,
    createTimeStamp,
    getTimestampShort,
    convertDateToString,
    extendObj,
    isHexadecimal,
    searchMosaicDefinitionArray,
    grep,
    isTextAmountValid,
    cleanTextAmount,
    formatEndpoint
}<|endoftext|>


<commit_before>#! /usr/bin/env node

'use strict'

const commander = require('commander')
const program = require('../lib/program')
const pkg = require('../package.json')

commander
  .version(pkg.version)
  .usage('--meetup-name [MEETUP_NAME] --event-id [EVENT_ID]')
  .option('--meetup-name [MEETUP_NAME]', `Meetup's name`) // eslint-disable-line quotes
  .option('--event-id [EVENT_ID]', `Event's id`) // eslint-disable-line quotes
  .parse(process.argv)

if (!commander.meetupName || !commander.eventId) commander.help()

program(commander.meetupName, commander.eventId)
  .then(() => {
    process.exit(0)
  })
  .catch(error => {
    console.error(error)
    process.exit(error)
  })
<commit_msg>fix(cli): Required parameters<commit_after>#! /usr/bin/env node

'use strict'

const commander = require('commander')
const program = require('../lib/program')
const pkg = require('../package.json')

commander
  .version(pkg.version)
  .usage('--meetup-name [MEETUP_NAME] --event-id [EVENT_ID]')
  .option('--meetup-name <MEETUP_NAME>', `Meetup's name`) // eslint-disable-line quotes
  .option('--event-id <EVENT_ID>', `Event's id`) // eslint-disable-line quotes
  .parse(process.argv)

if (!commander.meetupName || !commander.eventId) commander.help()

program(commander.meetupName, commander.eventId)
  .then(() => {
    process.exit(0)
  })
  .catch(error => {
    console.error(error)
    process.exit(error)
  })
<|endoftext|>


<commit_before>$.getScript("https://rawgit.com/MuseDJ/MusiqpadScript/master/scripts/main.js");
var museLoader = setInterval(function() {
    if(API !== undefined)
        if(muse !== undefined)
            setTimeout(function() {
                muse.fn.init();
                clearInterval(museLoader);
            }, 500);
}, 500);<commit_msg>Fixed loader<commit_after>$.getScript("https://rawgit.com/MuseDJ/MusiqpadScript/master/scripts/main.js");
var startTime = Date.now();
var museLoader = setInterval(function() {
    if (typeof API !== "undefined")
        if (typeof muse !== "undefined")
            setTimeout(function() {
                muse.fn.init();
                muse.fn.logger.info("Initialized in " + Date.now() - startTime);
                clearInterval(museLoader);
            }, 500);
}, 500);<|endoftext|>


<commit_before>angular.module('mwUI.ResponseToastHandler', ['mwUI.Toast','mwUI.ResponseHandler', 'mwUI.i18n']);

// @include ./services/mw_response_toast_handler.js<commit_msg>adds utils module as dependency<commit_after>angular.module('mwUI.ResponseToastHandler', ['mwUI.Toast','mwUI.ResponseHandler', 'mwUI.i18n', 'mwUI.Utils']);

// @include ./services/mw_response_toast_handler.js<|endoftext|>


<commit_before>#!/usr/bin/env node

const stdin = require('get-stdin')
const parseTorrent = require('../')

function usage () {
  console.error('Usage: parse-torrent /path/to/torrent')
  console.error('       parse-torrent magnet_uri')
  console.error('       parse-torrent --stdin')
  console.error('       parse-torrent --raw')
}

function error (err) {
  console.error(err.message)
  process.exit(1)
}

const arg = process.argv[2]

if (!arg || arg === '--help') {
  console.error('Missing required argument')
  usage()
  process.exit(1)
}

if (arg === '--stdin' || arg === '-') stdin.buffer().then(onTorrentId).catch(error)
else if (arg === '--version' || arg === '-v') console.log(require('../package.json').version)
else onTorrentId(arg)

function onTorrentId (torrentId) {
  parseTorrent.remote(torrentId, function (err, parsedTorrent) {
    if (err) return error(err)

    if (arg !== '--raw') {
      delete parsedTorrent.info
      delete parsedTorrent.infoBuffer
      delete parsedTorrent.infoHashBuffer
    }
    console.log(JSON.stringify(parsedTorrent, undefined, 2))
  })
}
<commit_msg>cmd: better --raw<commit_after>#!/usr/bin/env node

const stdin = require('get-stdin')
const parseTorrent = require('../')

function usage () {
  console.error('Usage: parse-torrent /path/to/torrent')
  console.error('       parse-torrent magnet_uri')
  console.error('       parse-torrent --stdin')
  console.error('       parse-torrent --raw /path/to/torrent')
  console.error('       parse-torrent --raw magnet_uri')
}

function error (err) {
  console.error(err.message)
  process.exit(1)
}

const args = process.argv.slice(2)

if (!args[0] || args.includes('--help')) {
  usage()
  process.exit(1)
}

if (args.includes('--stdin') || args.includes('-')) stdin.buffer().then(onTorrentId).catch(error)
else if (args.includes() === '--version' || args.includes('-v')) console.log(require('../package.json').version)
else onTorrentId(args[args.length - 1])

function onTorrentId (torrentId) {
  parseTorrent.remote(torrentId, function (err, parsedTorrent) {
    if (err) return error(err)

    if (args.includes('--raw')) {
      recursiveStringify(parsedTorrent.info)
    } else {
      delete parsedTorrent.info
    }

    delete parsedTorrent.infoBuffer
    delete parsedTorrent.infoHashBuffer

    console.log(JSON.stringify(parsedTorrent, undefined, 2))
  })
}

function recursiveStringify (obj) {
  for (const key of Object.keys(obj)) {
    if (!Buffer.isBuffer(obj[key]) &&
        typeof obj[key] === 'object' && obj[key] !== null) {
      recursiveStringify(obj[key])
    } else {
      obj[key] = obj[key].toString()
    }
  }
}
<|endoftext|>


<commit_before>/**
 * SDK内部上报数据类
 * 会记录请求响应成功失败次数、限制发送频率
 */

import Ajax from '../compats/ajax.js'
import * as utils from '../libs/utils.js'
import * as defaults from '../defaults.js'
import * as onlineTimer from './onlineTimer.js'

// 上次请求发生时间
var lastRequestTime = 0

export var failedCount = 0

export var reportCount = 0

export default function(opts, force) {
  var now = Date.now()

  /**
   * 频率控制
   * 强制上报的请求不受限制
   */
  if (!force) {
    if (lastRequestTime && (now - lastRequestTime < defaults.ASAP_TIMEOUT)) {
      utils.log('Request dropped: unexpected behavior')
      return
    }

    lastRequestTime = now
  }

  reportCount += 1

  Ajax({
    url: opts.url,
    data: opts.data,
    success: (xhr, elapsed) => {
      utils.attempt(opts.success, xhr, [xhr, elapsed])
    },
    error: (xhr, elapsed, isTimeout) => {
      failedCount += 1
      utils.attempt(opts.error, xhr, [xhr, elapsed, isTimeout])
    },
    complete: (xhr, elapsed) => {
      utils.attempt(opts.complete, xhr, [xhr, elapsed])

      /**
       * 重新设置定时器
       */
      if (!xhr.getAllResponseHeaders || !xhr.getResponseHeader) return

      var headers = xhr.getAllResponseHeaders()
      var header = 'X-Rate-Limit'
      if (headers.indexOf(header) === -1) return

      var interval = utils.parseInt(xhr.getResponseHeader(header))
      if (interval >= defaults.MIN_ONLINE_INTERVAL) {
        onlineTimer.reset(interval * 1000)
      }
    }
  })
}
<commit_msg> dynamic timer reset<commit_after>/**
 * SDK内部上报数据类
 * 会记录请求响应成功失败次数、限制发送频率
 */

import Ajax from '../compats/ajax.js'
import * as utils from '../libs/utils.js'
import * as defaults from '../defaults.js'
import * as onlineTimer from './onlineTimer.js'

// 上次请求发生时间
var lastRequestTime = 0

export var failedCount = 0

export var reportCount = 0

export default function(opts, force) {
  var now = Date.now()

  /**
   * 频率控制
   * 强制上报的请求不受限制
   */
  if (!force) {
    if (lastRequestTime && (now - lastRequestTime < defaults.ASAP_TIMEOUT)) {
      utils.log('Request dropped: unexpected behavior')
      return
    }

    lastRequestTime = now
  }

  reportCount += 1

  Ajax({
    url: opts.url,
    data: opts.data,
    success: (xhr, elapsed) => {
      utils.attempt(opts.success, xhr, [xhr, elapsed])
    },
    error: (xhr, elapsed, isTimeout) => {
      failedCount += 1
      utils.attempt(opts.error, xhr, [xhr, elapsed, isTimeout])
    },
    complete: (xhr, elapsed) => {
      utils.attempt(opts.complete, xhr, [xhr, elapsed])

      /**
       * 重新设置定时器
       */
      if (!xhr.getAllResponseHeaders || !xhr.getResponseHeader) return

      var headers = xhr.getAllResponseHeaders()
      var header = 'X-Rate-Limit'
      if (headers.indexOf(header) === -1) return

      var interval = utils.parseInt(xhr.getResponseHeader(header))
      if (interval > 1) {
        onlineTimer.reset(interval * 1000)
      }
    }
  })
}
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import {connect} from 'react-redux'
import {Wit} from 'node-wit';

import Layout from '../components/Layout.js';
import Footer from '../components/Footer.js';
import NavBar from '../components/NavBar.js';
import ButtonView from '../components/ButtonView.js';
import StoryInputView from '../components/StoryInputView.js';
import CodeView from '../components/CodeView.js';
import MessagesView from '../components/MessagesView.js';

import Intents from '../fixtures/Intents'

import * as MessageNormalizer from '../lib/MessageNormalizer';
import * as ResponseParser from '../lib/parsers/ResponseParser';
import * as RawStylesProcessor from '../lib/processors/RawStylesProcessor';
import * as RawIntensityProcessor from '../lib/processors/RawIntensityProcessor';
import * as RawTextProcessor from '../lib/processors/RawTextProcessor';
import * as RawClassProcessor from '../lib/processors/RawClassProcessor';
import * as RawUrlProcessor from '../lib/processors/RawUrlProcessor';
import * as actions from '../actions/index';
import * as constants from "./AppConstants";

class ButtonCreator extends Component {
    constructor(props) {
        super(props);

        this.witConfig = {accessToken: constants.WITAI_KEY, witURL: constants.WIT_URL};

        this.setMessage = this.setMessage.bind(this);
        this.getButtonHtml = this.getButtonHtml.bind(this);
        this.understandMessage = this.understandMessage.bind(this);
        this.processMessage = this.processMessage.bind(this);
        this.updateStyles = this.updateStyles.bind(this);
        this.updateMessages = this.updateMessages.bind(this);
        this.parse = this.parse.bind(this);
        this.expandMessages = this.expandMessages.bind(this);
        this.setShowSpeakButton = this.setShowSpeakButton.bind(this);
        this.clearStyles = this.clearStyles.bind(this);
        this.processAttributeChange = this.processAttributeChange.bind(this);
        this.processIntensityChange = this.processIntensityChange.bind(this);
        this.processClassChange = this.processClassChange.bind(this);
        this.processLinkChange = this.processLinkChange.bind(this);
    }

    componentDidMount() {
        const buttonHtml = this.getButtonHtml();
        this.props.setButtonHtml(buttonHtml);

        const styles = this.updateStyles(constants.INITIAL_STYLES);
        this.props.setStyles(styles);

        this.client = new Wit(this.witConfig);
    }

    getButtonHtml(text, cssClass, url) {
        text = text ? text : this.props.state.buttonText;
        cssClass = cssClass ? cssClass : this.props.state.buttonCssClass;
        url = url ? url : this.props.state.buttonUrl;

        return `<button class="${ cssClass }" onclick="location.href = '${ url }';">${ text }</button>`;
    }

    setMessage(message) {
        this.props.setMessage(message);
    }

    processMessage(message) {
        const normalizedMessage = MessageNormalizer.normalize(message);
        this.understandMessage(normalizedMessage);
        this.updateMessages(message, constants.USER);
    }

    understandMessage(message) {
        this.client.message(message, {})
            .then((response) => {
                this.parse(response);
            }, () => {
                this.updateMessages('sorry, we couldn\'t connect to our language parser', constants.APP);
            })
            .catch(console.error);
    }

    parse(response) {
        try {
            const intent = ResponseParser.getIntent(response);

            switch (intent) {
                case Intents.possibleIntents.changeAttribute:
                    this.processAttributeChange(response);
                    break;
                case  Intents.possibleIntents.changeValue:
                    this.processIntensityChange(response);
                    break;
                case Intents.possibleIntents.changeClass:
                    this.processClassChange(response);
                    break;
                case Intents.possibleIntents.changeText:
                    this.processTextChange(response);
                    break;
                case Intents.possibleIntents.changeLink:
                    this.processLinkChange(response);
                    break;
                default:
                    break;
            }
        }
        catch (error) {
            this.updateMessages(error.message, constants.APP);
        }
    }

    processAttributeChange(response) {
        const rawStyles = ResponseParser.getRawStyles(response);
        const normalizedRawStyle = RawStylesProcessor.normalize(rawStyles);
        const newStyle = RawStylesProcessor.process(normalizedRawStyle);
        const newStyles = this.updateStyles(newStyle);

        this.props.updateStyles(rawStyles, normalizedRawStyle, newStyles);

        this.updateMessages('Done!', constants.APP);
    }

    processIntensityChange(response) {
        const rawIntensity = ResponseParser.getRawIntensity(response);
        const normalizedStyle = RawIntensityProcessor.process(rawIntensity, this.props.state.currentStyle);
        const newStyle = RawStylesProcessor.process(normalizedStyle);
        const newStyles = this.updateStyles(newStyle);

        this.props.updateRawIntensity(rawIntensity, normalizedStyle, newStyles);

        this.updateMessages('Done!', constants.APP);
    }

    processLinkChange(response) {
        const rawUrl = ResponseParser.getRawUrl(response);
        const newUrl = RawUrlProcessor.process(rawUrl);
        const buttonHtml = this.getButtonHtml(this.props.state.buttonText, this.props.state.buttonCssClass, newUrl);

        this.props.updateButtonProps(buttonHtml, this.props.state.buttonText, this.props.state.buttonCssClass, newUrl);

        this.updateMessages('Done!', constants.APP);
    }

    processClassChange(response) {
        const rawClass = ResponseParser.getRawClass(response);
        const newClass = RawClassProcessor.process(rawClass);
        const buttonHtml = this.getButtonHtml(this.props.state.buttonText, newClass, this.props.state.buttonUrl);

        this.props.updateButtonProps(buttonHtml, this.props.state.buttonText, newClass, this.props.state.buttonUrl);

        this.updateMessages('Done!', constants.APP);
    }

    processTextChange(response) {
        const rawText = ResponseParser.getRawText(response);
        const newText = RawTextProcessor.process(rawText);
        const buttonHtml = this.getButtonHtml(newText, this.props.state.buttonCssClass, this.props.state.buttonUrl);

        this.props.updateButtonProps(buttonHtml, newText, this.props.state.buttonCssClass, this.props.state.buttonUrl);

        this.updateMessages('Done!', constants.APP);
    }

    expandMessages() {
        this.props.setExpandMessages(true);
    }

    setShowSpeakButton(value) {
        this.props.setShowSpeakButton(value);
    }

    clearStyles() {
        this.props.setStyles(constants.INITIAL_STYLES);
        this.updateMessages('restored default styles', constants.APP);
    }

    updateMessages(message, sender) {
        const messages = [...this.props.state.messages];
        messages.push({
            'body': message,
            'sender': sender
        });
        this.props.setMessages(messages);
    }

    updateStyles(newStyles) {
        const styles = {
            ...this.props.state.styles
        };

        Object.keys(newStyles).forEach((key) => {
            styles[key] = newStyles[key];
        });

        return styles;
    }

    render() {
        return (
            <Layout>
                <NavBar />
                <ButtonView buttonHtml={this.props.state.buttonHtml}
                            styles={this.props.state.styles}
                            buttonText={this.props.state.buttonText}
                            buttonCssClass={this.props.state.buttonCssClass}
                            buttonUrl={this.props.state.buttonUrl}
                            message={this.props.state.message}/>
                <MessagesView messages={this.props.state.messages}
                              expandMessages={this.props.state.expandMessages}/>
                <StoryInputView constants={constants}
                                updateMessages={this.updateMessages}
                                setMessage={this.setMessage}
                                startRecording={this.startRecording}
                                stopRecording={this.stopRecording}
                                processMessage={this.processMessage}
                                expandMessages={this.expandMessages}
                                showSpeakButton={this.props.state.showSpeakButton}
                                setShowSpeakButton={this.setShowSpeakButton}
                                showClearStylesButton={this.props.state.expandMessages}
                                clearStyles={this.clearStyles}
                                setExpandMessages={this.props.setExpandMessages}
                                message={this.props.state.message}/>
                <CodeView rawStyles={this.props.state.rawStyles}
                          rawValues={this.props.state.rawValues}
                          buttonHtml={this.props.state.buttonHtml}
                          styles={this.props.state.styles}/>
                <Footer />
            </Layout>
        );
    }
}

const mapStateToProps = (state) => {
    return {
        state: state.MainReducer,
        recorder: state.recorder
    };
};

const mapDispatchToProps = (dispatch, ownProps) => {
    return {
        setButtonText: (buttonText) => {
            dispatch(actions.setButtonText(buttonText))
        },
        setRawStyles: (rawStyles) => {
            dispatch(actions.setRawStyles(rawStyles))
        },
        setStyles: (styles) => {
            dispatch(actions.setStyles(styles))
        },
        setRawIntensity: (rawIntensity) => {
            dispatch(actions.setRawIntensity(rawIntensity))
        },
        setCurrentStyle: (currentStyle) => {
            dispatch(actions.setCurrentStyle(currentStyle))
        },
        setMessages: (messages) => {
            dispatch(actions.setMessages(messages))
        },
        setMessage: (message) => {
            dispatch(actions.setMessage(message))
        },
        setButtonHtml: (buttonHtml) => {
            dispatch(actions.setButtonHtml(buttonHtml))
        },
        setExpandMessages: (expandMessages) => {
            dispatch(actions.setExpandMessages(expandMessages))
        },
        setShowSpeakButton: (value) => {
            dispatch(actions.setShowSpeakButton(value))
        },
        updateStyles: (rawStyles, currentStyle, styles) => {
            dispatch(actions.updateStyles(rawStyles, currentStyle, styles))
        },
        updateRawIntensity: (rawIntensity, currentStyle, styles) => {
            dispatch(actions.updateRawIntensity(rawIntensity, currentStyle, styles))
        },
        updateButtonProps: (buttonHtml, buttonText, buttonCssClass, buttonUrl) => {
            dispatch(actions.updateButtonProps(buttonHtml, buttonText, buttonCssClass, buttonUrl))
        },
        startRecording: () => {
            // dispatch(recorderStart())
        },
        stopRecording: () => {
            // dispatch(recorderStop());
        }
    }
};

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(ButtonCreator);
<commit_msg>Fix to previous commit.<commit_after>import React, {Component} from 'react';
import {connect} from 'react-redux'
import {Wit} from 'node-wit';

import Layout from '../components/Layout.js';
import Footer from '../components/Footer.js';
import NavBar from '../components/NavBar.js';
import ButtonView from '../components/ButtonView.js';
import StoryInputView from '../components/StoryInputView.js';
import CodeView from '../components/CodeView.js';
import MessagesView from '../components/MessagesView.js';

import Intents from '../fixtures/Intents'

import * as MessageNormalizer from '../lib/MessageNormalizer';
import * as ResponseParser from '../lib/parsers/ResponseParser';
import * as RawStylesProcessor from '../lib/processors/RawStylesProcessor';
import * as RawIntensityProcessor from '../lib/processors/RawIntensityProcessor';
import * as RawTextProcessor from '../lib/processors/RawTextProcessor';
import * as RawClassProcessor from '../lib/processors/RawClassProcessor';
import * as RawUrlProcessor from '../lib/processors/RawUrlProcessor';
import * as actions from '../actions/index';
import * as constants from "./AppConstants";

class ButtonCreator extends Component {
    constructor(props) {
        super(props);

        this.witConfig = {accessToken: constants.WITAI_KEY, witURL: constants.WIT_URL};

        this.setMessage = this.setMessage.bind(this);
        this.getButtonHtml = this.getButtonHtml.bind(this);
        this.understandMessage = this.understandMessage.bind(this);
        this.processMessage = this.processMessage.bind(this);
        this.updateStyles = this.updateStyles.bind(this);
        this.updateMessages = this.updateMessages.bind(this);
        this.parse = this.parse.bind(this);
        this.expandMessages = this.expandMessages.bind(this);
        this.setShowSpeakButton = this.setShowSpeakButton.bind(this);
        this.clearStyles = this.clearStyles.bind(this);
        this.processAttributeChange = this.processAttributeChange.bind(this);
        this.processIntensityChange = this.processIntensityChange.bind(this);
        this.processClassChange = this.processClassChange.bind(this);
        this.processLinkChange = this.processLinkChange.bind(this);
    }

    componentDidMount() {
        const buttonHtml = this.getButtonHtml();
        this.props.setButtonHtml(buttonHtml);

        const styles = this.updateStyles(constants.INITIAL_STYLES);
        this.props.setStyles(styles);

        this.client = new Wit(this.witConfig);
    }

    getButtonHtml(text, cssClass, url) {
        text = text ? text : this.props.state.buttonText;
        cssClass = cssClass ? cssClass : this.props.state.buttonCssClass;
        url = url ? url : this.props.state.buttonUrl;

        return `<button class="${ cssClass }"
        onclick="location.href = '${ url }';">
        ${ text }\n</button>`;
    }

    setMessage(message) {
        this.props.setMessage(message);
    }

    processMessage(message) {
        const normalizedMessage = MessageNormalizer.normalize(message);
        this.understandMessage(normalizedMessage);
        this.updateMessages(message, constants.USER);
    }

    understandMessage(message) {
        this.client.message(message, {})
            .then((response) => {
                this.parse(response);
            }, () => {
                this.updateMessages('sorry, we couldn\'t connect to our language parser', constants.APP);
            })
            .catch(console.error);
    }

    parse(response) {
        try {
            const intent = ResponseParser.getIntent(response);

            switch (intent) {
                case Intents.possibleIntents.changeAttribute:
                    this.processAttributeChange(response);
                    break;
                case  Intents.possibleIntents.changeValue:
                    this.processIntensityChange(response);
                    break;
                case Intents.possibleIntents.changeClass:
                    this.processClassChange(response);
                    break;
                case Intents.possibleIntents.changeText:
                    this.processTextChange(response);
                    break;
                case Intents.possibleIntents.changeLink:
                    this.processLinkChange(response);
                    break;
                default:
                    break;
            }
        }
        catch (error) {
            this.updateMessages(error.message, constants.APP);
        }
    }

    processAttributeChange(response) {
        const rawStyles = ResponseParser.getRawStyles(response);
        const normalizedRawStyle = RawStylesProcessor.normalize(rawStyles);
        const newStyle = RawStylesProcessor.process(normalizedRawStyle);
        const newStyles = this.updateStyles(newStyle);

        this.props.updateStyles(rawStyles, normalizedRawStyle, newStyles);

        this.updateMessages('Done!', constants.APP);
    }

    processIntensityChange(response) {
        const rawIntensity = ResponseParser.getRawIntensity(response);
        const normalizedStyle = RawIntensityProcessor.process(rawIntensity, this.props.state.currentStyle);
        const newStyle = RawStylesProcessor.process(normalizedStyle);
        const newStyles = this.updateStyles(newStyle);

        this.props.updateRawIntensity(rawIntensity, normalizedStyle, newStyles);

        this.updateMessages('Done!', constants.APP);
    }

    processLinkChange(response) {
        const rawUrl = ResponseParser.getRawUrl(response);
        const newUrl = RawUrlProcessor.process(rawUrl);
        const buttonHtml = this.getButtonHtml(this.props.state.buttonText, this.props.state.buttonCssClass, newUrl);

        this.props.updateButtonProps(buttonHtml, this.props.state.buttonText, this.props.state.buttonCssClass, newUrl);

        this.updateMessages('Done!', constants.APP);
    }

    processClassChange(response) {
        const rawClass = ResponseParser.getRawClass(response);
        const newClass = RawClassProcessor.process(rawClass);
        const buttonHtml = this.getButtonHtml(this.props.state.buttonText, newClass, this.props.state.buttonUrl);

        this.props.updateButtonProps(buttonHtml, this.props.state.buttonText, newClass, this.props.state.buttonUrl);

        this.updateMessages('Done!', constants.APP);
    }

    processTextChange(response) {
        const rawText = ResponseParser.getRawText(response);
        const newText = RawTextProcessor.process(rawText);
        const buttonHtml = this.getButtonHtml(newText, this.props.state.buttonCssClass, this.props.state.buttonUrl);

        this.props.updateButtonProps(buttonHtml, newText, this.props.state.buttonCssClass, this.props.state.buttonUrl);

        this.updateMessages('Done!', constants.APP);
    }

    expandMessages() {
        this.props.setExpandMessages(true);
    }

    setShowSpeakButton(value) {
        this.props.setShowSpeakButton(value);
    }

    clearStyles() {
        this.props.setStyles(constants.INITIAL_STYLES);
        this.updateMessages('restored default styles', constants.APP);
    }

    updateMessages(message, sender) {
        const messages = [...this.props.state.messages];
        messages.push({
            'body': message,
            'sender': sender
        });
        this.props.setMessages(messages);
    }

    updateStyles(newStyles) {
        const styles = {
            ...this.props.state.styles
        };

        Object.keys(newStyles).forEach((key) => {
            styles[key] = newStyles[key];
        });

        return styles;
    }

    render() {
        return (
            <Layout>
                <NavBar />
                <ButtonView buttonHtml={this.props.state.buttonHtml}
                            styles={this.props.state.styles}
                            buttonText={this.props.state.buttonText}
                            buttonCssClass={this.props.state.buttonCssClass}
                            buttonUrl={this.props.state.buttonUrl}
                            message={this.props.state.message}/>
                <MessagesView messages={this.props.state.messages}
                              expandMessages={this.props.state.expandMessages}/>
                <StoryInputView constants={constants}
                                updateMessages={this.updateMessages}
                                setMessage={this.setMessage}
                                startRecording={this.startRecording}
                                stopRecording={this.stopRecording}
                                processMessage={this.processMessage}
                                expandMessages={this.expandMessages}
                                showSpeakButton={this.props.state.showSpeakButton}
                                setShowSpeakButton={this.setShowSpeakButton}
                                showClearStylesButton={this.props.state.expandMessages}
                                clearStyles={this.clearStyles}
                                setExpandMessages={this.props.setExpandMessages}
                                message={this.props.state.message}/>
                <CodeView rawStyles={this.props.state.rawStyles}
                          rawValues={this.props.state.rawValues}
                          buttonHtml={this.props.state.buttonHtml}
                          styles={this.props.state.styles}/>
                <Footer />
            </Layout>
        );
    }
}

const mapStateToProps = (state) => {
    return {
        state: state.MainReducer,
        recorder: state.recorder
    };
};

const mapDispatchToProps = (dispatch, ownProps) => {
    return {
        setButtonText: (buttonText) => {
            dispatch(actions.setButtonText(buttonText))
        },
        setRawStyles: (rawStyles) => {
            dispatch(actions.setRawStyles(rawStyles))
        },
        setStyles: (styles) => {
            dispatch(actions.setStyles(styles))
        },
        setRawIntensity: (rawIntensity) => {
            dispatch(actions.setRawIntensity(rawIntensity))
        },
        setCurrentStyle: (currentStyle) => {
            dispatch(actions.setCurrentStyle(currentStyle))
        },
        setMessages: (messages) => {
            dispatch(actions.setMessages(messages))
        },
        setMessage: (message) => {
            dispatch(actions.setMessage(message))
        },
        setButtonHtml: (buttonHtml) => {
            dispatch(actions.setButtonHtml(buttonHtml))
        },
        setExpandMessages: (expandMessages) => {
            dispatch(actions.setExpandMessages(expandMessages))
        },
        setShowSpeakButton: (value) => {
            dispatch(actions.setShowSpeakButton(value))
        },
        updateStyles: (rawStyles, currentStyle, styles) => {
            dispatch(actions.updateStyles(rawStyles, currentStyle, styles))
        },
        updateRawIntensity: (rawIntensity, currentStyle, styles) => {
            dispatch(actions.updateRawIntensity(rawIntensity, currentStyle, styles))
        },
        updateButtonProps: (buttonHtml, buttonText, buttonCssClass, buttonUrl) => {
            dispatch(actions.updateButtonProps(buttonHtml, buttonText, buttonCssClass, buttonUrl))
        },
        startRecording: () => {
            // dispatch(recorderStart())
        },
        stopRecording: () => {
            // dispatch(recorderStop());
        }
    }
};

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(ButtonCreator);
<|endoftext|>


<commit_before>Braintree = Npm.require('braintree');

BrainTreeConnect = function (key) {
  var BraintreeObj;
  var resources = {
    address : ['create', 'delete', 'find', 'update'],
    clientToken : ['generate'],
    customer : ['create', 'delete', 'find', 'search', 'update'],
    merchantAccount : ['create', 'find', 'update'],
    paymentMethod : ['create', 'delete', 'find', 'update'],
    paymentMethodNonce : ['create', 'find'],
    plan : ['all'],
    subscription : ['cancel', 'create', 'find', 'search', 'update'],
    transaction : ['cancelRelease', 'cloneTransaction', 'find', 'holdInEscrow', 'refund', 'releaseFromEscrow', 'sale', 'search', 'submitForSettlement', 'void']
  };

  BraintreeObj = Braintree.connect(key);

  _.each(resources, function (resource, key){
    _.each(resource, function (funcName){
      var func = BraintreeObj[key][funcName];
      BraintreeObj[key][funcName] = Meteor.wrapAsync(func, BraintreeObj[key]);
    });
  });

  return BraintreeObj;
};

BrainTreeConnect.Environment = Braintree.Environment;
<commit_msg>Revert "Link Braintree.Environment to BrainTreeConnect.Environment"<commit_after>Braintree = Npm.require('braintree');

BrainTreeConnect = function (key) {
  var BraintreeObj;
  var resources = {
    address : ['create', 'delete', 'find', 'update'],
    clientToken : ['generate'],
    customer : ['create', 'delete', 'find', 'search', 'update'],
    merchantAccount : ['create', 'find', 'update'],
    paymentMethod : ['create', 'delete', 'find', 'update'],
    paymentMethodNonce : ['create', 'find'],
    plan : ['all'],
    subscription : ['cancel', 'create', 'find', 'search', 'update'],
    transaction : ['cancelRelease', 'cloneTransaction', 'find', 'holdInEscrow', 'refund', 'releaseFromEscrow', 'sale', 'search', 'submitForSettlement', 'void']
  };

  BraintreeObj = Braintree.connect(key);

  _.each(resources, function (resource, key){
    _.each(resource, function (funcName){
      var func = BraintreeObj[key][funcName];
      BraintreeObj[key][funcName] = Meteor.wrapAsync(func, BraintreeObj[key]);
    });
  });

  return BraintreeObj;
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

var path = require("path")
  , fs = require("fs")
  , child = require("child_process")

  , program = require("commander")
  , ChromeExtension = require("..")

  , resolve = path.resolve
  , join = path.join
  , spawn = child.spawn
  , exec = child.exec

  , cwd = process.cwd()

program
  .version("0.2.8")
  .option("-f, --file [file]", "input/output <file> instead of stdin/stdout")
  .option("-p, --private-key <file>", "relative path to private key [key.pem]")
  // coming soon
  // .option("-x, --xml", "output autoupdate xml instead of extension ")

program
  .command("keygen [directory]")
  .description("generate a private key in [directory]/key.pem")
  .action(keygen)

program
  .command("pack [directory]")
  .description("pack [directory] into a .crx extension")
  .action(pack)

// program
//   .command("unpack [directory]")
//   .description("unpack a .crx extension into a directory")
//   .action(unpack)

program.parse(process.argv)

function keygen(dir, cb) {
  dir = resolve(cwd, dir)

  var key = join(dir, "key.pem")

  path.exists(key, function(exists) {
    if (exists) return cb && cb()

    var pubPath = key + ".pub"
      , command = "ssh-keygen -N '' -b 1024 -t rsa -f key.pem"

    exec(command, {cwd: dir}, function(err) {
      if (err) throw err

      // TODO: find a way to prevent .pub output
      fs.unlink(pubPath)
      cb && cb()
    })
  })
}

function pack(dir) {
  var input = resolve(cwd, dir)
    , output =
      program.file === true ? input + ".crx" :
      program.file ? resolve(cwd, program.file) : false

    , stream = output ? fs.createWriteStream(output) : process.stdout
    , key = program.privateKey
        ? resolve(cwd, program.privateKey)
        : join(input, "key.pem")

    , crx = new ChromeExtension

  fs.readFile(key, function(err, data) {
    if (err) keygen(dir, pack.bind(null, dir))

    crx.privateKey = data

    crx.load(input, function(err) {
      if (err) throw err

      this.pack(function(err, data){
        if (err) throw err

        stream.end(data)
        this.destroy()
      })
    })
  })
}<commit_msg>Added support for maxBuffer in CLI.<commit_after>#!/usr/bin/env node

var path = require("path")
  , fs = require("fs")
  , child = require("child_process")

  , program = require("commander")
  , ChromeExtension = require("..")

  , resolve = path.resolve
  , join = path.join
  , spawn = child.spawn
  , exec = child.exec

  , cwd = process.cwd()

program
  .version("0.2.8")
  .option("-f, --file [file]", "input/output <file> instead of stdin/stdout")
  .option("-p, --private-key <file>", "relative path to private key [key.pem]")
  .option("-b, --max-buffer <total>", "max amount of memory allowed to generate the crx, in byte")
  // coming soon
  // .option("-x, --xml", "output autoupdate xml instead of extension ")

program
  .command("keygen [directory]")
  .description("generate a private key in [directory]/key.pem")
  .action(keygen)

program
  .command("pack [directory]")
  .description("pack [directory] into a .crx extension")
  .action(pack)

// program
//   .command("unpack [directory]")
//   .description("unpack a .crx extension into a directory")
//   .action(unpack)

program.parse(process.argv)

function keygen(dir, cb) {
  dir = resolve(cwd, dir)

  var key = join(dir, "key.pem")

  path.exists(key, function(exists) {
    if (exists) return cb && cb()

    var pubPath = key + ".pub"
      , command = "ssh-keygen -N '' -b 1024 -t rsa -f key.pem"

    exec(command, {cwd: dir}, function(err) {
      if (err) throw err

      // TODO: find a way to prevent .pub output
      fs.unlink(pubPath)
      cb && cb()
    })
  })
}

function pack(dir) {
  var input = resolve(cwd, dir)
    , output =
      program.file === true ? input + ".crx" :
      program.file ? resolve(cwd, program.file) : false

    , stream = output ? fs.createWriteStream(output) : process.stdout
    , key = program.privateKey
        ? resolve(cwd, program.privateKey)
        : join(input, "key.pem")

    , crx = new ChromeExtension({
      maxBuffer: program.maxBuffer
    })

  fs.readFile(key, function(err, data) {
    if (err) keygen(dir, pack.bind(null, dir))

    crx.privateKey = data

    crx.load(input, function(err) {
      if (err) throw err

      this.pack(function(err, data){
        if (err) throw err

        stream.end(data)
        this.destroy()
      })
    })
  })
}<|endoftext|>


<commit_before>var player = (function () {
    function changeMovementAngle(player) {
        if (player.isRightPressed) {
            player.movementAngle += CONSTANTS.MOVEMENT_ANGLE_CHANGE;
        } else if (player.isLeftPressed) {
            player.movementAngle -= CONSTANTS.MOVEMENT_ANGLE_CHANGE;
        }
    }

    function changeModifiers(player) {
        if (0 <= player.movementAngle && player.movementAngle <= 90) {
            player.yModifier = player.movementAngle / 90;
            player.xModifier = (90 - player.movementAngle) / 90;
        } else if (90 < player.movementAngle && player.movementAngle <= 180) {
            player.yModifier = (180 - player.movementAngle) / 90;
            player.xModifier = (90 - player.movementAngle) / 90;
        } else if (180 < player.movementAngle && player.movementAngle <= 270) {
            player.yModifier = (180 - player.movementAngle) / 90;
            player.xModifier = (player.movementAngle - 270) / 90;
        } else {
            player.yModifier = (player.movementAngle - 360) / 90;
            player.xModifier = (player.movementAngle - 270) / 90;
        }
    }

    function changePosition(player) {
        player.x += 2 * player.xModifier;
        player.y += 2 * player.yModifier;
    }

    function drawPath(player) {
        gameFieldCtx.fillStyle = player.fillStyle;
        gameFieldCtx.beginPath();
        gameFieldCtx.arc(player.x, player.y, CONSTANTS.PLAYER_RADIUS, 0, 2 * Math.PI);
        gameFieldCtx.fill();
        gameFieldCtx.closePath();
    }

    var currentId = 0,
        fieldWidth = parseInt(gameField.getAttribute('width')),
        fieldHeight = parseInt(gameField.getAttribute('height')),
        player = Object.create({});

    Object.defineProperty(player, 'init', {
        value: function (name, fillStyle) {
            this.x = parseInt(Math.random() * fieldWidth);
            this.y = parseInt(Math.random() * fieldHeight);
            this.xModifier = 1;
            this.yModifier = 0;
            this.id = ++currentId;
            this.name = name;
            this.fillStyle = fillStyle;
            this.movementAngle = 0;
            this.isLeftPressed = false;
            this.isRightPressed = false;
            return this;
        }
    });

    Object.defineProperty(player, 'movementAngle', {
        get: function () {
            return this._movementAngle;
        },
        set: function (value) {
            if (value < 0) {
                this._movementAngle = 360 - CONSTANTS.MOVEMENT_ANGLE_CHANGE;
            } else if (value > 360) {
                this._movementAngle = CONSTANTS.MOVEMENT_ANGLE_CHANGE;
            } else {
                this._movementAngle = value;
            }
        }
    });

    Object.defineProperty(player, 'move', {
        value: function () {
            changeMovementAngle(this);
            changeModifiers(this);
            changePosition(this);
            drawPath(this);
        }
    });

    return player;
}());

var player1 = Object.create(player).init('PlayerOne', '#'+Math.random().toString(16).substr(-6));
var player2 = Object.create(player).init('PlayerTwo', '#'+Math.random().toString(16).substr(-6));<commit_msg>minor optimization with color of player path<commit_after>var player = (function () {
    function changeMovementAngle(player) {
        if (player.isRightPressed) {
            player.movementAngle += CONSTANTS.MOVEMENT_ANGLE_CHANGE;
        } else if (player.isLeftPressed) {
            player.movementAngle -= CONSTANTS.MOVEMENT_ANGLE_CHANGE;
        }
    }

    function changeModifiers(player) {
        if (0 <= player.movementAngle && player.movementAngle <= 90) {
            player.yModifier = player.movementAngle / 90;
            player.xModifier = (90 - player.movementAngle) / 90;
        } else if (90 < player.movementAngle && player.movementAngle <= 180) {
            player.yModifier = (180 - player.movementAngle) / 90;
            player.xModifier = (90 - player.movementAngle) / 90;
        } else if (180 < player.movementAngle && player.movementAngle <= 270) {
            player.yModifier = (180 - player.movementAngle) / 90;
            player.xModifier = (player.movementAngle - 270) / 90;
        } else {
            player.yModifier = (player.movementAngle - 360) / 90;
            player.xModifier = (player.movementAngle - 270) / 90;
        }
    }

    function changePosition(player) {
        player.x += 2 * player.xModifier;
        player.y += 2 * player.yModifier;
    }

    function drawPath(player) {
        gameFieldCtx.fillStyle = player.fillStyle;
        gameFieldCtx.beginPath();
        gameFieldCtx.arc(player.x, player.y, CONSTANTS.PLAYER_RADIUS, 0, 2 * Math.PI);
        gameFieldCtx.fill();
        gameFieldCtx.closePath();
    }

    var currentId = 0,
        fieldWidth = parseInt(gameField.getAttribute('width')),
        fieldHeight = parseInt(gameField.getAttribute('height')),
        player = Object.create({});

    Object.defineProperty(player, 'init', {
        value: function (name) {
            this.x = parseInt(Math.random() * fieldWidth);
            this.y = parseInt(Math.random() * fieldHeight);
            this.xModifier = 1;
            this.yModifier = 0;
            this.id = ++currentId;
            this.name = name;
            this.fillStyle = '#'+Math.random().toString(16).substr(-6);
            this.movementAngle = 0;
            this.isLeftPressed = false;
            this.isRightPressed = false;
            return this;
        }
    });

    Object.defineProperty(player, 'movementAngle', {
        get: function () {
            return this._movementAngle;
        },
        set: function (value) {
            if (value < 0) {
                this._movementAngle = 360 - CONSTANTS.MOVEMENT_ANGLE_CHANGE;
            } else if (value > 360) {
                this._movementAngle = CONSTANTS.MOVEMENT_ANGLE_CHANGE;
            } else {
                this._movementAngle = value;
            }
        }
    });

    Object.defineProperty(player, 'move', {
        value: function () {
            changeMovementAngle(this);
            changeModifiers(this);
            changePosition(this);
            drawPath(this);
        }
    });

    return player;
}());

var player1 = Object.create(player).init('PlayerOne');
var player2 = Object.create(player).init('PlayerTwo');<|endoftext|>


<commit_before>import React from 'react';
// import {Link} from 'react-router';
// import Header from '../../components/Header.js';
import Section from '../../components/Section.js';
// import AngledDivider from './AngledDivider.js';
import CursiveHeader from '../../components/CursiveHeader.js';
import CenteredContainer from '../../components/CenteredContainer.js';

const ContactPage = () => {
  const imgStyle = {
    height: "50px",
    padding: "5px"
  };
  const mapStyle = {
    height: "300px",
    padding: "5px"
  };
  return (

        {/*<AngledDivider/>*/}
        <CursiveHeader>Contact Us</CursiveHeader>
          {/*
The rush schedule is below

If you have any questions regarding rush and/or rush events, please contact our rush chair: Ian Loomis
*/}

President: Mark Eddy

Vice-President: Robert Pirdy

2nd Vice-President: Conor O'Brien

Seargant at Arms: Chris Schara

Chaplain: Brady Brown

Treasurer: Matthew Atwell

Advisor: Gary Proud

Advisor: Gary Gasper

General Questions?: Email Us!

              <CenteredContainer>

              </CenteredContainer>

  );
};

export default ContactPage;
<commit_msg>changed gasper to panish<commit_after>import React from 'react';
// import {Link} from 'react-router';
// import Header from '../../components/Header.js';
import Section from '../../components/Section.js';
// import AngledDivider from './AngledDivider.js';
import CursiveHeader from '../../components/CursiveHeader.js';
import CenteredContainer from '../../components/CenteredContainer.js';

const ContactPage = () => {
  const imgStyle = {
    height: "50px",
    padding: "5px"
  };
  const mapStyle = {
    height: "300px",
    padding: "5px"
  };
  return (

        {/*<AngledDivider/>*/}
        <CursiveHeader>Contact Us</CursiveHeader>
          {/*
The rush schedule is below

If you have any questions regarding rush and/or rush events, please contact our rush chair: Ian Loomis
*/}

President: Mark Eddy

Vice-President: Robert Pirdy

2nd Vice-President: Conor O'Brien

Seargant at Arms: Chris Schara

Chaplain: Brady Brown

Treasurer: Matthew Atwell

Advisor: Gary Proud

Advisor: Dave Panish

General Questions?: Email Us!

              <CenteredContainer>

              </CenteredContainer>

  );
};

export default ContactPage;
<|endoftext|>


<commit_before>function setContextMenuForFragments() {
    var menu = $("#frg-context-menu");

    $("#fragment-group, #fragment-overlay-content")
    .off("contextmenu.cvz_frg").on("contextmenu.cvz_frg", ".fragment-header", function(event) {

        var target = $(event.target);
        if (target.hasClass("rclick-hint")) {
            target = target.closest(".fragment-header");
        }
        if (target.hasClass("fragment-header")) {
            showPopup(menu, event);
            menu.data("target-frg", target);
            if (target.attr("_deletable") === "true") {
                menu.find("#fragment-group-form\\:bookmark").hide();
                menu.find("#fragment-group-form\\:trash").hide();
                menu.find("#fragment-group-form\\:delete").show();
                menu.find("#fragment-group-form\\:restore").show();
                menu.find("#fragment-group-form\\:relateNew").hide();
            }
            else {
                menu.find("#fragment-group-form\\:bookmark").show();
                menu.find("#fragment-group-form\\:trash").show();
                menu.find("#fragment-group-form\\:delete").hide();
                menu.find("#fragment-group-form\\:restore").hide();
                menu.find("#fragment-group-form\\:relateNew").show();
            }
            event.preventDefault();
        }
    });
}

function setContextMenuForBookmarks() {
    var menu = $("#bookmark-context-menu");

    $("#bookmark-form\\:bookmark-panel")
    .off("contextmenu.cvz_bm").on("contextmenu.cvz_bm", ".each-bookmark", function(event) {

        showPopup(menu, event);
        var target = $(event.target).closest(".each-bookmark");
        menu.data("target-bookmark", target);
        event.preventDefault();
    });
}

function setContextMenuForTags() {
    var menu = $("#tag-context-menu");

    $("#tag-palette-panel")
    .off("contextmenu.cvz_tag").on("contextmenu.cvz_tag", ".each-tag", function(event) {

        showPopup(menu, event);
        var target = $(event.target).closest(".each-tag");
        menu.data("target-tag", target);
        var tid = target.attr("_tid");
        if (tid <=0) {
            // special tags; not modifiable
            $("#tag-palette-form\\:edit").hide();
            $("#tag-palette-form\\:trash").hide();
        }
        else {
            $("#tag-palette-form\\:edit").show();
            $("#tag-palette-form\\:trash").show();
        }
        $("#tag-palette-form\\:id-placeholder-for-tag").val(tid);
        event.preventDefault();
    });
}
function setContextMenuForSelections() {
    var menu = $("#selection-box-context-menu");

    $("#selection-box")
    .off("contextmenu.cvz_sb").on("contextmenu.cvz_sb", function(event) {

        var fragments = getSelectedFragments();
        menu.find("#selection-box-form\\:bookmark").show();
        showOrHide(menu.find("#selection-box-form\\:relate"), fragments.length > 1);
        menu.find("#selection-box-form\\:trash").show();
        menu.find("#selection-box-form\\:unselect").show();
        menu.find("#selection-box-form\\:select_unselect").hide();
        if (fragments.length > 0)
            showPopup(menu, event);
        event.preventDefault();
    });

    $("#selection-box-form\\:selection-box-panel")
    .off("contextmenu.cvz_sb").on("contextmenu.cvz_sb", ".each-selected-frg", function(event) {

        var target = $(event.target).closest(".each-selected-frg");
        if (isNaN(parseInt(target.attr("_fid"))))
            return;

        menu.find("#selection-box-form\\:bookmark").hide();
        menu.find("#selection-box-form\\:relate").hide();
        menu.find("#selection-box-form\\:trash").hide();
        menu.find("#selection-box-form\\:unselect").hide();
        menu.find("#selection-box-form\\:select_unselect").show();

        showPopup(menu, event);
        menu.data("target-fragment", target);
        event.preventDefault();
    });
}

function setContextMenuForFiles() {
    var menu = $("#file-context-menu");

    $("#file-box-form\\:file-box-panel")
    .off("contextmenu.cvz_file").on("contextmenu.cvz_file", ".each-file, #file-path-tree", function(event) {
        showPopup(menu, event);
        var target = $(event.target);
        if (target.attr("_isFolder") === "false") {
            menu.find("#file-box-form\\:new-folder").hide();
        }
        else {
            menu.find("#file-box-form\\:new-folder").show();
        }
        if (isNaN(parseInt(target.attr("_id")))) {
            // the menu has no specified target;
            // the target will be the root folder
            menu.find("#file-box-form\\:rename").hide();
            menu.find("#file-box-form\\:move").hide();
            menu.find("#file-box-form\\:delete").hide();
        }
        else {
            // the menu has a target file or folder
            menu.find("#file-box-form\\:rename").show();
            menu.find("#file-box-form\\:move").show();
            menu.find("#file-box-form\\:delete").show();
        }
        menu.data("target-file", target);
        event.preventDefault();
    });
}

function completeContextMenuSetup() {
    $(document).off("click.cvz_ctxtm_off").on("click.cvz_ctxtm_off", function(event) {
        $("#frg-context-menu, #bookmark-context-menu, #tag-context-menu, #selection-box-context-menu, #file-context-menu")
        .hide();
    });
}

function setupContextMenus() {
    // Add "rclick-disabled" class to whatever element
    // that needs to keep from invoking browsers's default context menu.
    $(".rclick-disabled").off("contextmenu.cvz_rcd").on("contextmenu.cvz_rcd", function(e) {
        e.preventDefault();
    });

    setContextMenuForFragments();
    setContextMenuForBookmarks();
    setContextMenuForTags();
    setContextMenuForSelections();
    setContextMenuForFiles();

    completeContextMenuSetup();
}
<commit_msg>[bug fix] context menu setup for tags was incomplete;<commit_after>function setContextMenuForFragments() {
    var menu = $("#frg-context-menu");

    $("#fragment-group, #fragment-overlay-content")
    .off("contextmenu.cvz_frg").on("contextmenu.cvz_frg", ".fragment-header", function(event) {

        var target = $(event.target);
        if (target.hasClass("rclick-hint")) {
            target = target.closest(".fragment-header");
        }
        if (target.hasClass("fragment-header")) {
            showPopup(menu, event);
            menu.data("target-frg", target);
            if (target.attr("_deletable") === "true") {
                menu.find("#fragment-group-form\\:bookmark").hide();
                menu.find("#fragment-group-form\\:trash").hide();
                menu.find("#fragment-group-form\\:delete").show();
                menu.find("#fragment-group-form\\:restore").show();
                menu.find("#fragment-group-form\\:relateNew").hide();
            }
            else {
                menu.find("#fragment-group-form\\:bookmark").show();
                menu.find("#fragment-group-form\\:trash").show();
                menu.find("#fragment-group-form\\:delete").hide();
                menu.find("#fragment-group-form\\:restore").hide();
                menu.find("#fragment-group-form\\:relateNew").show();
            }
            event.preventDefault();
        }
    });
}

function setContextMenuForBookmarks() {
    var menu = $("#bookmark-context-menu");

    $("#bookmark-form\\:bookmark-panel")
    .off("contextmenu.cvz_bm").on("contextmenu.cvz_bm", ".each-bookmark", function(event) {

        showPopup(menu, event);
        var target = $(event.target).closest(".each-bookmark");
        menu.data("target-bookmark", target);
        event.preventDefault();
    });
}

function setContextMenuForTags() {
    var menu = $("#tag-context-menu");

    $("#fragment-group, #tag-palette-panel")
    .off("contextmenu.cvz_tag").on("contextmenu.cvz_tag", ".each-tag", function(event) {

        showPopup(menu, event);
        var target = $(event.target).closest(".each-tag");
        menu.data("target-tag", target);
        var tid = target.attr("_tid");
        if (tid <=0) {
            // special tags; not modifiable
            $("#tag-palette-form\\:edit").hide();
            $("#tag-palette-form\\:trash").hide();
        }
        else {
            $("#tag-palette-form\\:edit").show();
            $("#tag-palette-form\\:trash").show();
        }
        $("#tag-palette-form\\:id-placeholder-for-tag").val(tid);
        event.preventDefault();
    });
}
function setContextMenuForSelections() {
    var menu = $("#selection-box-context-menu");

    $("#selection-box")
    .off("contextmenu.cvz_sb").on("contextmenu.cvz_sb", function(event) {

        var fragments = getSelectedFragments();
        menu.find("#selection-box-form\\:bookmark").show();
        showOrHide(menu.find("#selection-box-form\\:relate"), fragments.length > 1);
        menu.find("#selection-box-form\\:trash").show();
        menu.find("#selection-box-form\\:unselect").show();
        menu.find("#selection-box-form\\:select_unselect").hide();
        if (fragments.length > 0)
            showPopup(menu, event);
        event.preventDefault();
    });

    $("#selection-box-form\\:selection-box-panel")
    .off("contextmenu.cvz_sb").on("contextmenu.cvz_sb", ".each-selected-frg", function(event) {

        var target = $(event.target).closest(".each-selected-frg");
        if (isNaN(parseInt(target.attr("_fid"))))
            return;

        menu.find("#selection-box-form\\:bookmark").hide();
        menu.find("#selection-box-form\\:relate").hide();
        menu.find("#selection-box-form\\:trash").hide();
        menu.find("#selection-box-form\\:unselect").hide();
        menu.find("#selection-box-form\\:select_unselect").show();

        showPopup(menu, event);
        menu.data("target-fragment", target);
        event.preventDefault();
    });
}

function setContextMenuForFiles() {
    var menu = $("#file-context-menu");

    $("#file-box-form\\:file-box-panel")
    .off("contextmenu.cvz_file").on("contextmenu.cvz_file", ".each-file, #file-path-tree", function(event) {
        showPopup(menu, event);
        var target = $(event.target);
        if (target.attr("_isFolder") === "false") {
            menu.find("#file-box-form\\:new-folder").hide();
        }
        else {
            menu.find("#file-box-form\\:new-folder").show();
        }
        if (isNaN(parseInt(target.attr("_id")))) {
            // the menu has no specified target;
            // the target will be the root folder
            menu.find("#file-box-form\\:rename").hide();
            menu.find("#file-box-form\\:move").hide();
            menu.find("#file-box-form\\:delete").hide();
        }
        else {
            // the menu has a target file or folder
            menu.find("#file-box-form\\:rename").show();
            menu.find("#file-box-form\\:move").show();
            menu.find("#file-box-form\\:delete").show();
        }
        menu.data("target-file", target);
        event.preventDefault();
    });
}

function completeContextMenuSetup() {
    $(document).off("click.cvz_ctxtm_off").on("click.cvz_ctxtm_off", function(event) {
        $("#frg-context-menu, #bookmark-context-menu, #tag-context-menu, #selection-box-context-menu, #file-context-menu")
        .hide();
    });
}

function setupContextMenus() {
    // Add "rclick-disabled" class to whatever element
    // that needs to keep from invoking browsers's default context menu.
    $(".rclick-disabled").off("contextmenu.cvz_rcd").on("contextmenu.cvz_rcd", function(e) {
        e.preventDefault();
    });

    setContextMenuForFragments();
    setContextMenuForBookmarks();
    setContextMenuForTags();
    setContextMenuForSelections();
    setContextMenuForFiles();

    completeContextMenuSetup();
}
<|endoftext|>


<commit_before>function makeBreakable(canvasId, centerX, centerY, radius) {
    var canvas = document.getElementById(canvasId);
    var context = canvas.getContext("2d");
    var i = 0;

    var spikes = [], midpoints = [];
    for (i = 0; i < 5; i += 1) {
        spikes[i] = {
            r: radius,
            theta: 2 * i * Math.PI / 5 - Math.PI / 2
        };
    }

    midpoints = [
        {r: 0.55 * radius, theta: -3 * Math.PI / 10},
        {r: 0.60 * radius, theta: Math.PI / 10},
        {r: 0.60 * radius, theta: 5 * Math.PI / 10},
        {r: 0.60 * radius, theta: 9 * Math.PI / 10},
        {r: 0.55 * radius, theta: 13 * Math.PI / 10}
    ];

    return {
        draw: function () {
            var width = window.innerWidth;
            var height = window.innerHeight;

            var canvasCenterX = width * (centerX / 1000);
            var canvasCenterY = height * (centerY / 1000);
            var canvasRadius = height * (radius / 1000);

            var cSpikes, cMidpoints;
            var i = 0;

            var map = function (r, theta) {
                var cr = height * (r / 1000);
                return mapToCenter(cr, theta, canvasCenterX, canvasCenterY);
            }

            canvas.width = width;
            canvas.height = height;

            cSpikes = Array.map(spikes, function (point) {
                return map(point.r, point.theta);
            });
            cMidpoints = Array.map(midpoints, function (point) {
                return map(point.r, point.theta);
            });

            context.save();
            context.strokeStyle = "white";

            for (i = 0; i < 5; i++) {
                context.beginPath();
                context.moveTo(canvasCenterX, canvasCenterY);
                context.lineTo(cSpikes[i].x, cSpikes[i].y);
                context.lineTo(cMidpoints[i].x, cMidpoints[i].y);
                context.lineTo(canvasCenterX, canvasCenterY);
                context.stroke();
                context.closePath();

                context.beginPath();
                context.moveTo(canvasCenterX, canvasCenterY);
                context.lineTo(cSpikes[i].x, cSpikes[i].y);
                context.lineTo(cMidpoints[(i+4) % 5].x, cMidpoints[(i+4) % 5].y);
                context.stroke();
                context.closePath();
            }
            context.restore();
        },
    };
}

<commit_msg>Is it just me, or does the shading on that star look really unnatural?<commit_after>function makeBreakable(canvasId, centerX, centerY, radius) {
    var canvas = document.getElementById(canvasId);
    var context = canvas.getContext("2d");
    var i = 0;

    var spikes = [], midpoints = [], faceFills = [];
    for (i = 0; i < 5; i += 1) {
        spikes[i] = {
            r: radius,
            theta: 2 * i * Math.PI / 5 - Math.PI / 2
        };
    }

    midpoints = [
        {r: 0.55 * radius, theta: -3 * Math.PI / 10},
        {r: 0.60 * radius, theta: Math.PI / 10},
        {r: 0.60 * radius, theta: 5 * Math.PI / 10},
        {r: 0.60 * radius, theta: 9 * Math.PI / 10},
        {r: 0.55 * radius, theta: 13 * Math.PI / 10}
    ];

    faceFills = [
        {a: "#99aacc", c: "#bbccee"},
        {a: "#bbccee", c: "#9988af"},
        {a: "#99aacc", c: "#9988af"},
        {a: "#9988af", c: "#99aacc"},
        {a: "#9988af", c: "#99aacc"}
    ];

    return {
        draw: function () {
            var width = window.innerWidth;
            var height = window.innerHeight;

            var canvasCenterX = width * (centerX / 1000);
            var canvasCenterY = height * (centerY / 1000);
            var canvasRadius = height * (radius / 1000);

            var cSpikes, cMidpoints;
            var i = 0, ai = 0;

            var map = function (r, theta) {
                var cr = height * (r / 1000);
                return mapToCenter(cr, theta, canvasCenterX, canvasCenterY);
            }

            canvas.width = width;
            canvas.height = height;

            cSpikes = Array.map(spikes, function (point) {
                return map(point.r, point.theta);
            });
            cMidpoints = Array.map(midpoints, function (point) {
                return map(point.r, point.theta);
            });

            context.save();
            context.strokeStyle = "#8888aa";

            for (i = 0; i < 5; i++) {
                ai = (i + 4) % 5; // anticlockwise index

                // draw face in clockwise direction
                context.beginPath();
                context.moveTo(canvasCenterX, canvasCenterY);
                context.lineTo(cSpikes[i].x, cSpikes[i].y);
                context.lineTo(cMidpoints[i].x, cMidpoints[i].y);
                context.lineTo(canvasCenterX, canvasCenterY);
                context.fillStyle = faceFills[i]["c"];
                context.fill();
                context.stroke();
                context.closePath();

                // draw face in anticlockwise direction
                context.beginPath();
                context.moveTo(canvasCenterX, canvasCenterY);
                context.lineTo(cSpikes[i].x, cSpikes[i].y);
                context.lineTo(cMidpoints[(i+4) % 5].x, cMidpoints[(i+4) % 5].y);
                context.fillStyle = faceFills[i]["a"];
                context.fill();
                context.stroke();
                context.closePath();
            }
            context.restore();
        },
    };
}

<|endoftext|>