<commit_before>/*
    --------------- jSQL ---------------
    a SQL like database using javascript
    website: http://jsql.us
    licence: MIT Licence
    version: 0.2.0 dev

    description: using jSQL to process the data easily.
*/

(function() {
    var push             = Array.prototype.push,
        slice            = Array.prototype.slice,
        unshift          = Array.prototype.unshift,
        toString         = Object.prototype.toString,
        hasOwnProperty   = Object.prototype.hasOwnProperty;

    var nativeForEach      = Array.prototype.forEach,
        nativeMap          = Array.prototype.map,
        nativeReduce       = Array.prototype.reduce,
        nativeReduceRight  = Array.prototype.reduceRight,
        nativeFilter       = Array.prototype.filter,
        nativeEvery        = Array.prototype.every,
        nativeSome         = Array.prototype.some,
        nativeIndexOf      = Array.prototype.indexOf,
        nativeLastIndexOf  = Array.prototype.lastIndexOf,
        nativeIsArray      = Array.isArray,
        nativeKeys         = Object.keys,
        nativeBind         = Function.prototype.bind;

    var _jSQL, jSQL, _DB = {};

    if(typeof(this.jSQL) !== 'undefined') {
        _jSQL = this.jSQL;
    }

    jSQL = function() {
        this.init.apply(this,arguments);
    };

    jSQL.prototype = {
        init: function() {
            this._jSQL = _jSQL;
            this._DB = _DB;
            this._currentDB = null;
            this._buffer = null;
        },

        /**
        * create a new database
        * @param dbname [String]
        * @param db [Object]
        */

        create: function(dbname, db) {
            var indexList;

            if(this._DB.hasOwnProperty(dbname)) {
                throw('DB Already Exist.');
            }

            if(this._isArray(db)) {
                indexList = this._listSlice(arguments, '2:');
                this._appendKey(db, indexList);
            }

            if(this._isObject(db)) {
                db = this._objectToArray(db);
            }

            this._DB[dbname] = db;
            return this;
        },

        /**
        * select an exist database as current
        * @param dbname [String]
        */

        use: function(dbname) {
            if(!this._DB.hasOwnProperty(dbname)) {
                throw('Database Not Exist.');
            }

            this._currentDB = this._DB[dbname];
            return this;
        },

        /**
        * drop an exist database
        * @param dbname [String]
        */

        drop: function(dbname) {
            if(this._DB.hasOwnProperty(dbname)) {
                delete this._DB[dbname];
            }
        },

        /**
        * select object from currentDB
        * @param key
            '*':     return all
            'a':     return base value which key is 'a'
            'a.b.c': return deep value a->b->c
        *
        */

        select: function(key) {
            if(!this._currentDB) {
                throw('Please Select Database First.');
            }

            this._buffer = this._currentDB; //reset the _buffer

            if(key==='*') {
                return this;
            }

            this.where(function(data) {
                return typeof(this._deep(data, key)) !== 'undefined';
            });

            return this;
        },

        /**
        * get the count of current result set
        */

        count: function() {
            return this._buffer.length;
        },

        /**
        * calculate the total of spec key
        * @param key
            '*':     return first package key count
            'a':     return base value which key is 'a'
            'a.b.c': return deep value a->b->c
        *
        * @use [jSQL instance].total('a.b.c')
        */

        total: function(scope) {
            var rs = 0, _tmp;

            for(var _key in this._currentDB) {
                if(this._currentDB.hasOwnProperty(_key)) {
                    _tmp = scope === '*' ?
                        this._currentDB[_key] :
                        typeof(scope) === 'function' ?
                            scope.call(this, this._currentDB[_key], _key) === true ? true : undefined :
                            this._deep(this._currentDB[_key], scope);

                    if(typeof(_tmp) !== 'undefined') {
                        rs++;
                    }
                }
            }

            return rs;
        },

        /**
        * sort the current result set
        * @param field [String]
        * @param callback [function]
        * @param order [String <asc | desc>]
        */

        orderby: function(field, callback, order) {
            var _array = this._buffer;
            var _this = this;

            if(typeof(callback) !== 'function') {
                callback = [order, order = callback][0];
            }

            _array.sort(function(a, b) {
                a = _this._deep(a, field);
                b = _this._deep(b, field);
                if(callback) {
                    a = callback(a);
                    b = callback(b);
                }
                return  order && order.toLowerCase() === 'asc' ? a - b : b - a;
            });

            this._buffer = _array;
            return this;
        },

        where: function(fn) {
            var _tmp = [], _swap;
            this._buffer = this._buffer || this._currentDB;

            for(var i in this._buffer) {
                if(this._buffer.hasOwnProperty(i)) {
                    if(typeof(fn) === 'function') {
                        _swap = fn.call(this, this._buffer[i], i);
                    }

                    if(this._isArray(fn)) {
                        _swap = false;

                        for(var f in fn) {
                            if(fn.hasOwnProperty(f)) {
                                if(fn[f].call(this, this._buffer[i], i)) {
                                    _swap = true;
                                }
                            }
                        }
                    }

                    if(_swap) {
                        _tmp[i] = this._buffer[i];
                    }
                }
            }
            this._buffer = _tmp;
            return this;
        },

        iterate: function(fn) {
            var _swap;
            this._buffer = this._buffer || this._currentDB;

            for(var i in this._buffer) {
                if(this._buffer.hasOwnProperty(i)) {
                    _swap = fn.call(this, this._buffer[i]);

                    if(_swap) {
                        this.update(i, _swap);
                    }
                }
            }
            return this;
        },

        /**
        * return the current result set
        * @return [Object]
        */

        findAll: function() {
            return this._clone(this._arrayToObject(this._buffer));
        },

        /**
        * return a specified item of current result set
        * if the key doesn't given, it'll return the first item
        * @return [Object]
        */

        find: function(key) {
            if(!key) {
                for(var i in this._buffer) {
                    if(key) {
                        break;
                    }

                    if(this._buffer.hasOwnProperty(i)) {
                        key = i;
                    }
                }
            }

            return this._clone(this._buffer[key]);
        },

        /**
        * return the current result set as array list
        * @return [Object]
        */

        listAll: function() {
            return this._clone(this._buffer);
        },

        /**
        * update the current result set
        * @param key [String]
        * @param data [Object]
        */

        update: function(key, data) {
            if(!this._currentDB) {
                throw('Please Select Database First.');
            }

            if(this._currentDB.hasOwnProperty(key)) {
                this._currentDB[key] = data;
            }
        },

        /**
        * limit the current result set
        * @param start [Number]
        * @param end [Number]
        */

        limit: function(start, end) {
            var _tmp = this._buffer;
            var limit;

            if(!end) {
                start = [0, end = start][0];
            }

            limit = start + ':' + (start + end);

            this._buffer = this._listSlice(_tmp, limit);
            return this;
        },

        keys: function() {
            return this._keys(this.findAll());
        },

        /**
        * private methods
        */

        _deep: function(data, scope) {
            var _tmp = data, scope = scope.split('.');
            for(var i = 0; i < scope.length; i++) {
                _tmp = _tmp[scope[i]];
            }
            return _tmp;
        },

        _isArray: nativeIsArray || function(obj) {
            return toString.call(obj) === '[object Array]';
        },

        _isObject: function(obj) {
            return obj === Object(obj);
        },

        _clone: function(obj) {
            var _tmp = {};

            if (!this._isObject(obj)) return obj;
            if(this._isArray(obj)) return obj.slice();

            for(var i in obj) {
                if(obj.hasOwnProperty(i)) {
                    _tmp[i] = obj[i];
                }
            }
            return _tmp;
        },

        _objectToArray: function(object) {
            var array = [], object = this._clone(object);

            for(var i in object) {
                if(object.hasOwnProperty(i)) {
                    object[i].jSQL_Key = i;
                    array.push(object[i]);
                }
            }

            return array;
        },

        _arrayToObject: function(array, key) {
            var object = {};

            for(var i = 0; i < array.length; i++) {
                object[array[i][key || 'jSQL_Key']] = array[i];
                delete object[array[i][key || 'jSQL_Key']][key || 'jSQL_Key'];
            };

            return object;
        },

        _each: function(list, fn) {
            if(nativeForEach) {
                list.forEach(fn);
                return;
            }

            for(var i = 0; i < list.length; i++) {
                fn(list[i], i, list);
            }
        },

        _keygen: function(object, indexList) {
            var that = this;
            var baseRef = [].slice.call(arguments, 1);
            var key = '';

            if(that._isArray(indexList)) {
                baseRef = indexList;
            }

            that._each(baseRef, function(o, i, r) {
                key += object[o];
            });

            return key;
        },

        _listSlice: function(list, range) {
            var start, end;

            list = [].slice.call(list);
            range = range.split(':');
            start = range[0] || 0;
            end = range.length > 1 ? range[1] || list.length : list.length;
            return [].slice.call(list, start, end);
        },

        _appendKey: function(list, indexList) {
            var that = this;
            that._each(list, function(o, i, r) {
                o['jSQL_Key'] = that._keygen(o, indexList);
            });
        },

        _keys: nativeKeys || (function() {
            var hasDontEnumBug = true,
                dontEnums = [
                    'toString',
                    'toLocaleString',
                    'valueOf',
                    'hasOwnProperty',
                    'isPrototypeOf',
                    'propertyIsEnumerable',
                    'constructor'
                ],
                dontEnumsLength = dontEnums.length;

            for (var key in {'toString': null}) {
                hasDontEnumBug = false;
            }

            return function keys(object) {
                if ((typeof object != 'object' && typeof object != 'function') || object === null) {
                    throw new TypeError('Object.keys called on a non-object');
                }

                var keys = [];
                for (var name in object) {
                    if (object.hasOwnProperty(name)) {
                        keys.push(name);
                    }
                }

                if (hasDontEnumBug) {
                    for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
                        var dontEnum = dontEnums[i];
                        if (object.hasOwnProperty(dontEnum)) {
                            keys.push(dontEnum);
                        }
                    }
                }
                return keys;
            };
        })()
    };

    jSQL = new jSQL();

    typeof(module) !== 'undefined' && module.exports ? module.exports = jSQL : this.jSQL = jSQL;
})();
<commit_msg>update jSQL.<commit_after>/*
    --------------- jSQL ---------------
    a SQL like database using javascript
    website: http://jsql.us
    licence: MIT Licence
    version: 0.2.0 dev

    description: using jSQL to process the data easily.
*/

(function() {
    var push             = Array.prototype.push,
        slice            = Array.prototype.slice,
        unshift          = Array.prototype.unshift,
        toString         = Object.prototype.toString,
        hasOwnProperty   = Object.prototype.hasOwnProperty;

    var nativeForEach      = Array.prototype.forEach,
        nativeMap          = Array.prototype.map,
        nativeReduce       = Array.prototype.reduce,
        nativeReduceRight  = Array.prototype.reduceRight,
        nativeFilter       = Array.prototype.filter,
        nativeEvery        = Array.prototype.every,
        nativeSome         = Array.prototype.some,
        nativeIndexOf      = Array.prototype.indexOf,
        nativeLastIndexOf  = Array.prototype.lastIndexOf,
        nativeIsArray      = Array.isArray,
        nativeKeys         = Object.keys,
        nativeBind         = Function.prototype.bind;

    var _jSQL, jSQL, _DB = {};

    if(typeof(this.jSQL) !== 'undefined') {
        _jSQL = this.jSQL;
    }

    jSQL = function() {
        this.init.apply(this,arguments);
    };

    jSQL.prototype = {
        init: function() {
            this._jSQL = _jSQL;
            this._DB = _DB;
            this._currentDB = null;
            this._buffer = null;
        },

        /**
        * create a new database
        * @param dbname [String]
        * @param db [Object]
        */

        create: function(dbname, db) {
            var indexList;

            if(this._DB.hasOwnProperty(dbname)) {
                throw('DB Already Exist.');
            }

            if(this._isArray(db)) {
                indexList = this._listSlice(arguments, '2:');
                this._appendKey(db, indexList);
            }

            if(this._isObject(db)) {
                db = this._objectToArray(db);
            }

            this._DB[dbname] = db;
            return this;
        },

        /**
        * select an exist database as current
        * @param dbname [String]
        */

        use: function(dbname) {
            if(!this._DB.hasOwnProperty(dbname)) {
                throw('Database Not Exist.');
            }

            this._currentDB = this._DB[dbname];
            return this;
        },

        /**
        * drop an exist database
        * @param dbname [String]
        */

        drop: function(dbname) {
            if(this._DB.hasOwnProperty(dbname)) {
                delete this._DB[dbname];
            }
        },

        dbs: function() {
            return this._keys(this._DB);
        },

        /**
        * select object from currentDB
        * @param key
            '*':     return all
            'a':     return base value which key is 'a'
            'a.b.c': return deep value a->b->c
        *
        */

        select: function(key) {
            if(!this._currentDB) {
                throw('Please Select Database First.');
            }

            this._buffer = this._currentDB; //reset the _buffer

            if(key==='*') {
                return this;
            }

            this.where(function(data) {
                return typeof(this._deep(data, key)) !== 'undefined';
            });

            return this;
        },

        /**
        * get the count of current result set
        */

        count: function() {
            return this._buffer.length;
        },

        /**
        * calculate the total of spec key
        * @param key
            '*':     return first package key count
            'a':     return base value which key is 'a'
            'a.b.c': return deep value a->b->c
        *
        * @use [jSQL instance].total('a.b.c')
        */

        total: function(scope) {
            var rs = 0, _tmp;

            for(var _key in this._currentDB) {
                if(this._currentDB.hasOwnProperty(_key)) {
                    _tmp = scope === '*' ?
                        this._currentDB[_key] :
                        typeof(scope) === 'function' ?
                            scope.call(this, this._currentDB[_key], _key) === true ? true : undefined :
                            this._deep(this._currentDB[_key], scope);

                    if(typeof(_tmp) !== 'undefined') {
                        rs++;
                    }
                }
            }

            return rs;
        },

        /**
        * sort the current result set
        * @param field [String]
        * @param callback [function]
        * @param order [String <asc | desc>]
        */

        orderby: function(field, callback, order) {
            var _array = this._buffer;
            var _this = this;

            if(typeof(callback) !== 'function') {
                callback = [order, order = callback][0];
            }

            _array.sort(function(a, b) {
                a = _this._deep(a, field);
                b = _this._deep(b, field);
                if(callback) {
                    a = callback(a);
                    b = callback(b);
                }
                return  order && order.toLowerCase() === 'asc' ? a - b : b - a;
            });

            this._buffer = _array;
            return this;
        },

        where: function(fn) {
            var _tmp = [], _swap;
            this._buffer = this._buffer || this._currentDB;

            for(var i in this._buffer) {
                if(this._buffer.hasOwnProperty(i)) {
                    if(typeof(fn) === 'function') {
                        _swap = fn.call(this, this._buffer[i], i);
                    }

                    if(this._isArray(fn)) {
                        _swap = false;

                        for(var f in fn) {
                            if(fn.hasOwnProperty(f)) {
                                if(fn[f].call(this, this._buffer[i], i)) {
                                    _swap = true;
                                }
                            }
                        }
                    }

                    if(_swap) {
                        _tmp[i] = this._buffer[i];
                    }
                }
            }
            this._buffer = _tmp;
            return this;
        },

        iterate: function(fn) {
            var _swap;
            this._buffer = this._buffer || this._currentDB;

            for(var i in this._buffer) {
                if(this._buffer.hasOwnProperty(i)) {
                    _swap = fn.call(this, this._buffer[i]);

                    if(_swap) {
                        this.update(i, _swap);
                    }
                }
            }
            return this;
        },

        /**
        * return the current result set
        * @return [Object]
        */

        findAll: function() {
            return this._clone(this._arrayToObject(this._buffer));
        },

        /**
        * return a specified item of current result set
        * if the key doesn't given, it'll return the first item
        * @return [Object]
        */

        find: function(key) {
            if(!key) {
                for(var i in this._buffer) {
                    if(key) {
                        break;
                    }

                    if(this._buffer.hasOwnProperty(i)) {
                        key = i;
                    }
                }
            }

            return this._clone(this._buffer[key]);
        },

        /**
        * return the current result set as array list
        * @return [Object]
        */

        listAll: function() {
            return this._clone(this._buffer);
        },

        /**
        * update the current result set
        * @param key [String]
        * @param data [Object]
        */

        update: function(key, data) {
            if(!this._currentDB) {
                throw('Please Select Database First.');
            }

            if(this._currentDB.hasOwnProperty(key)) {
                this._currentDB[key] = data;
            }
        },

        /**
        * limit the current result set
        * @param start [Number]
        * @param end [Number]
        */

        limit: function(start, end) {
            var _tmp = this._buffer;
            var limit;

            if(!end) {
                start = [0, end = start][0];
            }

            limit = start + ':' + (start + end);

            this._buffer = this._listSlice(_tmp, limit);
            return this;
        },

        keys: function() {
            return this._keys(this.findAll());
        },

        /**
        * private methods
        */

        _deep: function(data, scope) {
            var _tmp = data, scope = scope.split('.');
            for(var i = 0; i < scope.length; i++) {
                _tmp = _tmp[scope[i]];
            }
            return _tmp;
        },

        _isArray: nativeIsArray || function(obj) {
            return toString.call(obj) === '[object Array]';
        },

        _isObject: function(obj) {
            return obj === Object(obj);
        },

        _clone: function(obj) {
            var _tmp = {};

            if (!this._isObject(obj)) return obj;
            if(this._isArray(obj)) return obj.slice();

            for(var i in obj) {
                if(obj.hasOwnProperty(i)) {
                    _tmp[i] = obj[i];
                }
            }
            return _tmp;
        },

        _objectToArray: function(object) {
            var array = [], object = this._clone(object);

            for(var i in object) {
                if(object.hasOwnProperty(i)) {
                    object[i].jSQL_Key = i;
                    array.push(object[i]);
                }
            }

            return array;
        },

        _arrayToObject: function(array, key) {
            var object = {};

            for(var i = 0; i < array.length; i++) {
                object[array[i][key || 'jSQL_Key']] = array[i];
                delete object[array[i][key || 'jSQL_Key']][key || 'jSQL_Key'];
            };

            return object;
        },

        _each: function(list, fn) {
            if(nativeForEach) {
                list.forEach(fn);
                return;
            }

            for(var i = 0; i < list.length; i++) {
                fn(list[i], i, list);
            }
        },

        _keygen: function(object, indexList) {
            var that = this;
            var baseRef = [].slice.call(arguments, 1);
            var key = '';

            if(that._isArray(indexList)) {
                baseRef = indexList;
            }

            that._each(baseRef, function(o, i, r) {
                key += object[o];
            });

            return key;
        },

        _listSlice: function(list, range) {
            var start, end;

            list = [].slice.call(list);
            range = range.split(':');
            start = range[0] || 0;
            end = range.length > 1 ? range[1] || list.length : list.length;
            return [].slice.call(list, start, end);
        },

        _appendKey: function(list, indexList) {
            var that = this;
            that._each(list, function(o, i, r) {
                o['jSQL_Key'] = that._keygen(o, indexList);
            });
        },

        _keys: nativeKeys || (function() {
            var hasDontEnumBug = true,
                dontEnums = [
                    'toString',
                    'toLocaleString',
                    'valueOf',
                    'hasOwnProperty',
                    'isPrototypeOf',
                    'propertyIsEnumerable',
                    'constructor'
                ],
                dontEnumsLength = dontEnums.length;

            for (var key in {'toString': null}) {
                hasDontEnumBug = false;
            }

            return function keys(object) {
                if ((typeof object != 'object' && typeof object != 'function') || object === null) {
                    throw new TypeError('Object.keys called on a non-object');
                }

                var keys = [];
                for (var name in object) {
                    if (object.hasOwnProperty(name)) {
                        keys.push(name);
                    }
                }

                if (hasDontEnumBug) {
                    for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
                        var dontEnum = dontEnums[i];
                        if (object.hasOwnProperty(dontEnum)) {
                            keys.push(dontEnum);
                        }
                    }
                }
                return keys;
            };
        })()
    };

    jSQL = new jSQL();

    typeof(module) !== 'undefined' && module.exports ? module.exports = jSQL : this.jSQL = jSQL;
})();
<|endoftext|>


<commit_before>var fs = require('fs');

exports.commands = {

/***********************
	Set Gym Leader
***********************/

	sgl: 'setgymleader',
	setgymleader: function (target, room, user) {
		if (!this.can('makeroom')) return;
		if (!target) return this.sendReply('/setgymleader [league], [type], [user] - Adds user to GL list');
		var targetsArray = target.split(',');
		var target0 = targetsArray[0];
		var target1 = targetsArray[1];
		var target2 = targetsArray[2];
		target1 = target1.toString().substring(1, target1.Length);
		if(target1 != 'Fairy' && target1 != 'Bug' && target1 != 'Dragon' && target1 != 'Psychic' && target1 != 'Water' && target1 != 'Fire' && target1 != 'Grass' && target1 != 'Ground' && target1 != 'Rock' && target1 != 'Dark' && target1 != 'Ice' && target1 != 'Electric' && target1 != 'Flying' && target1 != 'Normal' && target1 != 'Poison' && target1 != 'Ghost' && target1 != 'Steel' && target1 != 'Fighting') return this.sendReply ('Please select a valid type using capitalisation');
		if (fs.existsSync('storage-files/'+target0+'gymleaders.json')) {
            		var gymleaderlist = JSON.parse(fs.readFileSync('storage-files/'+target0+'gymleaders.json'));
			gymleaderlist[target1] = target2;
  			fs.writeFile('storage-files/'+target0+'gymleaders.json', JSON.stringify(gymleaderlist));
        	}else{
            		fs.writeFileSync('storage-files/'+target0+'gymleaders.json', '{}');
            		var gymleaderlist = JSON.parse(fs.readFileSync('storage-files/'+target0+'gymleaders.json'));
		    	gymleaderlist[target1] = target2;
  		    	fs.writeFile('storage-files/'+target0+'gymleaders.json', JSON.stringify(gymleaderlist));
        	}

		this.sendReply(target2 + ' has now been set as ' + target1 + ' Gym Leader for ' + target0 + '.');

		return;
	},

	vgl: 'viewgymleaders',
	viewgymleaders: function (target, room, user) {
		if (!this.canBroadcast()) return;
		if(!target) return this.sendReply ('/viewgymleaders [league] - Displays the list of Gym Leaders for selected league.');
		if (fs.existsSync('storage-files/'+target+'gymleaders.json')) {
  			var gymleaderlist = JSON.parse(fs.readFileSync('storage-files/'+target+'gymleaders.json'));
		}else{
			return this.sendReply ('League doesn\'t exist or hasn\'t set up a Gym Leader list.');
		}

		var glList = '

Type	Gym Leader	Last Seen

';
		for (type in gymleaderlist) {
			var lastSeen = dates.lastSeen(toId(gymleadrlist[type])).split(",")[0] + ' ago';
			if (Users.get(gymleaderlist[type]) && Users.get(toId(gymleaderlist[type])).connected)
				lastSeen = ' online.';
			glList += '
' + '' + '	' + '' + gymleaderlist[type] + ': ' + '	' + '' + lastSeen + '	' + '
';
		}
		this.sendReplyBox(glList + '
');
	}
};
<commit_msg>Update leaguecommands.js<commit_after>var fs = require('fs');

exports.commands = {

/***********************
	Set Gym Leader
***********************/

	sgl: 'setgymleader',
	setgymleader: function (target, room, user) {
		if (!this.can('makeroom')) return;
		if (!target) return this.sendReply('/setgymleader [league], [type], [user] - Adds user to GL list');
		var targetsArray = target.split(',');
		var target0 = targetsArray[0];
		var target1 = targetsArray[1];
		var target2 = targetsArray[2];
		target1 = toId(target1);
		target1 = target1.charAt(0).toUpperCase() + target1.slice(1).toLowerCase();
		if(target1 != 'Fairy' && target1 != 'Bug' && target1 != 'Dragon' && target1 != 'Psychic' && target1 != 'Water' && target1 != 'Fire' && target1 != 'Grass' && target1 != 'Ground' && target1 != 'Rock' && target1 != 'Dark' && target1 != 'Ice' && target1 != 'Electric' && target1 != 'Flying' && target1 != 'Normal' && target1 != 'Poison' && target1 != 'Ghost' && target1 != 'Steel' && target1 != 'Fighting') return this.sendReply ('Please select a valid type using capitalisation');
		if (fs.existsSync('storage-files/'+target0+'gymleaders.json')) {
            		var gymleaderlist = JSON.parse(fs.readFileSync('storage-files/'+target0+'gymleaders.json'));
			gymleaderlist[target1] = target2;
  			fs.writeFile('storage-files/'+target0+'gymleaders.json', JSON.stringify(gymleaderlist));
        	}else{
            		fs.writeFileSync('storage-files/'+target0+'gymleaders.json', '{}');
            		var gymleaderlist = JSON.parse(fs.readFileSync('storage-files/'+target0+'gymleaders.json'));
		    	gymleaderlist[target1] = target2;
  		    	fs.writeFile('storage-files/'+target0+'gymleaders.json', JSON.stringify(gymleaderlist));
        	}

		this.sendReply(target2 + ' has now been set as ' + target1 + ' Gym Leader for ' + target0 + '.');

		return;
	},

	vgl: 'viewgymleaders',
	viewgymleaders: function (target, room, user) {
		if (!this.canBroadcast()) return;
		if(!target) return this.sendReply ('/viewgymleaders [league] - Displays the list of Gym Leaders for selected league.');
		if (fs.existsSync('storage-files/'+target+'gymleaders.json')) {
  			var gymleaderlist = JSON.parse(fs.readFileSync('storage-files/'+target+'gymleaders.json'));
		}else{
			return this.sendReply ('League doesn\'t exist or hasn\'t set up a Gym Leader list.');
		}

		var glList = '

Type	Gym Leader	Last Seen

';
		for (type in gymleaderlist) {
			var lastSeen = dates.lastSeen(toId(gymleadrlist[type])).split(",")[0] + ' ago';
			if (Users.get(gymleaderlist[type]) && Users.get(toId(gymleaderlist[type])).connected)
				lastSeen = ' online.';
			glList += '
' + '' + '	' + '' + gymleaderlist[type] + ': ' + '	' + '' + lastSeen + '	' + '
';
		}
		this.sendReplyBox(glList + '
');
	}
};
<|endoftext|>


<commit_before>module.exports = {

    data: function () {
        return _.extend({
            post: {},
            tree: {},
            comments: [],
            count: 0,
            reply: 0,
            error: false
        }, window.$comments);
    },

    created: function () {
        this.Comments = this.$resource('api/blog/comment/:id');
        this.load();
    },

    methods: {

        load: function () {

            return this.Comments.query({post: this.config.post}, function (data) {
                this.$set('comments', data.comments);
                this.$set('tree', _.groupBy(data.comments, 'parent_id'));
                this.$set('post', data.posts[0]);
                this.$set('count', data.count);
                this.$set('reply', 0);
            });
        }

    },

    components: {

        'comments-item': {

            inherit: true,
            props: ['depth'],
            template: '#comments-item',

            computed: {

                showReply: function () {

                    return this.config.enabled && this.reply && this.reply == this.comment.id;

                },

                showReplyButton: function () {

                    return this.config.enabled && this.depth < this.config.max_depth && !this.showReply;

                },

                remainder: function () {

                    return this.depth >= this.config.max_depth && this.tree[this.comment.id] || [];

                },

                permalink: function () {
                    return $pagekit.url + this.post.url + '#comment-' + this.comment.id;

                }

            },

            methods: {

                replyTo: function (e) {
                    e.preventDefault();
                    this.$set('reply', this.comment.id);
                }

            }

        },

        'comments-reply': {

            inherit: true,
            template: '#comments-reply',

            data: function () {
                return {
                    author: '',
                    email: '',
                    content: ''
                };
            },

            methods: {

                cancel: function (e) {
                    e.preventDefault();
                    this.$set('reply', 0);
                    this.$set('author', '');
                    this.$set('email', '');
                    this.$set('content', '');
                    this.$set('replyForm', {});
                },

                save: function (e) {
                    e.preventDefault();

                    var comment = {
                        parent_id: this.comment ? this.comment.id : 0,
                        post_id: this.config.post,
                        content: this.content
                    };

                    if (!this.user.isAuthenticated) {
                        comment['author'] = this.author;
                        comment['email'] = this.email;
                    }

                    this.$set('error', false);

                    this.$resource('api/blog/comment/:id').save({id: 0}, {comment: comment}, function (data) {
                        this.cancel(e);
                        this.load().success(function () {
                            window.location.hash = 'comment-' + data.comment.id;
                        });
                    }, function () {
                        // TODO better error messages
                        this.$set('error', this.$trans('Unable to comment. Please try again later.'))
                    });
                }

            }

        }

    }

};

jQuery(function () {
    new Vue(module.exports).$mount('#comments');
});
<commit_msg>front-end comments fixed<commit_after>module.exports = {

    data: function () {
        return _.extend({
            post: {},
            tree: {},
            comments: [],
            count: 0,
            reply: 0,
            error: false
        }, window.$comments);
    },

    created: function () {
        this.Comments = this.$resource('api/blog/comment/:id');
        this.load();
    },

    methods: {

        load: function () {

            return this.Comments.query({post: this.config.post}, function (data) {
                this.$set('comments', data.comments);
                this.$set('tree', _.groupBy(data.comments, 'parent_id'));
                this.$set('post', data.posts[0]);
                this.$set('count', data.count);
                this.$set('reply', 0);
            });
        }

    },

    components: {

        'comments-item': {

            inherit: true,
            props: ['depth'],
            template: '#comments-item',

            computed: {

                showReply: function () {

                    return this.config.enabled && this.reply && this.reply == this.comment.id;

                },

                showReplyButton: function () {

                    return this.config.enabled && this.depth < this.config.max_depth && !this.showReply;

                },

                remainder: function () {

                    return this.depth >= this.config.max_depth && this.tree[this.comment.id] || [];

                },

                permalink: function () {
                    return $pagekit.url + this.post.url + '#comment-' + this.comment.id;

                }

            },

            methods: {

                replyTo: function (e) {
                    e.preventDefault();
                    this.$set('reply', this.comment.id);
                }

            }

        },

        'comments-reply': {

            inherit: true,
            template: '#comments-reply',

            data: function () {
                return {
                    author: '',
                    email: '',
                    content: ''
                };
            },

            methods: {

                save: function (e) {

                    e.preventDefault();

                    var comment = {
                        parent_id: this.comment ? this.comment.id : 0,
                        post_id: this.config.post,
                        content: this.content
                    };

                    if (!this.user.isAuthenticated) {
                        comment.author = this.author;
                        comment.email  = this.email;
                    }

                    this.$set('error', false);

                    this.$resource('api/blog/comment/:id').save({id: 0}, {comment: comment}, function (data) {

                        this.$set('reply', 0);
                        this.$set('author', '');
                        this.$set('email', '');
                        this.$set('content', '');
                        this.$set('replyForm', {});

                        if (document.replyForm) {
                            document.replyForm.reset();
                        }

                        this.load().success(function () {
                            window.location.hash = 'comment-' + data.comment.id;
                        });

                    }, function () {

                        // TODO better error messages
                        this.$set('error', this.$trans('Unable to comment. Please try again later.'));
                    });
                }

            }

        }

    }

};

jQuery(function () {
    new Vue(module.exports).$mount('#comments');
});
<|endoftext|>


<commit_before>Ext.define('App.view.Window',{
    extend: 'Ext.window.Window',
    wm: null,//task bar / window manager button
    wmImg: 'css/ok.png',
    wmTooltip: 'wm tooltip',
    constrainHeader: true,// doesn't work properly
    autoShow: true,
    maximizable: true,
    tools:[{
        type:'refresh',
        tooltip:// developer's stuff must have no `l10n`
'view developent: reload view && controller
' +
'NOTE: no models or stores etc. are reloaded by default',
        callback:// anti-MVC pattern, but this is an abstract window to extend and control
        function reload_devel_view(panel, tool, event){
        var to = { renderTo: Ext.getCmp('desk').getEl() }
           ,wmId = panel.wmId
           ,url

            panel.destroy()// models, stores and backend can be reloaded there
            Ext.Loader.loadScript({
                url: url = (App.cfg.backend.url || '') + '/view/' + wmId + '.js'
               ,onLoad: function view_loaded(){
                    Ext.Loader.removeScriptElement(url)
                    Ext.Loader.loadScript({
                        url: url = (App.cfg.backend.url || '') + '/controller/' + wmId + '.js'
                       ,onLoad: function ctl_loaded(){
                            Ext.Loader.removeScriptElement(url)
                            App.create('controller.' + wmId, null, to)
                        }
                       ,onError: function ctl_not_loaded(){
                            Ext.Loader.removeScriptElement(url)
                            App.create('view.' + wmId, null, to)
                        }
                    })
                }
            })
        }
    },
    {
        type:'help',
        tooltip: 'Get Help',
        callback: function(panel, tool, event){
        }
    }],
    initComponent:// anti-MVC pattern
    function dynamic_init_window(){
    var me = this

        me.callParent()

        me.wm = Ext.getCmp('wm').add({
            text: ''
           ,itemId: me.wmId || ''
           ,enableToggle: true
           ,pressed: true
           ,tooltip: me.wmTooltip
           ,toggleHandler: me.onWMToggle
           ,scope: me
        })
        me.on({
            destroy: function onCloseWindow(){
                Ext.getCmp('wm').remove(me.wm, /*autoDestroy:*/ true)
                me.wm = null
            },
            activate: function onActivateWindow(){
                me.wm.toggle(true, true)
            },
            deactivate: function onDeactivateWindow(){
                me.wm.toggle(false, true)
            }
        })
    }
   ,onWMToggle:// anti-MVC pattern
    function onWMToggle(_, next_state){
    var me = this// window
        if(next_state){
            Ext.WindowManager.front.setActive(false)
            me.isHidden() && me.show()
            me.setActive(true)
        } else {
            me.hide()
            me.wm.toggle(false, true)
            Ext.WindowManager.front.setActive(true)
        }
    }
})
<commit_msg>view.Window devtool: check if `wmId` is set to support development mode<commit_after>Ext.define('App.view.Window',{
    extend: 'Ext.window.Window',
    wm: null,//task bar / window manager button
    wmImg: 'css/ok.png',
    wmTooltip: 'wm tooltip',
    constrainHeader: true,// doesn't work properly
    autoShow: true,
    maximizable: true,
    tools:[{
        type:'refresh',
        tooltip:// developer's stuff must have no `l10n`
'view developent: reload view && controller
' +
'NOTE: no models or stores etc. are reloaded by default',
        callback:// anti-MVC pattern, but this is an abstract window to extend and control
        function reload_devel_view(panel, tool, event){
        var to = { renderTo: Ext.getCmp('desk').getEl() }
           ,wmId = panel.wmId
           ,url

            if(!wmId){
                console.warn("window doesn't support devepment mode")
                return
            }

            panel.destroy()// models, stores and backend can be reloaded there
            Ext.Loader.loadScript({
                url: url = (App.cfg.backend.url || '') + '/view/' + wmId + '.js'
               ,onLoad: function view_loaded(){
                    Ext.Loader.removeScriptElement(url)
                    Ext.Loader.loadScript({
                        url: url = (App.cfg.backend.url || '') + '/controller/' + wmId + '.js'
                       ,onLoad: function ctl_loaded(){
                            Ext.Loader.removeScriptElement(url)
                            App.create('controller.' + wmId, null, to)
                        }
                       ,onError: function ctl_not_loaded(){
                            Ext.Loader.removeScriptElement(url)
                            App.create('view.' + wmId, null, to)
                        }
                    })
                }
            })
        }
    },
    {
        type:'help',
        tooltip: 'Get Help',
        callback: function(panel, tool, event){
        }
    }],
    initComponent:// anti-MVC pattern
    function dynamic_init_window(){
    var me = this

        me.callParent()

        me.wm = Ext.getCmp('wm').add({
            text: ''
           ,itemId: me.wmId || ''
           ,enableToggle: true
           ,pressed: true
           ,tooltip: me.wmTooltip
           ,toggleHandler: me.onWMToggle
           ,scope: me
        })
        me.on({
            destroy: function onCloseWindow(){
                Ext.getCmp('wm').remove(me.wm, /*autoDestroy:*/ true)
                me.wm = null
            },
            activate: function onActivateWindow(){
                me.wm.toggle(true, true)
            },
            deactivate: function onDeactivateWindow(){
                me.wm.toggle(false, true)
            }
        })
    }
   ,onWMToggle:// anti-MVC pattern
    function onWMToggle(_, next_state){
    var me = this// window
        if(next_state){
            Ext.WindowManager.front.setActive(false)
            me.isHidden() && me.show()
            me.setActive(true)
        } else {
            me.hide()
            me.wm.toggle(false, true)
            Ext.WindowManager.front.setActive(true)
        }
    }
})
<|endoftext|>


<commit_before>import Vue from 'vue';
import React from 'react';
import ReactDom from 'react-dom';

const registerRoute = (navConfig, isReact) => {
  let route = [];
  let navs = navConfig['zh-CN'];
  navs.forEach(nav => {
    if (nav.groups) {
      nav.groups.forEach(group => {
        group.list.forEach(nav => {
          addRoute(nav);
        });
      });
    } else if (nav.children) {
      nav.children.forEach(nav => {
        addRoute(nav);
      });
    } else {
      addRoute(nav);
    }
  });

  function addRoute(page) {
    const componentName = 'demo-page-' + page.path.slice(1);
    let filePath;
    if (page.filePath) {
      filePath = page.filePath;
    } else {
      let fileName = page.path + (isReact ? '.js' : '.md');
      filePath = './examples' + fileName;
    }

    if (isReact) {
      route.push({
        path: '/component' + page.path,
        component: Vue.component(componentName, {
          render(createElement) {
            return createElement('div', {
              'class': {
                'react-doc-page-content': true
              }
            });
          },
          mounted() {
            page.filePath().then((res) => {
              ReactDom.render(
                React.createElement(res),
                this.$el
              );
            });
          }
        })
      });
    } else {
      route.push({
        path: '/component' + page.path,
        component: function(resolve) {
          require([`${filePath}`], resolve);
        }
      });
    }
  }

  // console.log(route);

  return route;
};

export default registerRoute;
<commit_msg>fix: unmount react node before vue unmounts<commit_after>import Vue from 'vue';
import React from 'react';
import ReactDom from 'react-dom';

const registerRoute = (navConfig, isReact) => {
  let route = [];
  let navs = navConfig['zh-CN'];
  navs.forEach(nav => {
    if (nav.groups) {
      nav.groups.forEach(group => {
        group.list.forEach(nav => {
          addRoute(nav);
        });
      });
    } else if (nav.children) {
      nav.children.forEach(nav => {
        addRoute(nav);
      });
    } else {
      addRoute(nav);
    }
  });

  function addRoute(page) {
    const componentName = 'demo-page-' + page.path.slice(1);
    let filePath;
    if (page.filePath) {
      filePath = page.filePath;
    } else {
      let fileName = page.path + (isReact ? '.js' : '.md');
      filePath = './examples' + fileName;
    }

    if (isReact) {
      route.push({
        path: '/component' + page.path,
        component: Vue.component(componentName, {
          render(createElement) {
            return createElement('div', {
              'class': {
                'react-doc-page-content': true
              }
            });
          },
          mounted() {
            page.filePath().then((res) => {
              ReactDom.render(
                React.createElement(res),
                this.$el
              );
            });
          },
          beforeDestroy() {
            ReactDom.unmountComponentAtNode(this.$el);
          }
        })
      });
    } else {
      route.push({
        path: '/component' + page.path,
        component: function(resolve) {
          require([`${filePath}`], resolve);
        }
      });
    }
  }

  // console.log(route);

  return route;
};

export default registerRoute;
<|endoftext|>


<commit_before>// A history of commands sent to the server,
// oldest first.
var history = [''];
var history_position = 0;

// True if there is an ajax request en route
// to the server. The prompt only allows one
// request at a time.
var working = false;

// Debugging variable, remove at some point maybe
var last_request = null;

// Add an executed command onto the history stack
function updateHistory(cmd) {
  history.pop(); // Get rid of the blank off the end
  history.push(cmd); // Put the new command on the stack
  history.push(''); // Put a new blank on the end
  history_position = history.length - 1;
}

// Track back and forth through the history stack
$('#input').keydown(function(event) {
  // 38 == UP key
  // 40 == DOWN key
  if (event.which != 38 && event.which != 40) {
    return;
  }

  // We save the current command back into the stack
  // in case it's been modified.
  var p = $('#input');
  var current_cmd = p.val();
  history[history_position] = current_cmd;

  event.preventDefault();
  if (event.which == 38) {
    if (history_position == 0) {
      return;
    }
    p.val(history[--history_position]);
  } else {
    if (history_position == history.length - 1) {
      return;
    }
    p.val(history[++history_position]);
  }

  // Move cursor to the end of the prompt
  p[0].selectionStart = p[0].selectionEnd = p.val().length;
});

// Send the user's command to the server when
// the form is submitted.
$('#prompt').submit(function(event) {
  event.preventDefault();
  if (working)
    return;

  var input = $('#input');
  var cmd = $.trim(input.val());
  if (cmd.length == 0) return;

  updateHistory(cmd);

  working = true;
  $('#go').html('');
  $.ajax({
    type: 'GET', url: '/cmd?' + escapeCommand(cmd),
    dataType: 'html',
    success: function (response) {
      appendResult(cmd, response);
    },
    error: function (request, message, exception) {
      appendResult(
        '' + cmd + '',
        'HTTP ' + request.status
        + ' ' + request.statusText + ''
        + ' ' + request.responseText);
    },
    complete: function (request, message) {
      input.val('');
      working = false;
      $('#go').text('go');
      last_request = request;
    }
  });
});

// Add the user's command and the response
// returned from the server to the output list
function appendResult(command,response) {
  var output = $('#output');
  var scroll = $('#output_scroll');
  output.append(
        '

' + command + '
' +
        '
' + response + '

'
  );
  if (output.outerHeight() > scroll.innerHeight()) {
    scroll.animate({ scrollTop:
      (output.outerHeight() - scroll.innerHeight() + 32) },
      750);
  }
}

// URI encode the user's command
function escapeCommand(cmd) {
  return escape(cmd.replace(/ /g,'+'));
}

// Style-related. Ensure the output window fills the browser,
// save for a space at the bottom for the prompt.
function setOutputSize() {
  $('#output_scroll').css('height',
    ($('body').innerHeight() - $('#prompt').outerHeight())
      + 'px');
}
$(setOutputSize);
$(window).resize(setOutputSize);

$(function() { $('#input').focus() });

// Pull the current working directory from browser cookies
// and use it as the prompt. The prompt floats over top
// of the input box so we need to adjust the input's
// padding property to allow space for it.
function displayCwd() {
  var newPrompt = $.cookie('CWD') + '>';
  var div = $('#cwd');
  if (div.text() != newPrompt) {
    div.text(newPrompt);
    $('#input').css('paddingLeft',(div.outerWidth() + 5) + 'px');
  }
}
$(displayCwd);
$('#cwd').ajaxComplete(displayCwd);

<commit_msg>Tab completion support for the client.<commit_after>// A history of commands sent to the server,
// oldest first.
var history = [''];
var history_position = 0;

// True if there is an ajax request en route
// to the server. The prompt only allows one
// request at a time.
var working = false;

// Debugging variable, remove at some point maybe
var last_request = null;

// Add an executed command onto the history stack
function updateHistory(cmd) {
  history.pop(); // Get rid of the blank off the end
  history.push(cmd); // Put the new command on the stack
  history.push(''); // Put a new blank on the end
  history_position = history.length - 1;
}

// Track back and forth through the history stack
$('#input').keydown(function(event) {
  // 38 == UP key
  // 40 == DOWN key
  if (event.which != 38 && event.which != 40) {
    return;
  }

  // We save the current command back into the stack
  // in case it's been modified.
  var p = $('#input');
  var current_cmd = p.val();
  history[history_position] = current_cmd;

  event.preventDefault();
  if (event.which == 38) {
    if (history_position == 0) {
      return;
    }
    p.val(history[--history_position]);
  } else {
    if (history_position == history.length - 1) {
      return;
    }
    p.val(history[++history_position]);
  }

  // Move cursor to the end of the prompt
  p[0].selectionStart = p[0].selectionEnd = p.val().length;
});

// Tab completion service
$('#input').keydown(function(event) {
  if (event.which != 9 || event.shiftKey) {
    return;
  }
  event.preventDefault();

  // Pull from the prompt the root that should be
  // sent to the server for tab completion. This is
  // the portion of the prompt between the cursor and
  // the preceding space.  var input = $('#input')[0];
  var input = $('#input')[0];
  var root = input.value.substring(0, input.selectionStart);
  var start = root.lastIndexOf(' ');
  root = root.substring(start + 1, root.length);
  var type = start == -1 ? 'cmd' : 'file';

  setWorking(true);
  $.ajax({
    type: 'GET', url: '/tab?' + type + '&' + escape(root),
    dataType: 'html',
    success: function (response) {
      var before = input.value.substring(0, start + 1);
      var after = input.value.substring(input.selectionEnd,
                                        input.value.length);
      if (response.match(/<.*>/)) {
        appendResult(before + '' + root + '' + after, response);
      } else {
        input.value = before + response + after;
        input.selectionStart = input.selectionEnd = before.length + response.length;
      }
    },
    complete: function (request, message) {
      setWorking(false);
    }
  });
});

// Send the user's command to the server when
// the form is submitted.
$('#prompt').submit(function(event) {
  event.preventDefault();
  if (working)
    return;

  var input = $('#input');
  var cmd = $.trim(input.val());
  if (cmd.length == 0) return;

  updateHistory(cmd);

  setWorking(true);
  $.ajax({
    type: 'GET', url: '/cmd?' + escapeCommand(cmd),
    dataType: 'html',
    success: function (response) {
      input.val('');
      appendResult(cmd, response);
    },
    error: function (request, message, exception) {
      appendResult(
        '' + cmd + '',
        'HTTP ' + request.status
        + ' ' + request.statusText + ''
        + ' ' + request.responseText);
    },
    complete: function (request, message) {
      setWorking(false);
      last_request = request;
    }
  });
});

// When the prompt is 'working' it is disabled
function setWorking(w) {
  working = w;
  $('#input')[0].disabled = working;
  if (working) {
    $('#go').html('');
  } else {
    $('#go').text('go');
  }
}

// Add the user's command and the response
// returned from the server to the output list
function appendResult(command,response) {
  var output = $('#output');
  var scroll = $('#output_scroll');
  output.append(
        '

' + command + '
' +
        '
' + response + '

'
  );
  if (output.outerHeight() > scroll.innerHeight()) {
    scroll.animate({ scrollTop:
      (output.outerHeight() - scroll.innerHeight() + 32) },
      750);
  }
}

// URI encode the user's command
function escapeCommand(cmd) {
  return escape(cmd.replace(/ /g,'+'));
}

// Style-related. Ensure the output window fills the browser,
// save for a space at the bottom for the prompt.
function setOutputSize() {
  $('#output_scroll').css('height',
    ($('body').innerHeight() - $('#prompt').outerHeight())
      + 'px');
}
$(setOutputSize);
$(window).resize(setOutputSize);

$(function() { $('#input').focus() });

// Pull the current working directory from browser cookies
// and use it as the prompt. The prompt floats over top
// of the input box so we need to adjust the input's
// padding property to allow space for it.
function displayCwd() {
  var newPrompt = $.cookie('CWD') + '>';
  var div = $('#cwd');
  if (div.text() != newPrompt) {
    div.text(newPrompt);
    $('#input').css('paddingLeft',(div.outerWidth() + 5) + 'px');
  }
}
$(displayCwd);
$('#cwd').ajaxComplete(displayCwd);

<|endoftext|>


<commit_before>console.log('Pacman extension loading');

var initiatePacmanSpacenavHandlers = function() {

  GUTTER = 100;
  MESSAGE_INTERVAL = 200; // [ms]

  messageTs = 0;

  var pacmanFrame = document.getElementById('i');

  if (pacmanFrame == null) {
    console.log("DOM elements are not ready yet... wating for a while...");
    setTimeout(initiatePacmanSpacenavHandlers, 2000);
    return;
  }

  var pacmanWindow = pacmanFrame.contentWindow;

  var slinkyRosKiosk = new ROSLIB.Ros({
    url: 'wss://42-b:9090'
  });

  var navigatorListener = new ROSLIB.Topic({
    ros: slinkyRosKiosk,
      name: '/spacenav/offset',
      messageType: 'geometry_msgs/Vector3',
      throttle_rate: 100
  });

  function keydown(which) {
    var e = new Event('keydown');
    e.which = which;
    e.keyCode = which;
    return e;
  }

  var previousMessage = "";

  function move(direction) {
    // var t = new Date().getTime();

    if (previousMessage == direction) return;
    //if (t - messageTs < MESSAGE_INTERVAL) return;
    //messageTs = t;
    previousMessage = direction;

    if (direction == 'LEFT') left();
    else if (direction == 'RIGHT') right();
    else if (direction == 'DOWN') down();
    else if (direction == 'UP') up();
  };

  function left()  { console.log('LEFT');  pacmanWindow.dispatchEvent(keydown(37)); }
  function up()    { console.log('UP');    pacmanWindow.dispatchEvent(keydown(38)); }
  function right() { console.log('RIGHT'); pacmanWindow.dispatchEvent(keydown(39)); }
  function down()  { console.log('DOWN');  pacmanWindow.dispatchEvent(keydown(40)); }

  navigatorListener.subscribe(function(v){

    if (v.x > GUTTER) move('UP');
    else if (v.x < -GUTTER) move('DOWN');
    else if (v.y > GUTTER) move('LEFT');
    else if (v.y < -GUTTER) move('RIGHT');
  });

  console.log("Pacman loaded");
}

initiatePacmanSpacenavHandlers();
<commit_msg>Better SpaceNav input for Pac Man<commit_after>console.log('Pacman extension loading');

var initiatePacmanSpacenavHandlers = function() {

  var GUTTER = 180;

  var keyBindings = {
    'LEFT': 37,
    'UP': 38,
    'RIGHT': 39,
    'DOWN': 40
  };

  var pacmanFrame = document.getElementById('i');

  if (pacmanFrame == null) {
    console.log('DOM elements are not ready yet... wating for a while...');
    setTimeout(initiatePacmanSpacenavHandlers, 2000);
    return;
  }

  var pacmanWindow = pacmanFrame.contentWindow;

  var slinkyRosKiosk = new ROSLIB.Ros({
    url: 'wss://42-b:9090'
  });

  var navigatorListener = new ROSLIB.Topic({
    ros: slinkyRosKiosk,
      name: '/spacenav/twist',
      messageType: 'geometry_msgs/Twist',
      throttle_rate: 30
  });

  function keydown(which) {
    var e = new Event('keydown');
    e.which = which;
    e.keyCode = which;
    return e;
  }

  var previousMessage = '';

  function move(direction) {
    if (previousMessage == direction) return;
    previousMessage = direction;

    var keyCode = keyBindings[direction];
    pacmanWindow.dispatchEvent(keydown(keyCode));
  };

  navigatorListener.subscribe(function(twist) {

    // use a combination of linear and angular values
    var spacenavX = -twist.linear.y + twist.angular.x;
    var spacenavY = twist.linear.x + twist.angular.y;

    if (spacenavY > GUTTER) move('UP');
    else if (spacenavY < -GUTTER) move('DOWN');
    else if (spacenavX > GUTTER) move('RIGHT');
    else if (spacenavX < -GUTTER) move('LEFT');
  });

  console.log('Pacman loaded');
}

initiatePacmanSpacenavHandlers();
<|endoftext|>


<commit_before>/**
 *  Modules
 */
var mongoose = require('mongoose');
/*Promise is depreciated in recent monoogse versions so separate promise package is required */
mongoose.Promise = require('bluebird');

var gracefulShutdown;
var dbURI = 'mongodb://127.0.0.1:27017/hpc_monitoring';

var mongoOptions =
    {
        db: {safe: true},
        server: {
            socketOptions: {
                keepAlive: 60000
            }
        }
    };

mongoose.connect(dbURI,mongoOptions);

/*CONNECTION EVENTS*/
mongoose.connection.on('connected', function () {
    console.log('Mongoose connected to ' + dbURI);
});
mongoose.connection.on('error', function (err) {
    console.log('Mongoose connection error: ' + err);
});
mongoose.connection.on('disconnected', function () {
    console.log('Mongoose disconnected');
});

/* CAPTURE APP TERMINATION/RESTART EVENTS */
/* To be called when process is restarted or terminated */
gracefulShutdown = function (msg, callback) {
    mongoose.connection.close(function () {
        console.log('Mongoose disconnected through ' + msg);
        callback();
    });
};
/* For nodemon restarts */
process.once('SIGUSR2', function () {
    gracefulShutdown('nodemon restart', function () {
        process.kill(process.pid, 'SIGUSR2');
    });
});
/* For app termination */
process.on('SIGINT', function () {
    gracefulShutdown('app termination', function () {
        process.exit(0);
    });
});

/* YOUR SCHEMAS & MODELS */
require('./users');

module.exports.dbURI = dbURI;
<commit_msg>Deprecation fixes: Added new URL string parser option to MongoConnect object Added new Server Discover and Monitoring engine to MongoConnect object<commit_after>/**
 *  Modules
 */
const mongoose = require('mongoose');

/*Promise is depreciated in recent monoogse versions so separate promise package is required */
mongoose.Promise = require('bluebird');

var gracefulShutdown;
var dbURI = 'mongodb://127.0.0.1:27017/hpc_monitoring';
var mongoOptions =
{
    useNewUrlParser: true,
    useUnifiedTopology: true,
    db: {safe: true},
    server: {
        socketOptions: {
            keepAlive: 60000
        }
    }
};

mongoose.connect(dbURI, mongoOptions);

/*CONNECTION EVENTS*/
mongoose.connection.on('connected', function () {
    console.log('Mongoose connected to ' + dbURI);
});
mongoose.connection.on('error', function (err) {
    console.log('Mongoose connection error: ' + err);
});
mongoose.connection.on('disconnected', function () {
    console.log('Mongoose disconnected');
});

/* CAPTURE APP TERMINATION/RESTART EVENTS */
/* To be called when process is restarted or terminated */
gracefulShutdown = function (msg, callback) {
    mongoose.connection.close(function () {
        console.log('Mongoose disconnected through ' + msg);
        callback();
    });
};
/* For nodemon restarts */
process.once('SIGUSR2', function () {
    gracefulShutdown('nodemon restart', function () {
        process.kill(process.pid, 'SIGUSR2');
    });
});
/* For app termination */
process.on('SIGINT', function () {
    gracefulShutdown('app termination', function () {
        process.exit(0);
    });
});

/* YOUR SCHEMAS & MODELS */
require('./users');

module.exports.dbURI = dbURI;
<|endoftext|>


<commit_before>import { initOptions, keycloak } from "keycloak"
;(async() => {
  keycloak.onTokenExpired = () =>
    keycloak
      .updateToken()
      .then(() => {
        console.info("Token refreshed")
      })
      .catch(error => {
        console.warn(
          "Keycloak client failed to refresh token, re-authentication is needed"
        )
        console.warn(error)
      })

  try {
    const authenticated = await keycloak.init({ onLoad: initOptions.onLoad })
    if (!authenticated) {
      console.info("Keycloak client not authenticated, reloading page...")
      window.location.reload()
      return
    }
  } catch (error) {
    console.info("Error occurred during Keycloak client initialization")
    console.err(error)
    return
  }

  console.info("Authenticated successfully")
  try {
    require("index.js")
  } catch (error) {
    console.error(error)
  }
})()

export default keycloak
<commit_msg>Fix typo in error handling, preventing an error to be thrown while catching a top level error<commit_after>import { initOptions, keycloak } from "keycloak"
;(async() => {
  keycloak.onTokenExpired = () =>
    keycloak
      .updateToken()
      .then(() => {
        console.info("Token refreshed")
      })
      .catch(error => {
        console.warn(
          "Keycloak client failed to refresh token, re-authentication is needed"
        )
        console.warn(error)
      })

  try {
    const authenticated = await keycloak.init({ onLoad: initOptions.onLoad })
    if (!authenticated) {
      console.info("Keycloak client not authenticated, reloading page...")
      window.location.reload()
      return
    }
  } catch (error) {
    console.info("Error occurred during Keycloak client initialization")
    console.error(error)
    return
  }

  console.info("Authenticated successfully")
  try {
    require("index.js")
  } catch (error) {
    console.error(error)
  }
})()

export default keycloak
<|endoftext|>


<commit_before>const webpack = require('webpack')
const DEBUG = process.env.NODE_ENV !== 'production'

console.log(DEBUG ? 'development' : 'production')

const plugins = [
  new webpack.optimize.OccurrenceOrderPlugin()
]

if (!DEBUG) {
  plugins.push(
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production')
      }
    }),
    new webpack.optimize.UglifyJsPlugin({ compress: { screw_ie8: true, warnings: false } }),
    new webpack.optimize.AggressiveMergingPlugin(),
    new webpack.LoaderOptionsPlugin({
      debug: DEBUG
    })
  )
}

module.exports = {
  devtool: DEBUG ? 'inline-source-map' : 'hidden-source-map',
  entry: ['babel-polyfill', '.'],
  output: {
    filename: '../public/bundle.js'
  },
  module: {
    loaders: [{
      test: /\.jsx?$/,
      loader: 'babel-loader',
      exclude: /node_modules/
    },
    {
      test: /\.styl$/,
      loader: 'style-loader!css-loader!stylus-loader'
    }]
  },
  resolve: {
    extensions: ['.js', '.jsx', '.styl']
  },
  plugins: plugins
}
<commit_msg>fix(webpack): push debug plugins<commit_after>const webpack = require('webpack')
const DEBUG = process.env.NODE_ENV !== 'production'

console.log(DEBUG ? 'development' : 'production')

const plugins = [
  new webpack.optimize.OccurrenceOrderPlugin()
]

if (!DEBUG) {
  plugins.push(
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production')
      }
    }),
    new webpack.optimize.UglifyJsPlugin({ compress: { screw_ie8: true, warnings: false } }),
    new webpack.optimize.AggressiveMergingPlugin()
  )
} else {
  plugins.push(
    new webpack.LoaderOptionsPlugin({
      debug: DEBUG
    })
  )
}

module.exports = {
  devtool: DEBUG ? 'inline-source-map' : 'hidden-source-map',
  entry: ['babel-polyfill', '.'],
  output: {
    filename: '../public/bundle.js'
  },
  module: {
    loaders: [{
      test: /\.jsx?$/,
      loader: 'babel-loader',
      exclude: /node_modules/
    },
    {
      test: /\.styl$/,
      loader: 'style-loader!css-loader!stylus-loader'
    }]
  },
  resolve: {
    extensions: ['.js', '.jsx', '.styl']
  },
  plugins: plugins
}
<|endoftext|>


<commit_before>const path = require('path');
const webpack = require("webpack");
const GitRevisionPlugin = require('git-revision-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  entry: {
      main: './src/index.js',
  },
  output: {
    filename: '[name]-bundle.js',
    path: path.resolve(__dirname, 'dist', '[git-revision-hash]'),
    publicPath: '/dist/[git-revision-hash]/'
  },
  optimization: {
    splitChunks: {
      chunks: 'all',
    }
  },
  resolve: {
    alias: {
      // underscore: 'vendor/underscore.min',
      // backbone: 'vendor/backbone/backbone',
      marionette: 'backbone.marionette/lib/backbone.marionette.min',
      // 'backbone.paginator': 'vendor/backbone/backbone.paginator',
      // 'backbone-validation': 'vendor/backbone/backbone-validation',
      // backgrid: 'vendor/backbone/backgrid',
      // 'backgrid-paginator': 'vendor/backbone/backgrid-paginator',
      // 'backgrid-select-all': 'vendor/backbone/backgrid-select-all',
      // 'backbone.syphon': 'vendor/backbone/backbone.syphon',

      // 'jquery': 'vendor/jquery/jquery-1.9.1.min',
      // 'jquery-ui': 'vendor/jquery/jquery-ui.min',
      // 'jquery.cookie': 'vendor/jquery/jquery.cookie',

      'jquery.touchswipe': 'jquery-touchswipe',
      // 'jquery.touchswipe': 'vendor/jquery/jquery.touchSwipe',
      // 'jquery-ui.combobox': 'vendor/jquery/jquery-ui.combobox',
      'jquery.ui': 'jquery-ui', // Only required for timepicker-addon 1.5.5 apparently!
      'jquery-ui.timepicker': 'jquery-ui-timepicker-addon', // Need to update timepicker css to avoid showing microseconds/milliseconds
      // 'jquery-ui.timepicker': 'vendor/jquery/jquery-ui.timepicker-addon',

      'jquery.flot': 'vendor/flot/jquery.flot.min',
      'jquery.flot.resize': 'vendor/flot/jquery.flot.resize',
      'jquery.flot.pie': 'vendor/flot/jquery.flot.pie',
      'jquery.flot.time': 'vendor/flot/jquery.flot.time.min',
      'jquery.flot.selection': 'vendor/flot/jquery.flot.selection',
      'jquery.flot.stack': 'vendor/flot/jquery.flot.stack',

      'jquery.flot.tickrotor': 'vendor/flot/jquery.flot.tickrotor',
      'jquery.flot.tooltip': 'vendor/flot/jquery.flot.tooltip',
      'jquery.flot.axislabels': 'vendor/flot/jquery.flot.axislabels',

      'jquery.mp': 'vendor/jquery/jquery.magnific-popup',

      // jeditable provided by NPM.
      'jquery.editable': 'jquery-jeditable/dist/jquery.jeditable.min',
      'jquery.editable.datepicker': 'jquery-jeditable/dist/jquery.jeditable.datepicker.min',
      // 'jquery.editable': 'vendor/jquery/jquery.jeditable.min',
      // 'jquery.editable.datepicker': 'vendor/jquery/jquery.jeditable.datepicker',

      'jquery.color': 'vendor/jquery/jquery.color',

      // Canvas Mix in class..
      // canvas: 'utils/canvas',

      // Moved Caman to npm
      caman: 'vendor/caman.min',
      // fibers included as a dependency of caman through npm
      // using newer version as old (6 years) 1.0.1 not compatible with v8

      // heatmap in npm has dependency on canvas/node-gyp... so use old one for now
      heatmap: 'vendor/hmap',

      // gunzip is actually the
      gzip: 'vendor/gunzip.min',

      // markdown: 'vendor/markdown',

      // three: 'vendor/three.min',
      // uglymol: 'vendor/uglymol',

      // moment: 'vendor/moment',

      // highmaps: 'vendor/highmaps/highmaps',
      // 'highmaps-world': 'vendor/highmaps/world',

      // Move these to npm installs once working
      vue: 'vue/dist/vue.min',
      veevalidate: 'vee-validate',
      // veevalidate: 'vendor/vue/vee-validate.min',
      // promise: 'vendor/vue/polyfill.min',
      // promise: 'polyfill',
    },
    modules: [
      path.resolve(__dirname, 'js'),
      path.resolve(__dirname, 'node_modules'),
    ]
  },
  module: {
    rules: [
      {
        test: /\.html$/,
        use: [
          {
            loader: 'underscore-template-loader',
            options: {
              engine: 'underscore',
            }
          }
        ],
        exclude: [
          path.resolve(__dirname, 'js/templates/vue')
        ]
      },
      {
        test: /\.xml$/,
        use: [
          {
            loader: 'raw-loader',
          }
        ]
      },
      {
        test: /vue\/.+\.html/,
        use: [
          {
            loader: 'raw-loader',
          }
        ]
      },
      // We need to help Caman load properly
      // Caman adds to the window object within a browser
      // The import loader ensures it it recognised as browser env not NodeJS
      {
        test: /caman\.min\.js$/,
        use: "imports-loader?exports=>undefined,require=>false,this=>window"
      }
    ]
  },
  plugins: [
    new webpack.ProvidePlugin({
       $: "jquery",
        jQuery: "jquery",
        _: "underscore",
    }),
    // This generates a short (8 char) git hash used for build paths
    new GitRevisionPlugin({
      commithashCommand: 'rev-parse --short HEAD'
    }),
    // This builds an index.php file from the src template
    new HtmlWebpackPlugin({
      title: 'SynchWeb Webpack',
      filename: path.resolve(__dirname, 'index.php'),
      template: 'src/index.php',
    }),
  ]
}
<commit_msg>Tidy webpack alias entries<commit_after>const path = require('path');
const webpack = require("webpack");
const GitRevisionPlugin = require('git-revision-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  entry: {
      main: './src/index.js',
  },
  output: {
    filename: '[name]-bundle.js',
    path: path.resolve(__dirname, 'dist', '[git-revision-hash]'),
    publicPath: '/dist/[git-revision-hash]/'
  },
  optimization: {
    splitChunks: {
      chunks: 'all',
    }
  },
  resolve: {
    alias: {
      marionette: 'backbone.marionette/lib/backbone.marionette.min',

      'jquery.touchswipe': 'jquery-touchswipe',
      'jquery.ui': 'jquery-ui', // Only required for timepicker-addon 1.5.5 apparently!
      'jquery-ui.timepicker': 'jquery-ui-timepicker-addon', // Need to update timepicker css to avoid showing microseconds/milliseconds

      'jquery.flot': 'vendor/flot/jquery.flot.min',
      'jquery.flot.resize': 'vendor/flot/jquery.flot.resize',
      'jquery.flot.pie': 'vendor/flot/jquery.flot.pie',
      'jquery.flot.time': 'vendor/flot/jquery.flot.time.min',
      'jquery.flot.selection': 'vendor/flot/jquery.flot.selection',
      'jquery.flot.stack': 'vendor/flot/jquery.flot.stack',

      'jquery.flot.tickrotor': 'vendor/flot/jquery.flot.tickrotor',
      'jquery.flot.tooltip': 'vendor/flot/jquery.flot.tooltip',
      'jquery.flot.axislabels': 'vendor/flot/jquery.flot.axislabels',

      'jquery.mp': 'vendor/jquery/jquery.magnific-popup',

      // jeditable provided by NPM.
      'jquery.editable': 'jquery-jeditable/dist/jquery.jeditable.min',
      'jquery.editable.datepicker': 'jquery-jeditable/dist/jquery.jeditable.datepicker.min',

      'jquery.color': 'vendor/jquery/jquery.color',

      // Canvas Mix in class..
      // canvas: 'utils/canvas',

      // Caman npm depends on fibers, canvas, fs which we don't wont...
      caman: 'vendor/caman.min',

      // heatmap in npm has dependency on canvas/node-gyp... so use old one for now
      heatmap: 'vendor/hmap',

      // gunzip is actually the
      gzip: 'vendor/gunzip.min',

      // highmaps: 'vendor/highmaps/highmaps',
      // 'highmaps-world': 'vendor/highmaps/world',

      // Move these to npm installs once working
      vue: 'vue/dist/vue.min',
      veevalidate: 'vee-validate',
      // promise: 'vendor/vue/polyfill.min',
    },
    modules: [
      path.resolve(__dirname, 'js'),
      path.resolve(__dirname, 'node_modules'),
    ]
  },
  module: {
    rules: [
      {
        test: /\.html$/,
        use: [
          {
            loader: 'underscore-template-loader',
            options: {
              engine: 'underscore',
            }
          }
        ],
        exclude: [
          path.resolve(__dirname, 'js/templates/vue')
        ]
      },
      {
        test: /\.xml$/,
        use: [
          {
            loader: 'raw-loader',
          }
        ]
      },
      {
        test: /vue\/.+\.html/,
        use: [
          {
            loader: 'raw-loader',
          }
        ]
      },
      // We need to help Caman load properly
      // Caman adds to the window object within a browser
      // The import loader ensures it it recognised as browser env not NodeJS
      {
        test: /caman\.min\.js$/,
        use: "imports-loader?exports=>undefined,require=>false,this=>window"
      }
    ]
  },
  plugins: [
    new webpack.ProvidePlugin({
       $: "jquery",
        jQuery: "jquery",
        _: "underscore",
    }),
    // This generates a short (8 char) git hash used for build paths
    new GitRevisionPlugin({
      commithashCommand: 'rev-parse --short HEAD'
    }),
    // This builds an index.php file from the src template
    new HtmlWebpackPlugin({
      title: 'SynchWeb Webpack',
      filename: path.resolve(__dirname, 'index.php'),
      template: 'src/index.php',
    }),
  ]
}
<|endoftext|>


<commit_before>var App = function (host, port, type) {
 this.host = host;
 this.port = port;
 this.type = type;
 this.index = 0;
 this.count = 20;
 this.unviewedPosts = [];
 this.cardTpl = null;

 //Private functions
 var $this = this;

 var linking = function (tweet) {
   var twit = tweet.replace(/(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/ig,'$1')
        .replace(/#([a-zA-Z0-9_]+)/g,'#$1')
        .replace(/@([a-zA-Z0-9_]+)/g,'@$1');

   return twit;
 }

 var render_realtime_card = function (data) {
  if ($(".card[data-id='" + data.id + "']").length > 0) {
   //If the card already exists ignore it
   return;
  }
  var rendered = Mustache.render($this.cardTpl, parse_post(data));
  $("#stream").prepend(rendered);
  $("#new_posts_counter").html($this.unviewedPosts.length);
  scrollTop();
 }
 var render_archived_card = function (data) {
  if ($(".card[data-id='" + data.id + "']").length > 0) {
   //If the card already exists ignore it
   return;
  }
  var rendered = Mustache.render($this.cardTpl, parse_post(data));
  $("#stream").append(rendered);
  $("#new_posts_counter").html($this.unviewedPosts.length);

 }

 function scrollTop() {
  window.scrollTo(0, 0);
 }

 function element_in_scroll(elem) {
  var docViewTop = $(window).scrollTop();
  var docViewBottom = docViewTop + $(window).height();

  var elemTop = $(elem).offset().top;
  var elemBottom = elemTop + $(elem).height();

  return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
 }

 var parse_post = function (post) {
  var parsed_post = {
   "title": "",
    "body": twttr.txt.autoLink(post.title),
   "img": post.medias ? post.medias[0] : "",
   "id": post.id,
   "source": post.service_uri,
   "type": post.type,
   "username": post.username
  }

  return parsed_post;
 }

 var post_factory = function (posts) {
  var res = []
  for (var i = 0; i < posts.length; i++) {
   var post_unified = {
    "title": "",
    "body": posts[i].title,
    "img": posts[i].medias[0],
    "id": posts[i].id,
    "source": posts[i].service_uri,
    "type": posts[i].type,
    "username": posts[i].username
   }
   res.push(post_unified)
  }
  return res;
 }

 var show_new = function (e) {
  var len = $this.unviewedPosts.length;
  for (var i = 0; i < len; i++) {
   var post = $this.unviewedPosts.shift();
   render_realtime_card(post);
  }
  e.preventDefault();
  return false;
 }

 var show_more = function (e) {
  $this.index = $this.count + $this.index;
  var stop = $this.index + $this.count;
  $.get("/" + $this.type + "/" + $this.index + "/" + stop + "/json", function (posts) {
   if (posts) {
    posts = JSON.parse(posts);
    var len = posts.length;
    for (var i = 0; i < len; i++) {
     var post = posts.shift();
     render_archived_card(post);
    }
   }
   if (ga) {
    ga('send', 'pageview', {
     'page': '/' + $this.type,
     'title': 'More of Type ' + $this.type
    });
   }

  });
  return false;
 }

 this.init = function (posts, index, count) {
  this.index = index;
  this.count = count;

  $(document).ready(function () {
   $.get("/views/card.tpl.html", function (tpl) {

    $this.cardTpl = tpl;

    //Render preloaded data
    if (posts) {
     var len = posts.length;
     for (var i = 0; i < len; i++) {
      var post = posts.shift();
      render_archived_card(post);
     }
    }
    var socket = io.connect('http://' + $this.host + ':' + $this.port);
    socket.on('connect', function () {
     socket.emit('subscribe', this.type);
    });

    socket.on('message', function (message) {
     var post = JSON.parse(message);

     $this.unviewedPosts.push(post);
     $("#new_posts_counter").html($this.unviewedPosts.length);
    });
   });

   $("#show_new").click(show_new);
   $("#show_more").click(show_more);

   setInterval(function () {
    if ($this.unviewedPosts.length > 0) {
     $("#new_posts").show();
    } else {
     $("#new_posts").hide();
    }
   }, 500);

   $(window).scroll(function () {
    if (Math.ceil($(window).scrollTop()) == $(document).height() - $(window).height()) {
     show_more();
    }
   });

  });

 }

}<commit_msg>adding ga<commit_after>var App = function (host, port, type) {
 this.host = host;
 this.port = port;
 this.type = type;
 this.index = 0;
 this.count = 20;
 this.unviewedPosts = [];
 this.cardTpl = null;
 this.originalTitle = "";

 //Private functions
 var $this = this;

 var linking = function (tweet) {
  var twit = tweet.replace(/(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/ig, '$1')
   .replace(/#([a-zA-Z0-9_]+)/g, '#$1')
   .replace(/@([a-zA-Z0-9_]+)/g, '@$1');

  return twit;
 }

 var render_realtime_card = function (data) {
  if ($(".card[data-id='" + data.id + "']").length > 0) {
   //If the card already exists ignore it
   return;
  }
  var rendered = Mustache.render($this.cardTpl, parse_post(data));
  $("#stream").prepend(rendered);
  $("#new_posts_counter").html($this.unviewedPosts.length);
  scrollTop();
 }
 var render_archived_card = function (data) {
  if ($(".card[data-id='" + data.id + "']").length > 0) {
   //If the card already exists ignore it
   return;
  }
  var rendered = Mustache.render($this.cardTpl, parse_post(data));
  $("#stream").append(rendered);
  set_new_posts_counter();
 }

 function scrollTop() {
  window.scrollTo(0, 0);
 }

 function element_in_scroll(elem) {
  var docViewTop = $(window).scrollTop();
  var docViewBottom = docViewTop + $(window).height();

  var elemTop = $(elem).offset().top;
  var elemBottom = elemTop + $(elem).height();

  return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
 }

 var parse_post = function (post) {
  var parsed_post = {
   "title": "",
   "body": twttr.txt.autoLink(post.title),
   "img": post.medias ? post.medias[0] : "",
   "id": post.id,
   "source": post.service_uri,
   "type": post.type,
   "username": post.username
  }

  return parsed_post;
 }

 var post_factory = function (posts) {
  var res = []
  for (var i = 0; i < posts.length; i++) {
   var post_unified = {
    "title": "",
    "body": posts[i].title,
    "img": posts[i].medias[0],
    "id": posts[i].id,
    "source": posts[i].service_uri,
    "type": posts[i].type,
    "username": posts[i].username
   }
   res.push(post_unified)
  }
  return res;
 }

 var show_new = function (e) {
  var len = $this.unviewedPosts.length;
  for (var i = 0; i < len; i++) {
   var post = $this.unviewedPosts.shift();
   render_realtime_card(post);
  }
  e.preventDefault();
  return false;
 }

 var show_more = function (e) {
  $this.index = $this.count + $this.index;
  var stop = $this.index + $this.count;
  $.get("/" + $this.type + "/" + $this.index + "/" + stop + "/json", function (posts) {
   if (posts) {
    posts = JSON.parse(posts);
    var len = posts.length;
    for (var i = 0; i < len; i++) {
     var post = posts.shift();
     render_archived_card(post);
    }
   }
   if (ga) {
    ga('send', 'pageview', {
     'page': '/' + $this.type,
     'title': 'More of Type ' + $this.type
    });
   }

  });
  return false;
 }

 function set_new_posts_counter() {
  var len = $this.unviewedPosts.length;
  $("#new_posts_counter").html(len);
  set_title(len);
 }

 function set_title(post_number) {
  document.title = $this.originalTitle + "(" + post_number + ")";
 }

 this.init = function (posts, index, count) {
  this.index = index;
  this.count = count;

  this.originalTitle = document.title;

  $(document).ready(function () {
   $.get("/views/card.tpl.html", function (tpl) {

    $this.cardTpl = tpl;

    //Render preloaded data
    if (posts) {
     var len = posts.length;
     for (var i = 0; i < len; i++) {
      var post = posts.shift();
      render_archived_card(post);
     }
    }
    var socket = io.connect('http://' + $this.host + ':' + $this.port);
    socket.on('connect', function () {
     socket.emit('subscribe', this.type);
    });

    socket.on('message', function (message) {
     var post = JSON.parse(message);

     $this.unviewedPosts.push(post);
     set_new_posts_counter();
    });
   });

   $("#show_new").click(show_new);
   $("#show_more").click(show_more);

   setInterval(function () {
    if ($this.unviewedPosts.length > 0) {
     $("#new_posts").show();
    } else {
     $("#new_posts").hide();
    }
   }, 500);

   $(window).scroll(function () {
    if (Math.ceil($(window).scrollTop()) == $(document).height() - $(window).height()) {
     show_more();
    }
   });

  });

 }

}<|endoftext|>


<commit_before>"use strict";

var util = require("../../util");
var t    = require("../../types");

var visitor = {
  enter: function (node, parent, scope, state) {
    // check if this node is an identifier that matches the same as our function id
    if (!t.isIdentifier(node, { name: state.id })) return;

    // check if this node is the one referenced
    if (!t.isReferenced(node, parent)) return;

    // check that we don't have a local variable declared as that removes the need
    // for the wrapper
    var localDeclar = scope.getBinding(state.id);
    if (localDeclar !== state.outerDeclar) return;

    state.selfReference = true;
    this.stop();
  }
};

exports.property = function (node, file, scope) {
  var key = t.toComputedKey(node, node.key);
  if (!t.isLiteral(key)) return node; // we can't set a function id with this

  var id = t.toIdentifier(key.value);
  key = t.identifier(id);

  var state = {
    id: id,
    selfReference: false,
    outerDeclar: scope.getBinding(id),
  };

  scope.traverse(node, visitor, state);

  if (state.selfReference) {
    // todo: support generators
    node.value = util.template("property-method-assignment-wrapper", {
      FUNCTION: node.value,
      FUNCTION_ID: key,
      FUNCTION_KEY: scope.generateUidIdentifier(id),
      WRAPPER_KEY: scope.generateUidIdentifier(id + "Wrapper")
    });
  } else {
    node.value.id = key;
  }
};
<commit_msg>support generators in nameMethod helper<commit_after>"use strict";

var util = require("../../util");
var t    = require("../../types");

var visitor = {
  enter: function (node, parent, scope, state) {
    // check if this node is an identifier that matches the same as our function id
    if (!t.isIdentifier(node, { name: state.id })) return;

    // check if this node is the one referenced
    if (!t.isReferenced(node, parent)) return;

    // check that we don't have a local variable declared as that removes the need
    // for the wrapper
    var localDeclar = scope.getBinding(state.id);
    if (localDeclar !== state.outerDeclar) return;

    state.selfReference = true;
    this.stop();
  }
};

exports.property = function (node, file, scope) {
  var key = t.toComputedKey(node, node.key);
  if (!t.isLiteral(key)) return node; // we can't set a function id with this

  var id = t.toIdentifier(key.value);
  key = t.identifier(id);

  var state = {
    id: id,
    selfReference: false,
    outerDeclar: scope.getBinding(id),
  };

  scope.traverse(node, visitor, state);

  var method = node.value;

  if (state.selfReference) {
    var templateName = "property-method-assignment-wrapper";
    if (method.generator) templateName += "-generator";
    node.value = util.template(templateName, {
      FUNCTION: method,
      FUNCTION_ID: key,
      FUNCTION_KEY: scope.generateUidIdentifier(id),
      WRAPPER_KEY: scope.generateUidIdentifier(id + "Wrapper")
    });
  } else {
    method.id = key;
  }
};
<|endoftext|>


<commit_before>const trackRegister = require('~/trackRegister');
const { pool } = require('~/database');

module.exports = (ctx) => {
  // TODO validate ctx.params
  const { token, deviceId, fromTime, maxCount, maxAge } = ctx.params;

  (async () => {
    const db = await pool.getConnection();

    const { user } = ctx.ctx;

    async function isDeviceOwner() {
      const [row] = await db.query('SELECT userId FROM trackingDevice WHERE deviceId = ?', [deviceId]);
      return row && row.userId === user.id;
    }

    try {
      if (!token && deviceId) {
        if (!user || !user.isAdmin && !await isDeviceOwner()) {
          ctx.respondError(403, 'forbidden');
          return;
        }
      }

      // TODO check if token exists

      let websockets = trackRegister.get(token || deviceId);
      if (!websockets) {
        websockets = new Set();
        trackRegister.set(token || deviceId, websockets);
      }

      websockets.add(ctx.ctx.websocket);

      const params = [token || deviceId];
      if (fromTime) {
        params.push(new Date(fromTime));
      }
      if (maxAge) {
        params.push(Number.parseInt(maxAge, 10));
      }
      if (maxCount) {
        params.push(Number.parseInt(maxCount, 10));
      }

      let result;

      if (maxCount === 0 || maxAge === 0) {
        result = [];
      } else if (deviceId) {
        result = await db.query(
          `SELECT id, lat, lon, message, createdAt, altitude, speed, accuracy, bearing, battery, gsmSignal
            FROM trackingPoint
            WHERE deviceId = ?
              ${fromTime ? 'AND createdAt >= ?' : ''}
              ${maxAge ? 'AND trackingPoint.createdAt >= ?' : ''}
            ORDER BY id
            ${maxCount ? 'LIMIT ?' : ''}`,
          params,
        );
      } else {
        result = await db.query(
          `SELECT trackingPoint.id, lat, lon, message, trackingPoint.createdAt, altitude, speed, accuracy, bearing, battery, gsmSignal
            FROM trackingPoint JOIN trackingAccessToken
              ON trackingPoint.deviceId = trackingAccessToken.deviceId
            WHERE trackingAccessToken.token = ?
              ${maxAge ? 'AND TIMESTAMPDIFF(SECOND, trackingPoint.createdAt, now()) < ?' : ''}
              ${fromTime ? 'AND trackingPoint.createdAt >= ?' : ''}
              AND (timeFrom IS NULL OR trackingPoint.createdAt >= timeFrom)
              AND (timeTo IS NULL OR trackingPoint.createdAt < timeTo)
            ORDER BY trackingPoint.id
            ${maxCount ? 'LIMIT ?' : ''}`,
          params,
        );
      }

      // TODO skip nulls

      ctx.respondResult(result.map(item => ({
        id: item.id,
        lat: item.lat,
        lon: item.lon,
        message: item.message,
        ts: item.createdAt,
        altitude: item.altitude,
        speed: item.speed,
        accuracy: item.accuracy,
        bearing: item.bearing,
        battery: item.battery,
        gsmSignal: item.gsmSignal,
        [token ? 'token' : 'deviceId']: token || deviceId,
      })));
    } finally {
      pool.releaseConnection(db);
    }
  })().catch((err) => {
    ctx.respondError(500, err.message);
  });
};
<commit_msg>fixed subscribe handler<commit_after>const trackRegister = require('~/trackRegister');
const { pool } = require('~/database');

module.exports = (ctx) => {
  // TODO validate ctx.params
  const { token, deviceId, fromTime, maxCount, maxAge } = ctx.params;

  (async () => {
    const db = await pool.getConnection();

    const { user } = ctx.ctx;

    try {
      if (deviceId) {
        const [row] = await db.query('SELECT userId FROM trackingDevice WHERE id = ?', [deviceId]);
        if (!row) {
          ctx.respondError(404, 'no such device');
          return;
        }

        if (!user || !user.isAdmin && row.userId !== user.id) {
          ctx.respondError(403, 'forbidden');
          return;
        }
      } else if (token) {
        const [row] = await db.query('SELECT 1 FROM trackingAccessToken WHERE token = ?', token);
        if (!row) {
          ctx.respondError(404, 'no such token');
          return;
        }
      }

      // TODO check if token exists

      let websockets = trackRegister.get(deviceId || token);
      if (!websockets) {
        websockets = new Set();
        trackRegister.set(deviceId || token, websockets);
      }

      websockets.add(ctx.ctx.websocket);

      const params = [deviceId || token];
      if (fromTime) {
        params.push(new Date(fromTime));
      }
      if (maxAge) {
        params.push(Number.parseInt(maxAge, 10));
      }
      if (maxCount) {
        params.push(Number.parseInt(maxCount, 10));
      }

      let result;

      if (maxCount === 0 || maxAge === 0) {
        result = [];
      } else if (deviceId) {
        result = await db.query(
          `SELECT id, lat, lon, message, createdAt, altitude, speed, accuracy, bearing, battery, gsmSignal
            FROM trackingPoint
            WHERE deviceId = ?
              ${fromTime ? 'AND createdAt >= ?' : ''}
              ${maxAge ? 'AND trackingPoint.createdAt >= ?' : ''}
            ORDER BY id
            ${maxCount ? 'LIMIT ?' : ''}`,
          params,
        );
      } else {
        result = await db.query(
          `SELECT trackingPoint.id, lat, lon, message, trackingPoint.createdAt, altitude, speed, accuracy, bearing, battery, gsmSignal
            FROM trackingPoint JOIN trackingAccessToken
              ON trackingPoint.deviceId = trackingAccessToken.deviceId
            WHERE trackingAccessToken.token = ?
              ${maxAge ? 'AND TIMESTAMPDIFF(SECOND, trackingPoint.createdAt, now()) < ?' : ''}
              ${fromTime ? 'AND trackingPoint.createdAt >= ?' : ''}
              AND (timeFrom IS NULL OR trackingPoint.createdAt >= timeFrom)
              AND (timeTo IS NULL OR trackingPoint.createdAt < timeTo)
            ORDER BY trackingPoint.id
            ${maxCount ? 'LIMIT ?' : ''}`,
          params,
        );
      }

      // TODO skip nulls

      ctx.respondResult(result.map(item => ({
        id: item.id,
        lat: item.lat,
        lon: item.lon,
        message: item.message,
        ts: item.createdAt,
        altitude: item.altitude,
        speed: item.speed,
        accuracy: item.accuracy,
        bearing: item.bearing,
        battery: item.battery,
        gsmSignal: item.gsmSignal,
        [token ? 'token' : 'deviceId']: deviceId || token,
      })));
    } finally {
      pool.releaseConnection(db);
    }
  })().catch((err) => {
    ctx.respondError(500, err.message);
  });
};
<|endoftext|>