<commit_before>var pomelo = require('pomelo');
var channelUtil = require('../../util/channelUtil');
var MessageService = require('../../services/messageService');
var WYMusicService = require('../../services/wyMusicService.js');
var ProxyService = require('../../services/proxyService.js');

var studio = function (opts) {
    this.studioId = opts.id;

    this.users = {};
    this.playerList = {};
    this.songs = [];
    this.playingSong = null;
    this.channel = null;
}

module.exports = studio;

studio.prototype.getChannel = function () {
    if (!this.channel) {
        var channelName = channelUtil.getStudioChannelName(this.studioId);
        this.channel = pomelo.app.get('channelService').getChannel(channelName, true);
    }

    return this.channel;
};

studio.prototype.pushByUserName = function (userName, route, msg, cb) {
    var user = this.getUser(userName);
    if (!user) {
        cb(new Error('user[' + userName + '] is not in this studio'));
        return;
    }
    MessageService.pushMessageToUser({ uid: user.name, sid: user.serverId }, route, msg);
    pomelo.app.get('channelService').pushMessageByUids(route, msg, [{ uid: user.userName, sid: user.serverId }], cb);
};

studio.prototype.getPlayerMusicList = function () {
    var playerList = this.playerList;
    var songs = this.songs;
    var list = [];
    for (var n in songs) {
        list.push(playerList[songs[n].id]);
    }
    return list;
};

studio.prototype.getMusic = function (id, cb) {
    var music = this.playerList[id];
    if (!music) {
        cb('music not exist! ');
        return;
    }
    return music;
};

studio.prototype.addMusic = function (url, userName, cb) {
    var self = this;
    var getMusicFunc = function (err, music) {
        if (!!err) {
            cb('get music by url error! ');
            return;
        }
        if(!music.resourceUrl){
            self.getChannel().pushMessage('onMusicAdd', null, cb);
            return;
        }
        music.orderer = userName;
        if (!self.playerList[music.id]) {
            self.songs.push(music);
        }
        self.playerList[music.id] = music;
        self.getChannel().pushMessage('onMusicAdd', music, cb);
    };
    if (pomelo.app.get('appConfig').useProxy) {
        ProxyService.getIp(function (err, ip) {
            WYMusicService.getMusicByUrl(url, ip, getMusicFunc);
        });
    }
    else {
        WYMusicService.getMusicByUrl(url, null, getMusicFunc);
    }
};

studio.prototype.playMusic = function (id, cb) {
    var music = this.playerList[id];
    if (!music) {
        cb('music not exist! ');
        return;
    }
    this.playingSong = music;
    this.getChannel().pushMessage('onMusicPlay', music, cb);
};

studio.prototype.removeMusic = function (id, cb) {
    var songs = this.songs;
    delete this.playerList[id];
    for (var n in songs) {
        if (songs[n].id == id) {
            songs.splice(n, 1);
            break;
        }
    }
    if (this.playingSong.id == id) {
        this.playingSong = null;
    }
    this.getChannel().pushMessage('onMusicRemove', { id: id }, cb);
};

studio.prototype.getUser = function (userName) {
    return this.users[userName];
};

studio.prototype.addUser = function (user) {
    this.users[user.name] = user;
    this.getChannel().add(user.name, user.serverId);
};

studio.prototype.removeUser = function (userName) {
    var user = this.users[userName];
    this.getChannel().leave(user.name, user.serverId);
    delete this.users[userName];
};

studio.prototype.getPlayingSong = function () {
    return this.playingSong;
}
<commit_msg>remove update music<commit_after>var pomelo = require('pomelo');
var channelUtil = require('../../util/channelUtil');
var MessageService = require('../../services/messageService');
var WYMusicService = require('../../services/wyMusicService.js');
var ProxyService = require('../../services/proxyService.js');

var studio = function (opts) {
    this.studioId = opts.id;

    this.users = {};
    this.playerList = {};
    this.songs = [];
    this.playingSong = null;
    this.channel = null;
}

module.exports = studio;

studio.prototype.getChannel = function () {
    if (!this.channel) {
        var channelName = channelUtil.getStudioChannelName(this.studioId);
        this.channel = pomelo.app.get('channelService').getChannel(channelName, true);
    }

    return this.channel;
};

studio.prototype.pushByUserName = function (userName, route, msg, cb) {
    var user = this.getUser(userName);
    if (!user) {
        cb(new Error('user[' + userName + '] is not in this studio'));
        return;
    }
    MessageService.pushMessageToUser({ uid: user.name, sid: user.serverId }, route, msg);
    pomelo.app.get('channelService').pushMessageByUids(route, msg, [{ uid: user.userName, sid: user.serverId }], cb);
};

studio.prototype.getPlayerMusicList = function () {
    var playerList = this.playerList;
    var songs = this.songs;
    var list = [];
    for (var n in songs) {
        list.push(playerList[songs[n].id]);
    }
    return list;
};

studio.prototype.getMusic = function (id, cb) {
    var music = this.playerList[id];
    if (!music) {
        cb('music not exist! ');
        return;
    }
    return music;
};

studio.prototype.addMusic = function (url, userName, cb) {
    var self = this;
    var getMusicFunc = function (err, music) {
        if (!!err) {
            cb('get music by url error! ');
            return;
        }
        if(!music.resourceUrl){
            self.getChannel().pushMessage('onMusicAdd', null, cb);
            return;
        }
        if(self.playerList[music.id]){
            cb('music already existed! ');
            return;
        }
        music.orderer = userName;
        self.songs.push(music);
        self.playerList[music.id] = music;
        self.getChannel().pushMessage('onMusicAdd', music, cb);
    };
    if (pomelo.app.get('appConfig').useProxy) {
        ProxyService.getIp(function (err, ip) {
            WYMusicService.getMusicByUrl(url, ip, getMusicFunc);
        });
    }
    else {
        WYMusicService.getMusicByUrl(url, null, getMusicFunc);
    }
};

studio.prototype.playMusic = function (id, cb) {
    var music = this.playerList[id];
    if (!music) {
        cb('music not exist! ');
        return;
    }
    this.playingSong = music;
    this.getChannel().pushMessage('onMusicPlay', music, cb);
};

studio.prototype.removeMusic = function (id, cb) {
    var songs = this.songs;
    delete this.playerList[id];
    for (var n in songs) {
        if (songs[n].id == id) {
            songs.splice(n, 1);
            break;
        }
    }
    if (this.playingSong.id == id) {
        this.playingSong = null;
    }
    this.getChannel().pushMessage('onMusicRemove', { id: id }, cb);
};

studio.prototype.getUser = function (userName) {
    return this.users[userName];
};

studio.prototype.addUser = function (user) {
    this.users[user.name] = user;
    this.getChannel().add(user.name, user.serverId);
};

studio.prototype.removeUser = function (userName) {
    var user = this.users[userName];
    this.getChannel().leave(user.name, user.serverId);
    delete this.users[userName];
};

studio.prototype.getPlayingSong = function () {
    return this.playingSong;
}
<|endoftext|>


<commit_before>/**
 * jQuery Form Field Dependency ( dependsOn ) JavaScript Library
 * Version: 2.0.0
 * Author: Emran Ahmed (emran.bd.08@gmail.com)
 * Website: https://github.com/EmranAhmed/Form-Field-Dependency
 * Docs: https://github.com/EmranAhmed/Form-Field-Dependency
 * Repo: https://github.com/EmranAhmed/Form-Field-Dependency
 * Issues: https://github.com/EmranAhmed/Form-Field-Dependency/issues
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license
 */

(function (window) {

    'use strict'

    const Plugin = (($) => {

        return class {

            DEFAULTS = {
                attribute : 'data-dependency',
            }

            constructor(element, options = {}) {
                this.$element = $(element)
                this.settings = $.extend(true, {}, this.DEFAULTS, options)
                this.init();
                this.action();
            }

            init() {
                this.$element.addClass('has-dependency-data');

                let attribute = this.settings.attribute.trim()

                let conditionString = this.$element.attr(attribute).replace(/'/g, '"')

                this.conditions = JSON.parse(conditionString);

                let success = this.check();
                this.showHide(success);
            }

            showHide(success) {
                if (success) {
                    this.$element.removeClass('dependency-show').addClass('dependency-show')
                    return true;
                }
                else {
                    this.$element.removeClass('dependency-show')
                    return false;
                }
            }

            check() {
                return this.conditions.every((conditionObj) => {

                    let selectors = Object.keys(conditionObj);

                    return selectors.every((selector) => {

                        let condition = conditionObj[selector];

                        return this.decision(selector, condition)
                    })
                })
            }

            action() {
                this.conditions.forEach((rules) => {

                    for (const [selector, rule] of Object.entries(rules)) {
                        // @TODO: Some SelectBox like select2 doesn't trigger input event
                        $(document.body).on('input.dependency change.dependency', selector, (event) => {
                            let success = this.check();
                            this.showHide(success);
                        })
                    }
                })
            }

            getValue(selector) {

                let values = []

                if (selector) {
                    let inputType = $(selector).prop('type').toLowerCase()

                    let currentSelector = selector;

                    if (['checkbox', 'radio'].includes(inputType)) {
                        currentSelector = `${selector}:checked`
                    }

                    if ('select-multiple' === inputType) {
                        currentSelector = `${selector} option:selected`
                    }

                    $(currentSelector).each((index, element) => {
                        let value = $(element).val().trim();
                        values.push(value)
                    })
                }

                return values.filter(value => value !== '');
            }

            decision(selector, condition) {

                let type         = condition['type'];
                let currentValue = this.getValue(selector)

                let checkValue = (typeof condition['value'] === 'undefined') ? false : condition['value'];

                let minValue = (typeof condition['min'] === 'undefined') ? false : parseInt(condition['min']);
                let maxValue = (typeof condition['max'] === 'undefined') ? false : parseInt(condition['max']);

                let allowEmpty = (typeof condition['empty'] === 'undefined') ? false : condition['empty'];
                let isEmpty    = (!allowEmpty && currentValue.length < 1)

                let likeSelector      = (typeof condition['like'] === 'undefined') ? false : condition['like'];
                let likeSelectorValue = this.getValue(likeSelector)

                let regExpPattern  = (typeof condition['pattern'] === 'undefined') ? false : condition['pattern'];
                let regExpModifier = (typeof condition['modifier'] === 'undefined') ? 'gi' : condition['modifier'];
                let sign           = (typeof condition['sign'] === 'undefined') ? false : condition['sign'];
                let strict         = (typeof condition['strict'] === 'undefined') ? false : condition['strict'];

                let emptyTypes    = ['empty', 'blank']
                let notEmptyTypes = ['!empty', 'notEmpty', 'not-empty', 'notempty']

                let equalTypes    = ['equal', '=', '==', '===']
                let notEqualTypes = ['!equal', '!=', '!==', '!===', 'notEqual', 'not-equal', 'notequal']

                let regularExpressionTypes = ['regexp', 'exp', 'expression', 'match']

                // if empty return true
                if (emptyTypes.includes(type)) {
                    return (currentValue.length < 1);
                }

                // if not empty return true
                if (notEmptyTypes.includes(type)) {
                    return (currentValue.length > 0)
                }

                // if equal return true
                if (equalTypes.includes(type)) {

                    if (isEmpty) {
                        return false
                    }

                    // Match two selector value/s
                    if (likeSelector) {

                        if (strict) {
                            return likeSelectorValue.every((value) => {
                                return currentValue.includes(value)
                            })
                        }
                        else {
                            return likeSelectorValue.some((value) => {
                                return currentValue.includes(value)
                            })
                        }
                    }

                    // Match pre-defined value/s
                    if (strict) {

                        if (checkValue && Array.isArray(checkValue)) {
                            return checkValue.every((value) => {
                                return currentValue.includes(value);
                            })
                        }

                        if (checkValue && !Array.isArray(checkValue)) {
                            return currentValue.includes(checkValue);
                        }
                    }

                    else {

                        if (checkValue && Array.isArray(checkValue)) {
                            return checkValue.some((value) => {
                                return currentValue.includes(value);
                            })
                        }

                        if (checkValue && !Array.isArray(checkValue)) {

                            /*return currentValue.find(value => {
                                return value.toLowerCase() === checkValue.toLowerCase();
                            });*/

                            return currentValue.includes(checkValue);
                        }
                    }
                }

                // if not equal return true
                if (notEqualTypes.includes(type)) {

                    if (isEmpty) {
                        return false
                    }

                    // Match two selector value/s
                    if (likeSelector) {

                        if (strict) {
                            return likeSelectorValue.every((value) => {
                                return !currentValue.includes(value)
                            })
                        }
                        else {
                            return likeSelectorValue.some((value) => {
                                return !currentValue.includes(value)
                            })
                        }
                    }

                    // Match pre-defined value/s
                    if (strict) {

                        if (checkValue && Array.isArray(checkValue)) {
                            return checkValue.every((value) => {
                                return !currentValue.includes(value);
                            })
                        }

                        if (checkValue && !Array.isArray(checkValue)) {
                            return !currentValue.includes(checkValue);
                        }

                    }
                    else {

                        if (checkValue && Array.isArray(checkValue)) {
                            return checkValue.some((value) => {
                                return !currentValue.includes(value);
                            })
                        }

                        if (checkValue && !Array.isArray(checkValue)) {
                            return !currentValue.includes(checkValue);
                        }
                    }
                }

                // if regexp match
                if ((regularExpressionTypes.includes(type)) && regExpPattern) {

                    if (isEmpty) {
                        return false
                    }

                    let exp = new RegExp(regExpPattern, regExpModifier)
                    return currentValue.every((value) => {
                        return exp.test(value)
                    })
                }

                // if length
                if ('length' === type) {

                    if (isEmpty) {
                        return false
                    }

                    if (checkValue && Array.isArray(checkValue)) {
                        minValue = parseInt(checkValue[0]);
                        maxValue = (typeof checkValue[1] === 'undefined') ? false : parseInt(checkValue[1]);
                    }

                    if (checkValue && !Array.isArray(checkValue)) {
                        minValue = parseInt(checkValue);
                        maxValue = false;
                    }

                    return currentValue.every((value) => {
                        if (!maxValue) {
                            return value.length >= minValue;
                        }

                        if (!minValue) {
                            return value.length <= maxValue;
                        }

                        return value.length >= minValue && value.length <= maxValue;

                    })
                }

                // if range
                if ('range' === type) {

                    if (isEmpty) {
                        return false
                    }

                    if (checkValue && Array.isArray(checkValue)) {
                        minValue = parseInt(checkValue[0]);
                        maxValue = (typeof checkValue[1] === 'undefined') ? false : parseInt(checkValue[1]);
                    }

                    return currentValue.every((value) => {
                        if (!maxValue) {
                            return parseInt(value) > minValue;
                        }

                        if (!minValue) {
                            return parseInt(value) < maxValue;
                        }

                        return parseInt(value) > minValue && parseInt(value) < maxValue;

                    })
                }

                // if compare
                if ('compare' === type && sign && checkValue) {

                    if (isEmpty) {
                        return false
                    }

                    checkValue = parseInt(checkValue)

                    switch (sign) {
                        case '<':
                            return currentValue.every((value) => {
                                return parseInt(value) < checkValue;
                            })
                            break;

                        case '<=':
                            return currentValue.every((value) => {
                                return parseInt(value) <= checkValue;
                            })
                            break;

                        case '>':
                            return currentValue.every((value) => {
                                return parseInt(value) > checkValue;
                            })
                            break;

                        case '>=':
                            return currentValue.every((value) => {
                                return parseInt(value) >= checkValue;
                            })
                            break;

                        case '=':
                        case '==':
                            return currentValue.every((value) => {
                                return parseInt(value) === checkValue;
                            })
                            break;
                    }

                }

                // $( document.body ).triggerHandler( 'depends-on',[selector, condition, this])

            }
        }

    })(jQuery)

    const jQueryPlugin = (($) => {

        return (PluginName, ClassName) => {

            $.fn[PluginName] = function (options, ...args) {
                return this.each((index, element) => {

                    let $element = $(element)
                    let data     = $element.data(PluginName)

                    if (!data) {
                        data = new ClassName($element, $.extend({}, options))
                        $element.data(PluginName, data)
                    }

                    if (typeof options === 'string') {

                        if (typeof data[options] === 'object') {
                            return data[options]
                        }

                        if (typeof data[options] === 'function') {
                            return data[options](...args)
                        }
                    }

                    return this
                })
            }

            // Constructor
            $.fn[PluginName].Constructor = ClassName

            // Short Hand
            $[PluginName] = (options, ...args) => $({})[PluginName](options, ...args)

            // No Conflict
            $.fn[PluginName].noConflict = () => $.fn[PluginName]
        }

    })(jQuery)

    jQueryPlugin('dependsOn', Plugin)

})(window);<commit_msg>Update<commit_after>/**
 * jQuery Form Field Dependency ( dependsOn ) JavaScript Library
 * Version: 2.0.0
 * Author: Emran Ahmed (emran.bd.08@gmail.com)
 * Website: https://github.com/EmranAhmed/Form-Field-Dependency
 * Docs: https://github.com/EmranAhmed/Form-Field-Dependency
 * Repo: https://github.com/EmranAhmed/Form-Field-Dependency
 * Issues: https://github.com/EmranAhmed/Form-Field-Dependency/issues
 * Copyright OpenJS Foundation and other contributors
 * Released under the MIT license
 */

(function (window) {

    'use strict'

    const Plugin = (($) => {

        return class {

            DEFAULTS = {
                attribute : 'data-dependency',
            }

            constructor(element, options, name) {
                this.name     = name
                this.$element = $(element)
                this.settings = $.extend(true, {}, this.DEFAULTS, options)
                this.init();
                this.action();
            }

            init() {
                this.$element.addClass('has-dependency-data');

                let attribute = this.settings.attribute.trim()

                let conditionString = this.$element.attr(attribute).replace(/'/g, '"')

                this.conditions = JSON.parse(conditionString);

                let success = this.check();
                this.showHide(success);
            }

            showHide(success) {
                if (success) {
                    this.$element.removeClass('dependency-show').addClass('dependency-show')
                    return true;
                }
                else {
                    this.$element.removeClass('dependency-show')
                    return false;
                }
            }

            check() {
                return this.conditions.every((conditionObj) => {

                    let selectors = Object.keys(conditionObj);

                    return selectors.every((selector) => {

                        let condition = conditionObj[selector];

                        return this.decision(selector, condition)
                    })
                })
            }

            action() {
                this.conditions.forEach((rules) => {

                    for (const [selector, rule] of Object.entries(rules)) {
                        // @TODO: Some SelectBox like select2 doesn't trigger input event
                        $(document.body).on('input.dependency change.dependency', selector, (event) => {
                            let success = this.check();
                            this.showHide(success);
                        })
                    }
                })
            }

            getValue(selector) {

                let values = []

                if (selector && $(selector).length > 0) {
                    let inputType = $(selector).prop('type').toLowerCase()

                    let currentSelector = selector;

                    if (['checkbox', 'radio'].includes(inputType)) {
                        currentSelector = `${selector}:checked`
                    }

                    if ('select-multiple' === inputType) {
                        currentSelector = `${selector} option:selected`
                    }

                    $(currentSelector).each((index, element) => {
                        let value = $(element).val().trim();
                        values.push(value)
                    })
                }

                return values.filter(value => value !== '');
            }

            decision(selector, condition) {

                let type         = condition['type'];
                let currentValue = this.getValue(selector)

                let checkValue = (typeof condition['value'] === 'undefined') ? false : condition['value'];

                let minValue = (typeof condition['min'] === 'undefined') ? false : parseInt(condition['min']);
                let maxValue = (typeof condition['max'] === 'undefined') ? false : parseInt(condition['max']);

                let allowEmpty = (typeof condition['empty'] === 'undefined') ? false : condition['empty'];
                let isEmpty    = (!allowEmpty && currentValue.length < 1)

                let likeSelector      = (typeof condition['like'] === 'undefined') ? false : condition['like'];
                let likeSelectorValue = this.getValue(likeSelector)

                let regExpPattern  = (typeof condition['pattern'] === 'undefined') ? false : condition['pattern'];
                let regExpModifier = (typeof condition['modifier'] === 'undefined') ? 'gi' : condition['modifier'];
                let sign           = (typeof condition['sign'] === 'undefined') ? false : condition['sign'];
                let strict         = (typeof condition['strict'] === 'undefined') ? false : condition['strict'];

                let emptyTypes    = ['empty', 'blank']
                let notEmptyTypes = ['!empty', 'notEmpty', 'not-empty', 'notempty']

                let equalTypes    = ['equal', '=', '==', '===']
                let notEqualTypes = ['!equal', '!=', '!==', '!===', 'notEqual', 'not-equal', 'notequal']

                let regularExpressionTypes = ['regexp', 'exp', 'expression', 'match']

                // if empty return true
                if (emptyTypes.includes(type)) {
                    return (currentValue.length < 1);
                }

                // if not empty return true
                if (notEmptyTypes.includes(type)) {
                    return (currentValue.length > 0)
                }

                // if equal return true
                if (equalTypes.includes(type)) {

                    if (isEmpty) {
                        return false
                    }

                    // Match two selector value/s
                    if (likeSelector) {

                        if (strict) {
                            return likeSelectorValue.every((value) => {
                                return currentValue.includes(value)
                            })
                        }
                        else {
                            return likeSelectorValue.some((value) => {
                                return currentValue.includes(value)
                            })
                        }
                    }

                    // Match pre-defined value/s
                    if (strict) {

                        if (checkValue && Array.isArray(checkValue)) {
                            return checkValue.every((value) => {
                                return currentValue.includes(value);
                            })
                        }

                        if (checkValue && !Array.isArray(checkValue)) {
                            return currentValue.includes(checkValue);
                        }
                    }

                    else {

                        if (checkValue && Array.isArray(checkValue)) {
                            return checkValue.some((value) => {
                                return currentValue.includes(value);
                            })
                        }

                        if (checkValue && !Array.isArray(checkValue)) {

                            /*return currentValue.find(value => {
                                return value.toLowerCase() === checkValue.toLowerCase();
                            });*/

                            return currentValue.includes(checkValue);
                        }
                    }
                }

                // if not equal return true
                if (notEqualTypes.includes(type)) {

                    if (isEmpty) {
                        return false
                    }

                    // Match two selector value/s
                    if (likeSelector) {

                        if (strict) {
                            return likeSelectorValue.every((value) => {
                                return !currentValue.includes(value)
                            })
                        }
                        else {
                            return likeSelectorValue.some((value) => {
                                return !currentValue.includes(value)
                            })
                        }
                    }

                    // Match pre-defined value/s
                    if (strict) {

                        if (checkValue && Array.isArray(checkValue)) {
                            return checkValue.every((value) => {
                                return !currentValue.includes(value);
                            })
                        }

                        if (checkValue && !Array.isArray(checkValue)) {
                            return !currentValue.includes(checkValue);
                        }

                    }
                    else {

                        if (checkValue && Array.isArray(checkValue)) {
                            return checkValue.some((value) => {
                                return !currentValue.includes(value);
                            })
                        }

                        if (checkValue && !Array.isArray(checkValue)) {
                            return !currentValue.includes(checkValue);
                        }
                    }
                }

                // if regexp match
                if ((regularExpressionTypes.includes(type)) && regExpPattern) {

                    if (isEmpty) {
                        return false
                    }

                    let exp = new RegExp(regExpPattern, regExpModifier)
                    return currentValue.every((value) => {
                        return exp.test(value)
                    })
                }

                // if length
                if ('length' === type) {

                    if (isEmpty) {
                        return false
                    }

                    if (checkValue && Array.isArray(checkValue)) {
                        minValue = parseInt(checkValue[0]);
                        maxValue = (typeof checkValue[1] === 'undefined') ? false : parseInt(checkValue[1]);
                    }

                    if (checkValue && !Array.isArray(checkValue)) {
                        minValue = parseInt(checkValue);
                        maxValue = false;
                    }

                    return currentValue.every((value) => {
                        if (!maxValue) {
                            return value.length >= minValue;
                        }

                        if (!minValue) {
                            return value.length <= maxValue;
                        }

                        return value.length >= minValue && value.length <= maxValue;

                    })
                }

                // if range
                if ('range' === type) {

                    if (isEmpty) {
                        return false
                    }

                    if (checkValue && Array.isArray(checkValue)) {
                        minValue = parseInt(checkValue[0]);
                        maxValue = (typeof checkValue[1] === 'undefined') ? false : parseInt(checkValue[1]);
                    }

                    return currentValue.every((value) => {
                        if (!maxValue) {
                            return parseInt(value) > minValue;
                        }

                        if (!minValue) {
                            return parseInt(value) < maxValue;
                        }

                        return parseInt(value) > minValue && parseInt(value) < maxValue;

                    })
                }

                // if compare
                if ('compare' === type && sign && checkValue) {

                    if (isEmpty) {
                        return false
                    }

                    checkValue = parseInt(checkValue)

                    switch (sign) {
                        case '<':
                            return currentValue.every((value) => {
                                return parseInt(value) < checkValue;
                            })
                            break;

                        case '<=':
                            return currentValue.every((value) => {
                                return parseInt(value) <= checkValue;
                            })
                            break;

                        case '>':
                            return currentValue.every((value) => {
                                return parseInt(value) > checkValue;
                            })
                            break;

                        case '>=':
                            return currentValue.every((value) => {
                                return parseInt(value) >= checkValue;
                            })
                            break;

                        case '=':
                        case '==':
                            return currentValue.every((value) => {
                                return parseInt(value) === checkValue;
                            })
                            break;
                    }

                }

                // $( document.body ).triggerHandler( 'depends-on',[selector, condition, this])

            }

            destroy() {
                this.$element.removeData(this.name)
            }
        }

    })(jQuery)

    const jQueryPlugin = (($) => {

        return (PluginName, ClassName) => {

            $.fn[PluginName] = function (options, ...args) {
                return this.each((index, element) => {

                    let $element = $(element)
                    let data     = $element.data(PluginName)

                    if (!data) {
                        data = new ClassName($element, $.extend({}, options), PluginName)
                        $element.data(PluginName, data)
                    }

                    if (typeof options === 'string') {

                        if (typeof data[options] === 'object') {
                            return data[options]
                        }

                        if (typeof data[options] === 'function') {
                            return data[options](...args)
                        }
                    }

                    return this
                })
            }

            // Constructor
            $.fn[PluginName].Constructor = ClassName

            // Short Hand
            $[PluginName] = (options, ...args) => $({})[PluginName](options, ...args)

            // No Conflict
            $.fn[PluginName].noConflict = () => $.fn[PluginName]
        }

    })(jQuery)

    jQueryPlugin('dependsOn', Plugin)

})(window);<|endoftext|>


<commit_before>var oscar = (function(o, $) {
    // Replicate Django's flash messages so they can be used by AJAX callbacks.
    o.messages = {
        icons: {
            'info': '',
            'success': '',
            'warning': '',
            'error': ''
        },
        addMessage: function(tag, msg) {
            var iconHTML = o.messages.icons[tag],
                msgHTML = '
' +
                'x' + iconHTML + " " + msg +
                '
';
            $('#messages').append($(msgHTML));
        },
        debug: function(msg) { o.messages.addMessage('debug', msg); },
        info: function(msg) { o.messages.addMessage('info', msg); },
        success: function(msg) { o.messages.addMessage('success', msg); },
        warning: function(msg) { o.messages.addMessage('warning', msg); },
        error: function(msg) { o.messages.addMessage('error:', msg); }
    };

    // This block may need removing after reworking of promotions app
    o.promotions = {
        init: function() {
            $('#myCarousel').carousel({
                interval: 6000
            });
        }
    };

    // Notifications inbox within 'my account' section.
    o.notifications = {
        init: function() {
            $('a[data-behaviours~="archive"]').click(function() {
                o.notifications.checkAndSubmit($(this), 'archive');
            });
            $('a[data-behaviours~="delete"]').click(function() {
                o.notifications.checkAndSubmit($(this), 'delete');
            });
        },
        checkAndSubmit: function($ele, btn_val) {
            $ele.closest('tr').find('input').attr('checked', 'checked');
            $ele.closest('form').find('button[value="' + btn_val + '"]').click();
            return false;
        }
    };

    // Site-wide forms events
    o.forms = {
        init: function() {
            // Forms with this behaviour are 'locked' once they are submitted to
            // prevent multiple submissions
            $('form[data-behaviours~="lock"]').submit(o.forms.submitIfNotLocked);

            // Disable buttons when they are clicked
            $('.js-disable-on-click').click(function(){$(this).button('loading');});
        },
        submitIfNotLocked: function(event) {
            $form = $(this);
            if ($form.data('locked')) {
                return false;
            }
            $form.data('locked', true);
        }
    };

    o.account = {
        init: function() {
            if (document.location.hash) {
                // Ensure the right tab is open if it is specified in the hash.
                var hash = document.location.hash.substring(1),
                $activeClass = $('.account-profile .tabbable'),
                $li = $('a[href=#' + hash + ']').closest('li');
                $activeClass.find('.active').removeClass('active');
                $('#' + hash).add($li).addClass('active');
            }
        }
    };

    o.catalogue = {
        init: function() {
            // Product star rating -- must improve this in python -- this is
            // one of the worst things I have ever come across.  It will die in raging fire
            // very soon.
            $('.product_pod, .span6, .promotion_single').each(function() {
                var sum_total_reviews = $(this).find(".review_count li").length * 5,
                sum_rating_count = 0;
                $(this).find('.review_count li').each(function() {
                    sum_rating_count += parseFloat($(this).text());
                });
                var ave_rating = sum_rating_count / sum_total_reviews *10;
                if (ave_rating <= 2) {
                    ave_rating = 'One';
                } else if (ave_rating <= 4) {
                    ave_rating = 'Two';
                } else if (ave_rating <= 6) {
                    ave_rating = 'Three';
                } else if (ave_rating <= 8) {
                    ave_rating = 'Four';
                } else if (ave_rating <= 10) {
                    ave_rating = 'Five';
                }
                $(this).find('.review_count').after('

').remove();
            });
        }
    };

    o.page = {
        init: function() {
            // Scroll to sections
            $('.top_page a').click(function(e) {
                var href = $(this).attr('href');
                $('html, body').animate({
                    scrollTop: $(href).offset().top
                }, 500);
                e.preventDefault();
            });
        }
    };

    o.responsive = {
        init: function() {
            if (o.responsive.isDesktop()) {
                o.responsive.initNav();
                o.responsive.initCarousel();
            }
        },
        isDesktop: function() {
            return document.body.clientWidth > 767;
        },
        initNav: function() {
            // Initial navigation for desktop
            var $sidebar = $('aside.span3'),
                $browse = $('#browse > .dropdown-menu'),
                $browseOpen = $browse.parent().find('> button[data-toggle]');
            // Set width of nav dropdown to be same as sidebar
            $browse.css('width', $sidebar.outerWidth());
            // Remove click on browse button if menu is currently open
            if (!$browseOpen.length) {
                $browse.parent().find('> a').off('click');
                // Set margin top of aside allow space for open navigation
                $sidebar.css({ marginTop: $browse.outerHeight() });
            }
        },
        initCarousel: function() {
            $('.es-carousel-wrapper').each(function(){
                var gallery = $(this).parent('.rg-thumbs').length;
                // Don't apply this to the gallery carousel
                if (gallery <= 0) {
                    $(this).elastislide({
                        imageW: 175,
                        minItems: 4,
                        onClick: function() {return true;}
                    });
                }
            });
        }
    };

    // IE compabibility hacks
    o.compatibility = {
        init: function() {
            if (!o.compatibility.isIE()) return;
            // Set the width of a select in an overflow hidden container.
            // This is for add-to-basket forms within browing pages
            $('.product_pod select').on({
                mousedown: function(){
                    $(this).addClass("select-open");
                },
                change: function(){
                    $(this).removeClass("select-open");
                }
            });
        },
        isIE: function() {
            return navigator.userAgent.toLowerCase().indexOf("msie") > -1;
        }
    };

    o.basket = {
        is_form_being_submitted: false,
        init: function() {
            $('#content_inner').on('click', '#basket_formset a[data-behaviours~="remove"]', function(event) {
                o.basket.checkAndSubmit($(this), 'form', 'DELETE');
                event.preventDefault();
            });
            $('#content_inner').on('click', '#basket_formset a[data-behaviours~="save"]', function(event) {
                o.basket.checkAndSubmit($(this), 'form', 'save_for_later');
                event.preventDefault();
            });
            $('#content_inner').on('click', '#saved_basket_formset a[data-behaviours~="move"]', function(event) {
                o.basket.checkAndSubmit($(this), 'saved', 'move_to_basket');
            });
            $('#content_inner').on('click', '#saved_basket_formset a[data-behaviours~="remove"]', function(event) {
                o.basket.checkAndSubmit($(this), 'saved', 'DELETE');
                event.preventDefault();
            });
            $('#content_inner').on('click', '#voucher_form_link a', function(event) {
                o.basket.showVoucherForm();
                event.preventDefault();
            });
            $('#content_inner').on('click', '#voucher_form_cancel', function(event) {
                o.basket.hideVoucherForm();
                event.preventDefault();
            });
            $('#content_inner').on('submit', '#basket_formset', o.basket.submitBasketForm);
            if (window.location.hash == '#voucher') {
                o.basket.showVoucherForm();
            }
        },
        submitBasketForm: function(event) {
            $('#messages').html('');
            var payload = $('#basket_formset').serializeArray();
            $.post('/basket/', payload, o.basket.submitFormSuccess, 'json');
            event.preventDefault();
        },
        submitFormSuccess: function(data) {
            $('#content_inner').html(data.content_html);
            $('#messages').html('');
            for (var level in data.messages) {
                for (var i=0; i<data.messages[level].length; i++) {
                    o.messages[level](data.messages[level][i]);
                }
            }
            o.basket.is_form_being_submitted = false;
        },
        showVoucherForm: function() {
            $('#voucher_form_container').show();
            $('#voucher_form_link').hide();
        },
        hideVoucherForm: function() {
            $('#voucher_form_container').hide();
            $('#voucher_form_link').show();
        },
        checkAndSubmit: function($ele, formPrefix, idSuffix) {
            if (o.basket.is_form_being_submitted) {
                return;
            }
            var formID = $ele.attr('data-id');
            var inputID = '#id_' + formPrefix + '-' + formID + '-' + idSuffix;
            $(inputID).attr('checked', 'checked');
            $ele.closest('form').submit();
            o.basket.is_form_being_submitted = true;
        }
    };

    o.checkout = {
        gateway: {
            init: function() {
                var radioWidgets = $('form input[name=options]');
                o.checkout.gateway.handleRadioSelection(radioWidgets.val());
                radioWidgets.change(o.checkout.gateway.handleRadioChange);
            },
            handleRadioChange: function() {
                o.checkout.gateway.handleRadioSelection($(this).val());
            },
            handleRadioSelection: function(value) {
                var pwInput = $('#id_password');
                if (value == 'new') {
                    pwInput.attr('disabled', 'disabled');
                } else {
                    pwInput.removeAttr('disabled');
                }
            }
        }
    };

    o.init = function() {
        o.catalogue.init();
        o.forms.init();
        o.page.init();
        o.responsive.init();
        o.compatibility.init();
    };

    return o;

})(oscar || {}, jQuery);
<commit_msg>Enable Bootstrap tooltips<commit_after>var oscar = (function(o, $) {
    // Replicate Django's flash messages so they can be used by AJAX callbacks.
    o.messages = {
        icons: {
            'info': '',
            'success': '',
            'warning': '',
            'error': ''
        },
        addMessage: function(tag, msg) {
            var iconHTML = o.messages.icons[tag],
                msgHTML = '
' +
                'x' + iconHTML + " " + msg +
                '
';
            $('#messages').append($(msgHTML));
        },
        debug: function(msg) { o.messages.addMessage('debug', msg); },
        info: function(msg) { o.messages.addMessage('info', msg); },
        success: function(msg) { o.messages.addMessage('success', msg); },
        warning: function(msg) { o.messages.addMessage('warning', msg); },
        error: function(msg) { o.messages.addMessage('error:', msg); }
    };

    // This block may need removing after reworking of promotions app
    o.promotions = {
        init: function() {
            $('#myCarousel').carousel({
                interval: 6000
            });
        }
    };

    // Notifications inbox within 'my account' section.
    o.notifications = {
        init: function() {
            $('a[data-behaviours~="archive"]').click(function() {
                o.notifications.checkAndSubmit($(this), 'archive');
            });
            $('a[data-behaviours~="delete"]').click(function() {
                o.notifications.checkAndSubmit($(this), 'delete');
            });
        },
        checkAndSubmit: function($ele, btn_val) {
            $ele.closest('tr').find('input').attr('checked', 'checked');
            $ele.closest('form').find('button[value="' + btn_val + '"]').click();
            return false;
        }
    };

    // Site-wide forms events
    o.forms = {
        init: function() {
            // Forms with this behaviour are 'locked' once they are submitted to
            // prevent multiple submissions
            $('form[data-behaviours~="lock"]').submit(o.forms.submitIfNotLocked);

            // Disable buttons when they are clicked
            $('.js-disable-on-click').click(function(){$(this).button('loading');});
        },
        submitIfNotLocked: function(event) {
            $form = $(this);
            if ($form.data('locked')) {
                return false;
            }
            $form.data('locked', true);
        }
    };

    o.account = {
        init: function() {
            if (document.location.hash) {
                // Ensure the right tab is open if it is specified in the hash.
                var hash = document.location.hash.substring(1),
                $activeClass = $('.account-profile .tabbable'),
                $li = $('a[href=#' + hash + ']').closest('li');
                $activeClass.find('.active').removeClass('active');
                $('#' + hash).add($li).addClass('active');
            }
        }
    };

    o.catalogue = {
        init: function() {
            // Product star rating -- must improve this in python -- this is
            // one of the worst things I have ever come across.  It will die in raging fire
            // very soon.
            $('.product_pod, .span6, .promotion_single').each(function() {
                var sum_total_reviews = $(this).find(".review_count li").length * 5,
                sum_rating_count = 0;
                $(this).find('.review_count li').each(function() {
                    sum_rating_count += parseFloat($(this).text());
                });
                var ave_rating = sum_rating_count / sum_total_reviews *10;
                if (ave_rating <= 2) {
                    ave_rating = 'One';
                } else if (ave_rating <= 4) {
                    ave_rating = 'Two';
                } else if (ave_rating <= 6) {
                    ave_rating = 'Three';
                } else if (ave_rating <= 8) {
                    ave_rating = 'Four';
                } else if (ave_rating <= 10) {
                    ave_rating = 'Five';
                }
                $(this).find('.review_count').after('

').remove();
            });
        }
    };

    o.page = {
        init: function() {
            // Scroll to sections
            $('.top_page a').click(function(e) {
                var href = $(this).attr('href');
                $('html, body').animate({
                    scrollTop: $(href).offset().top
                }, 500);
                e.preventDefault();
            });
            // Tooltips
            $('[rel="tooltip"]').tooltip();
        }
    };

    o.responsive = {
        init: function() {
            if (o.responsive.isDesktop()) {
                o.responsive.initNav();
                o.responsive.initCarousel();
            }
        },
        isDesktop: function() {
            return document.body.clientWidth > 767;
        },
        initNav: function() {
            // Initial navigation for desktop
            var $sidebar = $('aside.span3'),
                $browse = $('#browse > .dropdown-menu'),
                $browseOpen = $browse.parent().find('> button[data-toggle]');
            // Set width of nav dropdown to be same as sidebar
            $browse.css('width', $sidebar.outerWidth());
            // Remove click on browse button if menu is currently open
            if (!$browseOpen.length) {
                $browse.parent().find('> a').off('click');
                // Set margin top of aside allow space for open navigation
                $sidebar.css({ marginTop: $browse.outerHeight() });
            }
        },
        initCarousel: function() {
            $('.es-carousel-wrapper').each(function(){
                var gallery = $(this).parent('.rg-thumbs').length;
                // Don't apply this to the gallery carousel
                if (gallery <= 0) {
                    $(this).elastislide({
                        imageW: 175,
                        minItems: 4,
                        onClick: function() {return true;}
                    });
                }
            });
        }
    };

    // IE compabibility hacks
    o.compatibility = {
        init: function() {
            if (!o.compatibility.isIE()) return;
            // Set the width of a select in an overflow hidden container.
            // This is for add-to-basket forms within browing pages
            $('.product_pod select').on({
                mousedown: function(){
                    $(this).addClass("select-open");
                },
                change: function(){
                    $(this).removeClass("select-open");
                }
            });
        },
        isIE: function() {
            return navigator.userAgent.toLowerCase().indexOf("msie") > -1;
        }
    };

    o.basket = {
        is_form_being_submitted: false,
        init: function() {
            $('#content_inner').on('click', '#basket_formset a[data-behaviours~="remove"]', function(event) {
                o.basket.checkAndSubmit($(this), 'form', 'DELETE');
                event.preventDefault();
            });
            $('#content_inner').on('click', '#basket_formset a[data-behaviours~="save"]', function(event) {
                o.basket.checkAndSubmit($(this), 'form', 'save_for_later');
                event.preventDefault();
            });
            $('#content_inner').on('click', '#saved_basket_formset a[data-behaviours~="move"]', function(event) {
                o.basket.checkAndSubmit($(this), 'saved', 'move_to_basket');
            });
            $('#content_inner').on('click', '#saved_basket_formset a[data-behaviours~="remove"]', function(event) {
                o.basket.checkAndSubmit($(this), 'saved', 'DELETE');
                event.preventDefault();
            });
            $('#content_inner').on('click', '#voucher_form_link a', function(event) {
                o.basket.showVoucherForm();
                event.preventDefault();
            });
            $('#content_inner').on('click', '#voucher_form_cancel', function(event) {
                o.basket.hideVoucherForm();
                event.preventDefault();
            });
            $('#content_inner').on('submit', '#basket_formset', o.basket.submitBasketForm);
            if (window.location.hash == '#voucher') {
                o.basket.showVoucherForm();
            }
        },
        submitBasketForm: function(event) {
            $('#messages').html('');
            var payload = $('#basket_formset').serializeArray();
            $.post('/basket/', payload, o.basket.submitFormSuccess, 'json');
            event.preventDefault();
        },
        submitFormSuccess: function(data) {
            $('#content_inner').html(data.content_html);
            $('#messages').html('');
            for (var level in data.messages) {
                for (var i=0; i<data.messages[level].length; i++) {
                    o.messages[level](data.messages[level][i]);
                }
            }
            o.basket.is_form_being_submitted = false;
        },
        showVoucherForm: function() {
            $('#voucher_form_container').show();
            $('#voucher_form_link').hide();
        },
        hideVoucherForm: function() {
            $('#voucher_form_container').hide();
            $('#voucher_form_link').show();
        },
        checkAndSubmit: function($ele, formPrefix, idSuffix) {
            if (o.basket.is_form_being_submitted) {
                return;
            }
            var formID = $ele.attr('data-id');
            var inputID = '#id_' + formPrefix + '-' + formID + '-' + idSuffix;
            $(inputID).attr('checked', 'checked');
            $ele.closest('form').submit();
            o.basket.is_form_being_submitted = true;
        }
    };

    o.checkout = {
        gateway: {
            init: function() {
                var radioWidgets = $('form input[name=options]');
                o.checkout.gateway.handleRadioSelection(radioWidgets.val());
                radioWidgets.change(o.checkout.gateway.handleRadioChange);
            },
            handleRadioChange: function() {
                o.checkout.gateway.handleRadioSelection($(this).val());
            },
            handleRadioSelection: function(value) {
                var pwInput = $('#id_password');
                if (value == 'new') {
                    pwInput.attr('disabled', 'disabled');
                } else {
                    pwInput.removeAttr('disabled');
                }
            }
        }
    };

    o.init = function() {
        o.catalogue.init();
        o.forms.init();
        o.page.init();
        o.responsive.init();
        o.compatibility.init();
    };

    return o;

})(oscar || {}, jQuery);
<|endoftext|>


<commit_before>const Message = require('./../../orm/Message');
const m2e = require('./../lib/message2embed');
const bot = require('./../bot');
/**
 * This method should return the response directly to the channel
 * @param {*string array} params
 * @param {*message} message
 */
async function command(params, message) {
    if (params.length < 1)
        return message.reply("incorrect usage\nSyntax: ~quote <messageID>");
    let m = await Message.where('messageID', params[0]).fetch();
    if (m) {
        console.log(m);
        const ch = bot.channels.get(m.attributes.channel);
        m = await ch.fetchMessage(m.attributes.messageID);
        console.log("fetching : "+m.id);
        m =m2e(m);
        console.log(m);
        let attach = m.attachments;
        if(attach)
            attach = attach.first();
        message.channel.sendEmbed(m,{file:attach}).catch(console.error);
    }
    else
        message.reply("message not available");
}
/**
 * description of the command
 */
const description = "quotes a message via id";
/**
 * Define Exports
 */
module.exports = {
    execute: command,
    description: description
};
<commit_msg>Update quote.js<commit_after>const Message = require('./../../orm/Message');
const m2e = require('./../lib/message2embed');
const bot = require('./../bot');
/**
 * This method should return the response directly to the channel
 * @param {*string array} params
 * @param {*message} message
 */
async function command(params, message) {
    if (params.length < 1)
        return message.reply("incorrect usage\nSyntax: ~quote <messageID>");
    let m = await Message.where('messageID', params[0]).fetch();
    if (m) {
        console.log(m);
        const ch = bot.channels.get(m.attributes.channel);
        m = await ch.fetchMessage(m.attributes.messageID);
        console.log("fetching : "+m.id);
        let attach = m.attachments;
        m =m2e(m);
        console.log(m);
        if(attach)
            attach = attach.array();
        message.channel.sendEmbed(m,{files:attach}).catch(console.error);
    }
    else
        message.reply("message not available");
}
/**
 * description of the command
 */
const description = "quotes a message via id";
/**
 * Define Exports
 */
module.exports = {
    execute: command,
    description: description
};
<|endoftext|>


<commit_before>import Ember from 'ember';
import FirebaseAdapter from 'emberfire/adapters/firebase';

const {inject, computed} = Ember;

export default FirebaseAdapter.extend({
  firebase: inject.service(),
});
<commit_msg>Remove unused `computed` var in blueprint app adapter<commit_after>import Ember from 'ember';
import FirebaseAdapter from 'emberfire/adapters/firebase';

const { inject } = Ember;

export default FirebaseAdapter.extend({
  firebase: inject.service(),
});
<|endoftext|>


<commit_before>const os = require('os');
const fs = require('fs');
const cp = require('child_process');
const path = require('path');
const express = require('express');
const realWebpack = require('webpack');
const proxy = require('express-http-proxy');
const webpackMiddleware = require('webpack-dev-middleware');
const hotMiddleware = require('webpack-hot-middleware');
const chokidar = require('chokidar');
const generateExamples = require('./example-generator');

const lnk = require('lnk').sync;
const mkdirp = require('mkdir-p').sync;
const colors = require('colors');

const EXPRESS_PORT = 8080;
const PHP_PORT = 8888;
const HOST = '127.0.0.1';
const WINDOWS = /^win/.test(os.platform());

const rewrite = require('express-urlrewrite');

function addWebpackMiddleware(app, configPath, prefix) {
    const webpackConfig = require(path.resolve('./webpack-config/', configPath + '.js'));
    const compiler = realWebpack(webpackConfig);

    app.use(rewrite(new RegExp(`^${prefix}/(.+).hot-update.(json|js)`), `${prefix}${prefix}/$1.hot-update.$2`));

    app.use(
        prefix,
        webpackMiddleware(compiler, {
            noInfo: true,
            publicPath: '/'
        })
    );

    app.use(prefix, hotMiddleware(compiler));
}

function launchPhpCP(app) {
    const php = cp.spawn('php', ['-S', `${HOST}:${PHP_PORT}`, '-t', 'src'], {
        stdio: ['ignore', 'ignore', 'ignore'],
        env: {AG_DEV: 'true'}
    });

    app.use(
        '/',
        proxy(`${HOST}:${PHP_PORT}`, {
            proxyReqOptDecorator: function(proxyReqOpts, srcReq) {
                proxyReqOpts.headers['X-PROXY-HTTP-HOST'] = srcReq.headers.host;
                return proxyReqOpts;
            }
        })
    );

    process.on('exit', () => {
        php.kill();
    });
}

function serveAndWatchAngular(app) {
    const gulpPath = WINDOWS ? 'node_modules\\.bin\\gulp.cmd' : 'node_modules/.bin/gulp';

    const angularWatch = cp.spawn(gulpPath, ['watch'], {
        stdio: 'inherit',
        cwd: '../ag-grid-angular'
    });

    app.use('/dev/ag-grid-angular', express.static('../ag-grid-angular'));

    process.on('exit', () => {
        angularWatch.kill();
    });
}

function launchTSCCheck() {
    if (!fs.existsSync('_dev')) {
        console.log('_dev not present, creating links...');
        const linkType = 'symbolic';
        mkdirp('_dev/ag-grid/dist');
        lnk('../ag-grid/exports.ts', '_dev/ag-grid/', {force: true, type: linkType, rename: 'main.ts'});
        lnk('../ag-grid/src/ts', '_dev/ag-grid/dist', {force: true, type: linkType, rename: 'lib'});
        lnk('../ag-grid-enterprise/', '_dev', {force: true, type: linkType});
        lnk('../ag-grid-react/', '_dev', {force: true, type: linkType});
        lnk('../ag-grid-angular/', '_dev', {force: true, type: linkType});
    }

    const tscPath = WINDOWS ? 'node_modules\\.bin\\tsc.cmd' : 'node_modules/.bin/tsc';

    const tsChecker = cp.spawn(tscPath, ['--watch', '--noEmit']);

    // works:
    //    ..\ag-grid\src\ts\rendering\cellComp.ts(689,9): error TS2304: Cannot find name 'asfdsdf'.
    //    @ ../ag-grid-react/src/reactFrameworkFactory.ts 4:33-75

    tsChecker.stdout.on('data', data => {
        data
            .toString()
            .trim()
            .split('\n')
            .filter(line => line.indexOf('Watching for') === -1 && line.indexOf('File change') === -1)
            .forEach(line => console.log(line.replace('_dev', '..').replace('/dist/lib/', '/src/ts/').red));
    });
}

const exampleDirMatch = new RegExp('src/([-\\w]+)/');
function watchAndGenerateExamples() {
    const callback = file => {
        let dir;
        if (file) {
            console.log(`${file} changed, regenerating`);
            try {
                dir = file.match(exampleDirMatch)[1];
            } catch (e) {
                throw new Error(`'${exampleDirMatch}' did not extract the example dir from '${file}'. Fix the regexp in dev-server.js`);
            }
        }
        console.log('regenerating examples...');
        generateExamples(() => console.log('generation done.'), dir);
    };

    callback();

    chokidar.watch('./src/*/*.php').on('change', callback);
    chokidar.watch('./src/*/*/*.{html,css,js}').on('change', callback);
}

module.exports = callback => {
    const app = express();

    // necessary for plunkers
    app.use(function(req, res, next) {
        res.setHeader('Access-Control-Allow-Origin', '*');
        return next();
    });

    // serve ag-grid, enterprise and react
    addWebpackMiddleware(app, 'standard', '/dev/ag-grid');
    addWebpackMiddleware(app, 'site', '/dist');
    addWebpackMiddleware(app, 'enterprise', '/dev/ag-grid-enterprise');
    addWebpackMiddleware(app, 'enterprise-bundle', '/dev/ag-grid-enterprise-bundle');
    addWebpackMiddleware(app, 'react', '/dev/ag-grid-react');

    // angular is another story
    serveAndWatchAngular(app);
    watchAndGenerateExamples();

    // PHP
    launchPhpCP(app);

    // Watch TS for errors. No actual transpiling happens here, just errors
    launchTSCCheck();

    app.listen(EXPRESS_PORT, function() {
        console.log(`ag-Grid dev server available on http://${HOST}:${EXPRESS_PORT}`);
    });
};
<commit_msg>Fix windows paths<commit_after>const os = require('os');
const fs = require('fs');
const cp = require('child_process');
const path = require('path');
const express = require('express');
const realWebpack = require('webpack');
const proxy = require('express-http-proxy');
const webpackMiddleware = require('webpack-dev-middleware');
const hotMiddleware = require('webpack-hot-middleware');
const chokidar = require('chokidar');
const generateExamples = require('./example-generator');

const lnk = require('lnk').sync;
const mkdirp = require('mkdir-p').sync;
const colors = require('colors');

const EXPRESS_PORT = 8080;
const PHP_PORT = 8888;
const HOST = '127.0.0.1';
const WINDOWS = /^win/.test(os.platform());

const rewrite = require('express-urlrewrite');

function addWebpackMiddleware(app, configPath, prefix) {
    const webpackConfig = require(path.resolve('./webpack-config/', configPath + '.js'));
    const compiler = realWebpack(webpackConfig);

    app.use(rewrite(new RegExp(`^${prefix}/(.+).hot-update.(json|js)`), `${prefix}${prefix}/$1.hot-update.$2`));

    app.use(
        prefix,
        webpackMiddleware(compiler, {
            noInfo: true,
            publicPath: '/'
        })
    );

    app.use(prefix, hotMiddleware(compiler));
}

function launchPhpCP(app) {
    const php = cp.spawn('php', ['-S', `${HOST}:${PHP_PORT}`, '-t', 'src'], {
        stdio: ['ignore', 'ignore', 'ignore'],
        env: {AG_DEV: 'true'}
    });

    app.use(
        '/',
        proxy(`${HOST}:${PHP_PORT}`, {
            proxyReqOptDecorator: function(proxyReqOpts, srcReq) {
                proxyReqOpts.headers['X-PROXY-HTTP-HOST'] = srcReq.headers.host;
                return proxyReqOpts;
            }
        })
    );

    process.on('exit', () => {
        php.kill();
    });
}

function serveAndWatchAngular(app) {
    const gulpPath = WINDOWS ? 'node_modules\\.bin\\gulp.cmd' : 'node_modules/.bin/gulp';

    const angularWatch = cp.spawn(gulpPath, ['watch'], {
        stdio: 'inherit',
        cwd: '../ag-grid-angular'
    });

    app.use('/dev/ag-grid-angular', express.static('../ag-grid-angular'));

    process.on('exit', () => {
        angularWatch.kill();
    });
}

function launchTSCCheck() {
    if (!fs.existsSync('_dev')) {
        console.log('_dev not present, creating links...');
        const linkType = 'symbolic';
        mkdirp('_dev/ag-grid/dist');
        lnk('../ag-grid/exports.ts', '_dev/ag-grid/', {force: true, type: linkType, rename: 'main.ts'});
        lnk('../ag-grid/src/ts', '_dev/ag-grid/dist', {force: true, type: linkType, rename: 'lib'});
        lnk('../ag-grid-enterprise/', '_dev', {force: true, type: linkType});
        lnk('../ag-grid-react/', '_dev', {force: true, type: linkType});
        lnk('../ag-grid-angular/', '_dev', {force: true, type: linkType});
    }

    const tscPath = WINDOWS ? 'node_modules\\.bin\\tsc.cmd' : 'node_modules/.bin/tsc';

    const tsChecker = cp.spawn(tscPath, ['--watch', '--noEmit']);

    // works:
    //    ..\ag-grid\src\ts\rendering\cellComp.ts(689,9): error TS2304: Cannot find name 'asfdsdf'.
    //    @ ../ag-grid-react/src/reactFrameworkFactory.ts 4:33-75

    tsChecker.stdout.on('data', data => {
        data
            .toString()
            .trim()
            .split('\n')
            .filter(line => line.indexOf('Watching for') === -1 && line.indexOf('File change') === -1)
            .forEach(line => console.log(line.replace('_dev', '..').replace('/dist/lib/', '/src/ts/').red));
    });
}

const exampleDirMatch = new RegExp('src/([-\\w]+)/');
function watchAndGenerateExamples() {
    const callback = file => {
        let dir;
        if (file) {
            console.log(`${file} changed, regenerating`);
            try {
                dir = file.replace(/\\/g, '/').match(exampleDirMatch)[1];
            } catch (e) {
                throw new Error(`'${exampleDirMatch}' did not extract the example dir from '${file}'. Fix the regexp in dev-server.js`);
            }
        }
        console.log('regenerating examples...');
        generateExamples(() => console.log('generation done.'), dir);
    };

    callback();

    chokidar.watch('./src/*/*.php').on('change', callback);
    chokidar.watch('./src/*/*/*.{html,css,js}').on('change', callback);
}

module.exports = callback => {
    const app = express();

    // necessary for plunkers
    app.use(function(req, res, next) {
        res.setHeader('Access-Control-Allow-Origin', '*');
        return next();
    });

    // serve ag-grid, enterprise and react
    addWebpackMiddleware(app, 'standard', '/dev/ag-grid');
    addWebpackMiddleware(app, 'site', '/dist');
    addWebpackMiddleware(app, 'enterprise', '/dev/ag-grid-enterprise');
    addWebpackMiddleware(app, 'enterprise-bundle', '/dev/ag-grid-enterprise-bundle');
    addWebpackMiddleware(app, 'react', '/dev/ag-grid-react');

    // angular is another story
    serveAndWatchAngular(app);
    watchAndGenerateExamples();

    // PHP
    launchPhpCP(app);

    // Watch TS for errors. No actual transpiling happens here, just errors
    launchTSCCheck();

    app.listen(EXPRESS_PORT, function() {
        console.log(`ag-Grid dev server available on http://${HOST}:${EXPRESS_PORT}`);
    });
};
<|endoftext|>


<commit_before>/*
 * Copyright 2015 Concept
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Client Routes
 */
Router.route('/', {
  name: 'ConceptIndex'
});

// -- Report routes ---------------------------------------------------

Router.route('/rapporter/side/:page', {
  name: 'Reports',
  controller: 'ReportsController'
});

Router.route('/rapporter', {
  name: 'ReportsIndex',
  onBeforeAction: function() {
    this.redirect('/rapporter/side/1');
  }
});

Router.route('/opprett', {
  name: 'CreateReport',
  controller: 'CreateReportController'
});

Router.route('/rapport/:_id/endre', {
  name: 'EditReport',
  template: 'CreateReport',
  controller: 'EditReportController'
});

Router.route('/rapport/:_id/:slug?', {
  name: 'Report',
  controller: 'ReportViewController'
});

// -- Accounts routes --------------------------------------------------

Router.route('/concept-admin', {
  name: 'AdminLogon',
  template: 'LoginForm',
  controller: 'AdminLogonController'
});

Router.route('/concept-admin-forgotton-password', {
  name: 'AdminForgottonPassword',
  template: 'LoginForm'
});

Router.route('/brukere', {
  name: 'UserControl',
  template: 'UserControl',
  controller: 'UserControlController'
});

// -- Miscellaneous routes ---------------------------------------------

Router.route('/om', {
  name: 'AboutConcept'
});

Router.route('/kriterier', {
  name: 'EvaluationCriteria'
});

// -- Server routes ----------------------------------------------------

Router.route('/pdf/:_id', {
  name: 'pdfFile',
  where: 'server',
  controller: 'PDFExportController'
});

Router.route('/csv', {
  name: 'csvFile',
  where: 'server',
  controller: 'CSVExportController'
});

Router.onBeforeAction(function() {
  Session.set('query', {});
  Session.set('searchQuery', '');
  Session.set('searchBy', 'Navn');
  Session.set('filters', []);
  Session.set('sortBy', 'project.name');
  Session.set('sortOrder', 'asc');
  Session.set('sortType', 'string');
  Session.set('showFilter', false);
  this.next();

}, {
  except: ['Reports']
});

if(Meteor.isClient) {
  //where to put this? we need to subscribe for the account field for the user
  Meteor.subscribe('moreUserData');
}
<commit_msg>Resets the filter and sort parameters.<commit_after>/*
 * Copyright 2015 Concept
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Client Routes
 */
Router.route('/', {
  name: 'ConceptIndex'
});

// -- Report routes ---------------------------------------------------

Router.route('/rapporter/side/:page', {
  name: 'Reports',
  controller: 'ReportsController'
});

Router.route('/rapporter', {
  name: 'ReportsIndex',
  onBeforeAction: function() {
    this.redirect('/rapporter/side/1');
  }
});

Router.route('/opprett', {
  name: 'CreateReport',
  controller: 'CreateReportController'
});

Router.route('/rapport/:_id/endre', {
  name: 'EditReport',
  template: 'CreateReport',
  controller: 'EditReportController'
});

Router.route('/rapport/:_id/:slug?', {
  name: 'Report',
  controller: 'ReportViewController'
});

// -- Accounts routes --------------------------------------------------

Router.route('/concept-admin', {
  name: 'AdminLogon',
  template: 'LoginForm',
  controller: 'AdminLogonController'
});

Router.route('/concept-admin-forgotton-password', {
  name: 'AdminForgottonPassword',
  template: 'LoginForm'
});

Router.route('/brukere', {
  name: 'UserControl',
  template: 'UserControl',
  controller: 'UserControlController'
});

// -- Miscellaneous routes ---------------------------------------------

Router.route('/om', {
  name: 'AboutConcept'
});

Router.route('/kriterier', {
  name: 'EvaluationCriteria'
});

// -- Server routes ----------------------------------------------------

Router.route('/pdf/:_id', {
  name: 'pdfFile',
  where: 'server',
  controller: 'PDFExportController'
});

Router.route('/csv', {
  name: 'csvFile',
  where: 'server',
  controller: 'CSVExportController'
});

if(Meteor.isClient) {
  Router.onBeforeAction(function() {
    Session.set('query', {});
    Session.set('searchQuery', '');
    Session.set('searchBy', 'Navn');
    Session.set('filters', []);
    Session.set('sortBy', 'project.name');
    Session.set('sortOrder', 'asc');
    Session.set('sortType', 'string');
    Session.set('showFilter', false);
    this.next();

  }, {
    except: ['Reports']
  });

  //where to put this? we need to subscribe for the account field for the user
  Meteor.subscribe('moreUserData');
}
<|endoftext|>


<commit_before>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

var argscheck = require('cordova/argscheck'),
    exec = require('cordova/exec'),
    FileTransferError = require('./FileTransferError'),
    ProgressEvent = require('cordova-plugin-file.ProgressEvent');

function newProgressEvent(result) {
    var pe = new ProgressEvent();
    pe.lengthComputable = result.lengthComputable;
    pe.loaded = result.loaded;
    pe.total = result.total;
    return pe;
}

function getUrlCredentials(urlString) {
    var credentialsPattern = /^https?\:\/\/(?:(?:(([^:@\/]*)(?::([^@\/]*))?)?@)?([^:\/?#]*)(?::(\d*))?).*$/,
        credentials = credentialsPattern.exec(urlString);

    return credentials && credentials[1];
}

function getBasicAuthHeader(urlString) {
    var header =  null;

    // This is changed due to MS Windows doesn't support credentials in http uris
    // so we detect them by regexp and strip off from result url
    // Proof: http://social.msdn.microsoft.com/Forums/windowsapps/en-US/a327cf3c-f033-4a54-8b7f-03c56ba3203f/windows-foundation-uri-security-problem

    if (window.btoa) {
        var credentials = getUrlCredentials(urlString);
        if (credentials) {
            var authHeader = "Authorization";
            var authHeaderValue = "Basic " + window.btoa(credentials);

            header = {
                name : authHeader,
                value : authHeaderValue
            };
        }
    }

    return header;
}

function convertHeadersToArray(headers) {
    var result = [];
    for (var header in headers) {
        if (headers.hasOwnProperty(header)) {
            var headerValue = headers[header];
            result.push({
                name: header,
                value: headerValue.toString()
            });
        }
    }
    return result;
}

var idCounter = 0;

/**
 * FileTransfer uploads a file to a remote server.
 * @constructor
 */
var FileTransfer = function() {
    this._id = ++idCounter;
    this.onprogress = null; // optional callback
};

/**
* Given an absolute file path, uploads a file on the device to a remote server
* using a multipart HTTP request.
* @param filePath {String}           Full path of the file on the device
* @param server {String}             URL of the server to receive the file
* @param successCallback (Function}  Callback to be invoked when upload has completed
* @param errorCallback {Function}    Callback to be invoked upon error
* @param options {FileUploadOptions} Optional parameters such as file name and mimetype
* @param trustAllHosts {Boolean} Optional trust all hosts (e.g. for self-signed certs), defaults to false
*/
FileTransfer.prototype.upload = function(filePath, server, successCallback, errorCallback, options, trustAllHosts) {
    argscheck.checkArgs('ssFFO*', 'FileTransfer.upload', arguments);
    // check for options
    var fileKey = null;
    var fileName = null;
    var mimeType = null;
    var params = null;
    var chunkedMode = true;
    var headers = null;
    var httpMethod = null;
    var basicAuthHeader = getBasicAuthHeader(server);
    if (basicAuthHeader) {
        server = server.replace(getUrlCredentials(server) + '@', '');

        options = options || {};
        options.headers = options.headers || {};
        options.headers[basicAuthHeader.name] = basicAuthHeader.value;
    }

    if (options) {
        fileKey = options.fileKey;
        fileName = options.fileName;
        mimeType = options.mimeType;
        headers = options.headers;
        httpMethod = options.httpMethod || "POST";
        if (httpMethod.toUpperCase() == "PUT"){
            httpMethod = "PUT";
        } else {
            httpMethod = "POST";
        }
        if (options.chunkedMode !== null || typeof options.chunkedMode != "undefined") {
            chunkedMode = options.chunkedMode;
        }
        if (options.params) {
            params = options.params;
        }
        else {
            params = {};
        }
    }

    if (cordova.platformId === "windowsphone") {
        headers = headers && convertHeadersToArray(headers);
        params = params && convertHeadersToArray(params);
    }

    var fail = errorCallback && function(e) {
        var error = new FileTransferError(e.code, e.source, e.target, e.http_status, e.body, e.exception);
        errorCallback(error);
    };

    var self = this;
    var win = function(result) {
        if (typeof result.lengthComputable != "undefined") {
            if (self.onprogress) {
                self.onprogress(newProgressEvent(result));
            }
        } else {
            successCallback && successCallback(result);
        }
    };
    exec(win, fail, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id, httpMethod]);
};

/**
 * Downloads a file form a given URL and saves it to the specified directory.
 * @param source {String}          URL of the server to receive the file
 * @param target {String}         Full path of the file on the device
 * @param successCallback (Function}  Callback to be invoked when upload has completed
 * @param errorCallback {Function}    Callback to be invoked upon error
 * @param trustAllHosts {Boolean} Optional trust all hosts (e.g. for self-signed certs), defaults to false
 * @param options {FileDownloadOptions} Optional parameters such as headers
 */
FileTransfer.prototype.download = function(source, target, successCallback, errorCallback, trustAllHosts, options) {
    argscheck.checkArgs('ssFF*', 'FileTransfer.download', arguments);
    var self = this;

    var basicAuthHeader = getBasicAuthHeader(source);
    if (basicAuthHeader) {
        source = source.replace(getUrlCredentials(source) + '@', '');

        options = options || {};
        options.headers = options.headers || {};
        options.headers[basicAuthHeader.name] = basicAuthHeader.value;
    }

    var headers = null;
    if (options) {
        headers = options.headers || null;
    }

    if (cordova.platformId === "windowsphone" && headers) {
        headers = convertHeadersToArray(headers);
    }

    var win = function(result) {
        if (typeof result.lengthComputable != "undefined") {
            if (self.onprogress) {
                return self.onprogress(newProgressEvent(result));
            }
        } else if (successCallback) {
            var entry = null;
            if (result.isDirectory) {
                entry = new (require('cordova-plugin-file.DirectoryEntry'))();
            }
            else if (result.isFile) {
                entry = new (require('cordova-plugin-file.FileEntry'))();
            }
            entry.isDirectory = result.isDirectory;
            entry.isFile = result.isFile;
            entry.name = result.name;
            entry.fullPath = result.fullPath;
            entry.filesystem = new FileSystem(result.filesystemName || (result.filesystem == window.PERSISTENT ? 'persistent' : 'temporary'));
            entry.nativeURL = result.nativeURL;
            successCallback(entry);
        }
    };

    var fail = errorCallback && function(e) {
        var error = new FileTransferError(e.code, e.source, e.target, e.http_status, e.body, e.exception);
        errorCallback(error);
    };

    exec(win, fail, 'FileTransfer', 'download', [source, target, trustAllHosts, this._id, headers]);
};

/**
 * Aborts the ongoing file transfer on this object. The original error
 * callback for the file transfer will be called if necessary.
 */
FileTransfer.prototype.abort = function() {
    exec(null, null, 'FileTransfer', 'abort', [this._id]);
};

module.exports = FileTransfer;
<commit_msg>Fixed a bug: Uncaught module cordova-plugin-file.ProgressEvent not found<commit_after>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

var argscheck = require('cordova/argscheck'),
    exec = require('cordova/exec'),
    FileTransferError = require('./FileTransferError'),
    ProgressEvent = require('org.apache.cordova.file.ProgressEvent');

function newProgressEvent(result) {
    var pe = new ProgressEvent();
    pe.lengthComputable = result.lengthComputable;
    pe.loaded = result.loaded;
    pe.total = result.total;
    return pe;
}

function getUrlCredentials(urlString) {
    var credentialsPattern = /^https?\:\/\/(?:(?:(([^:@\/]*)(?::([^@\/]*))?)?@)?([^:\/?#]*)(?::(\d*))?).*$/,
        credentials = credentialsPattern.exec(urlString);

    return credentials && credentials[1];
}

function getBasicAuthHeader(urlString) {
    var header =  null;

    // This is changed due to MS Windows doesn't support credentials in http uris
    // so we detect them by regexp and strip off from result url
    // Proof: http://social.msdn.microsoft.com/Forums/windowsapps/en-US/a327cf3c-f033-4a54-8b7f-03c56ba3203f/windows-foundation-uri-security-problem

    if (window.btoa) {
        var credentials = getUrlCredentials(urlString);
        if (credentials) {
            var authHeader = "Authorization";
            var authHeaderValue = "Basic " + window.btoa(credentials);

            header = {
                name : authHeader,
                value : authHeaderValue
            };
        }
    }

    return header;
}

function convertHeadersToArray(headers) {
    var result = [];
    for (var header in headers) {
        if (headers.hasOwnProperty(header)) {
            var headerValue = headers[header];
            result.push({
                name: header,
                value: headerValue.toString()
            });
        }
    }
    return result;
}

var idCounter = 0;

/**
 * FileTransfer uploads a file to a remote server.
 * @constructor
 */
var FileTransfer = function() {
    this._id = ++idCounter;
    this.onprogress = null; // optional callback
};

/**
* Given an absolute file path, uploads a file on the device to a remote server
* using a multipart HTTP request.
* @param filePath {String}           Full path of the file on the device
* @param server {String}             URL of the server to receive the file
* @param successCallback (Function}  Callback to be invoked when upload has completed
* @param errorCallback {Function}    Callback to be invoked upon error
* @param options {FileUploadOptions} Optional parameters such as file name and mimetype
* @param trustAllHosts {Boolean} Optional trust all hosts (e.g. for self-signed certs), defaults to false
*/
FileTransfer.prototype.upload = function(filePath, server, successCallback, errorCallback, options, trustAllHosts) {
    argscheck.checkArgs('ssFFO*', 'FileTransfer.upload', arguments);
    // check for options
    var fileKey = null;
    var fileName = null;
    var mimeType = null;
    var params = null;
    var chunkedMode = true;
    var headers = null;
    var httpMethod = null;
    var basicAuthHeader = getBasicAuthHeader(server);
    if (basicAuthHeader) {
        server = server.replace(getUrlCredentials(server) + '@', '');

        options = options || {};
        options.headers = options.headers || {};
        options.headers[basicAuthHeader.name] = basicAuthHeader.value;
    }

    if (options) {
        fileKey = options.fileKey;
        fileName = options.fileName;
        mimeType = options.mimeType;
        headers = options.headers;
        httpMethod = options.httpMethod || "POST";
        if (httpMethod.toUpperCase() == "PUT"){
            httpMethod = "PUT";
        } else {
            httpMethod = "POST";
        }
        if (options.chunkedMode !== null || typeof options.chunkedMode != "undefined") {
            chunkedMode = options.chunkedMode;
        }
        if (options.params) {
            params = options.params;
        }
        else {
            params = {};
        }
    }

    if (cordova.platformId === "windowsphone") {
        headers = headers && convertHeadersToArray(headers);
        params = params && convertHeadersToArray(params);
    }

    var fail = errorCallback && function(e) {
        var error = new FileTransferError(e.code, e.source, e.target, e.http_status, e.body, e.exception);
        errorCallback(error);
    };

    var self = this;
    var win = function(result) {
        if (typeof result.lengthComputable != "undefined") {
            if (self.onprogress) {
                self.onprogress(newProgressEvent(result));
            }
        } else {
            successCallback && successCallback(result);
        }
    };
    exec(win, fail, 'FileTransfer', 'upload', [filePath, server, fileKey, fileName, mimeType, params, trustAllHosts, chunkedMode, headers, this._id, httpMethod]);
};

/**
 * Downloads a file form a given URL and saves it to the specified directory.
 * @param source {String}          URL of the server to receive the file
 * @param target {String}         Full path of the file on the device
 * @param successCallback (Function}  Callback to be invoked when upload has completed
 * @param errorCallback {Function}    Callback to be invoked upon error
 * @param trustAllHosts {Boolean} Optional trust all hosts (e.g. for self-signed certs), defaults to false
 * @param options {FileDownloadOptions} Optional parameters such as headers
 */
FileTransfer.prototype.download = function(source, target, successCallback, errorCallback, trustAllHosts, options) {
    argscheck.checkArgs('ssFF*', 'FileTransfer.download', arguments);
    var self = this;

    var basicAuthHeader = getBasicAuthHeader(source);
    if (basicAuthHeader) {
        source = source.replace(getUrlCredentials(source) + '@', '');

        options = options || {};
        options.headers = options.headers || {};
        options.headers[basicAuthHeader.name] = basicAuthHeader.value;
    }

    var headers = null;
    if (options) {
        headers = options.headers || null;
    }

    if (cordova.platformId === "windowsphone" && headers) {
        headers = convertHeadersToArray(headers);
    }

    var win = function(result) {
        if (typeof result.lengthComputable != "undefined") {
            if (self.onprogress) {
                return self.onprogress(newProgressEvent(result));
            }
        } else if (successCallback) {
            var entry = null;
            if (result.isDirectory) {
                entry = new (require('cordova-plugin-file.DirectoryEntry'))();
            }
            else if (result.isFile) {
                entry = new (require('cordova-plugin-file.FileEntry'))();
            }
            entry.isDirectory = result.isDirectory;
            entry.isFile = result.isFile;
            entry.name = result.name;
            entry.fullPath = result.fullPath;
            entry.filesystem = new FileSystem(result.filesystemName || (result.filesystem == window.PERSISTENT ? 'persistent' : 'temporary'));
            entry.nativeURL = result.nativeURL;
            successCallback(entry);
        }
    };

    var fail = errorCallback && function(e) {
        var error = new FileTransferError(e.code, e.source, e.target, e.http_status, e.body, e.exception);
        errorCallback(error);
    };

    exec(win, fail, 'FileTransfer', 'download', [source, target, trustAllHosts, this._id, headers]);
};

/**
 * Aborts the ongoing file transfer on this object. The original error
 * callback for the file transfer will be called if necessary.
 */
FileTransfer.prototype.abort = function() {
    exec(null, null, 'FileTransfer', 'abort', [this._id]);
};

module.exports = FileTransfer;
<|endoftext|>


<commit_before>/*
Reading progress bar
Based on Reading Position Indicator @ CCS Tricks https://css-tricks.com/reading-position-indicator/
*/

$(document).ready(function() {
  /* configuration */
  var elementToReadSelector      = '.chapter';
  var progressBarSelector        = '#reading-progress progress';
  var progressActiveSelector     = '#reading-progress progress.uk-active';
  var fallbackBarSelector        = '.progress-bar';
  var getWidthFromSelector       = '.chapter';
  var getOffsetLeftFromSelector  = '.chapter';
  var getOffsetTopFromSelector   = 'nav.uk-navbar';
  var sticky;

  var initSticky = function(){
    var progressElement = $(progressBarSelector)[0];
    sticky = UIkit.sticky(progressElement, {
      top: getOffsetTop(),
      getWidthFrom: getWidthFromSelector
    });
  }

  var getMax = function(){
    return $(elementToReadSelector).height() - $(window).height();
  }

  var getValue = function(){
    return $(window).scrollTop();
  }

  var setReadingProgressOffsetLeft = function(){
    var offsetLeft = $(getOffsetLeftFromSelector).offset().left;
    $(progressActiveSelector).css('left', offsetLeft+'px');
  }

  var getOffsetTop = function (){
    return $(getOffsetTopFromSelector).outerHeight() -1; // move up 1 px to counter 1px gap on Safari
  }

  var setReadingProgressOffsetTop = function(){
    var offsetTop = getOffsetTop();
    if (sticky.options.top !== offsetTop) {
      sticky.options.top = offsetTop;
      $(progressActiveSelector).css('top', offsetTop+'px');
    }
  }

  initSticky();
  setReadingProgressOffsetTop();

  $(document).on('active.uk.sticky', function () {
    setReadingProgressOffsetLeft();
  });

  if ('max' in document.createElement('progress')) {
    // Browser supports progress element
    var progressBar = $(progressBarSelector);

    // Set the Max attr for the first time
    progressBar.attr({ max: getMax() });

    $(document).on('scroll', function(){
      // set value
      // edit: also set max to ensure accurate scroll ratio
      progressBar.attr({ max: getMax(), value: getValue() });
    });

    $(window).resize(function(){
      // On resize, both Max/Value attr needs to be calculated
      progressBar.attr({ max: getMax(), value: getValue() });
      setReadingProgressOffsetLeft();
      setReadingProgressOffsetTop();
    });

  } else {

    var progressBar = $(fallbackBarSelector),
        max = getMax(),
        value, width;

    var getWidth = function() {
      // Calculate width in percentage
      value = getValue();
      width = (value/max) * 100;
      width = width + '%';
      return width;
    }

    var setWidth = function(){
      progressBar.css({ width: getWidth() });
    }

    $(document).on('scroll', setWidth);
    $(window).on('resize', function(){
      // Need to reset the Max attr
      max = getMax();
      setWidth();
    });
  }
});<commit_msg>correct semicolons after statements<commit_after>/*
Reading progress bar
Based on Reading Position Indicator @ CCS Tricks https://css-tricks.com/reading-position-indicator/
*/

$(document).ready(function() {
  /* configuration */
  var elementToReadSelector      = '.chapter';
  var progressBarSelector        = '#reading-progress progress';
  var progressActiveSelector     = '#reading-progress progress.uk-active';
  var fallbackBarSelector        = '.progress-bar';
  var getWidthFromSelector       = '.chapter';
  var getOffsetLeftFromSelector  = '.chapter';
  var getOffsetTopFromSelector   = 'nav.uk-navbar';
  var sticky;

  var initSticky = function(){
    var progressElement = $(progressBarSelector)[0];
    sticky = UIkit.sticky(progressElement, {
      top: getOffsetTop(),
      getWidthFrom: getWidthFromSelector
    });
  };

  var getMax = function(){
    return $(elementToReadSelector).height() - $(window).height();
  };

  var getValue = function(){
    return $(window).scrollTop();
  };

  var setReadingProgressOffsetLeft = function(){
    var offsetLeft = $(getOffsetLeftFromSelector).offset().left;
    $(progressActiveSelector).css('left', offsetLeft+'px');
  };

  var getOffsetTop = function (){
    return $(getOffsetTopFromSelector).outerHeight() -1; // move up 1 px to counter 1px gap on Safari
  };

  var setReadingProgressOffsetTop = function(){
    var offsetTop = getOffsetTop();
    if (sticky.options.top !== offsetTop) {
      sticky.options.top = offsetTop;
      $(progressActiveSelector).css('top', offsetTop+'px');
    }
  };

  initSticky();
  setReadingProgressOffsetTop();

  $(document).on('active.uk.sticky', function () {
    setReadingProgressOffsetLeft();
  });

  if ('max' in document.createElement('progress')) {
    // Browser supports progress element
    var progressBar = $(progressBarSelector);

    // Set the Max attr for the first time
    progressBar.attr({ max: getMax() });

    $(document).on('scroll', function(){
      // set value
      // edit: also set max to ensure accurate scroll ratio
      progressBar.attr({ max: getMax(), value: getValue() });
    });

    $(window).resize(function(){
      // On resize, both Max/Value attr needs to be calculated
      progressBar.attr({ max: getMax(), value: getValue() });
      setReadingProgressOffsetLeft();
      setReadingProgressOffsetTop();
    });

  } else {

    var progressBar = $(fallbackBarSelector),
        max = getMax(),
        value, width;

    var getWidth = function() {
      // Calculate width in percentage
      value = getValue();
      width = (value/max) * 100;
      width = width + '%';
      return width;
    }

    var setWidth = function(){
      progressBar.css({ width: getWidth() });
    };

    $(document).on('scroll', setWidth);
    $(window).on('resize', function(){
      // Need to reset the Max attr
      max = getMax();
      setWidth();
    });
  }
});<|endoftext|>