<commit_before>var expect = require('expect.js'),
    Variable = require('../../lib/index.js').Variable;

/* global describe, it */
describe.only('Variable', function () {
    it('should initialise variable of type `any` and value `undefined`', function () {
        var v = new Variable();

        expect(v.value).to.be(undefined);
        expect(v.type).to.be('any');
    });

    it('should initialize variable with correct system value', function () {
        var v = new Variable();
        expect(v.system).to.be(undefined);

        v = new Variable({
            system: true
        });
        expect(v.system).to.be(true);

        v = new Variable({
            system: false
        });
        expect(v.system).to.be(false);
    });

    it('should update the sytem property of a variable', function () {
        var v = new Variable();
        v.update({ system: true });
        expect(v.system).to.be(true);

        v = new Variable({
            system: true
        });
        v.update({ system: false });
        expect(v.system).to.be(false);
    });

    it('should prepopulate value and type when passed to the constructor (string)', function () {
        var v = new Variable({
            value: 'Picard',
            type: 'string'
        });

        expect(v.value).to.be('Picard');
        expect(v.type).to.be('string');
    });

    it('should prepopulate value and type when passed to the constructor (number)', function () {
        var v = new Variable({
            value: 42,
            type: 'number'
        });

        expect(v.value).to.be(42);
        expect(v.type).to.be('number');
    });

    it('should prepopulate value and type when passed to the constructor (boolean)', function () {
        var v = new Variable({
            value: true,
            type: 'boolean'
        });

        expect(v.value).to.be(true);
        expect(v.type).to.be('boolean');
    });

    it('should prepopulate value and type when passed to the constructor (json)', function () {
        var vValue = { foo: 'bar' },
            v = new Variable({
                value: vValue,
                type: 'json'
            });

        expect(v.value).to.be(JSON.stringify(vValue));
        expect(v.type).to.be('json');
    });

    it('should typecast value during construction when type is provided (number)', function () {
        var v = new Variable({
            value: '108',
            type: 'number'
        });

        expect(v.value).to.be(108);
    });

    it('should typecast value during construction when type is provided (string)', function () {
        var v = new Variable({
            value: true,
            type: 'string'
        });

        expect(v.value).to.be('true');
    });

    it('should typecast value during construction when type is provided (boolean)', function () {
        var v = new Variable({
            value: 'foo',
            type: 'boolean'
        });

        expect(v.value).to.be(true);
    });

    it('should typecast value during construction when type is provided (json)', function () {
        var v = new Variable({
                value: null,
                type: 'json'
            }),
            v1 = new Variable({
                value: '{"foo":"bar"}',
                type: 'json'
            });

        expect(v.value).to.be('null');
        expect(v1.value).to.be('{"foo":"bar"}');
    });

    it('should support any data type if type is set to `any`', function () {
        var v = new Variable();

        v.set('Picard');
        expect(v.get()).to.be('Picard');

        v.set(3.142);
        expect(v.get()).to.be(3.142);
    });

    it('should type cast values to the specific type set', function () {
        var v = new Variable({
            type: 'string'
        });

        v.set('Picard');
        expect(v.get()).to.be('Picard');

        v.set(3.142);
        expect(v.get()).to.be('3.142');
    });

    it('should recast values when type is changed', function () {
        var v = new Variable({
            type: 'string'
        });

        v.set(3.142);
        expect(v.get()).to.be('3.142');

        v.valueType('number');
        expect(v.get()).to.be(3.142);
    });

    it('should handle functions correctly', function () {
        var v = new Variable({ type: 'string', key: 'foo', value: function () { return 'bar'; } });

        expect(v.get()).to.be('bar');
    });

    describe('.set', function () {
        it('should handle functions correctly', function () {
            var variable = new Variable({ type: 'string' });

            expect(variable.set.bind(variable)).withArgs(function () {
                return 'random';
            }).to.not.throwError();
        });
    });

    describe('.valueOf', function () {
        it('should handle set arguments correctly', function () {
            var variable = new Variable({ type: 'string', key: 'foo', value: 'bar' });

            variable.valueOf('newVal');
            expect(variable.value).to.be('newVal');
        });
    });

    describe('.toString', function () {
        it('should handle the absence of .valueOf correctly', function () {
            var variable = new Variable({ key: 'foo', value: Object.create(null) });

            expect(variable.toString()).to.be('');
        });
    });

    describe('.cast', function () {
        it('should use a default type of any if there is no existing type', function () {
            var variable = new Variable({ key: 'foo', value: 'bar' });

            delete variable.type;
            expect(variable.cast(123)).to.be.a('number');
        });
    });

    describe('.valueType', function () {
        it('should use the current type if no type is provided', function () {
            var variable = new Variable({ type: 'string', key: 'foo', value: 'bar' });

            expect(variable.valueType()).to.be('string');
        });

        it('should use the default type if no type is provided, and no type exists', function () {
            var variable = new Variable({ type: 'string', key: 'foo', value: 'bar' });
            delete variable.type;

            expect(variable.valueType()).to.be('any');
        });

        it('should cast to the specified type when specified', function () {
            var variable = new Variable({ type: 'string', key: 'foo', value: '123' });

            expect(variable.valueType('number')).to.be('number');
        });

        it('should handle invalid types correctly', function () {
            var variable = new Variable({ type: 'string', key: 'foo', value: '123' });
            delete variable.type;

            expect(variable.valueType('random')).to.be('any');
        });
    });

    describe('sanity', function () {
        it('constructor must be exported', function () {
            expect(Variable).to.be.a('function');
        });

        it('should create a new instance', function () {
            var v = new Variable();
            expect(v instanceof Variable).to.be.ok();
        });

        it('should not update if a non-object parameter is provided', function () {
            var v = new Variable({ key: 'foo', value: 'bar' });

            v.update();
            expect(v.key).to.be('foo');
            expect(v.value).to.be('bar');
        });
    });

    describe('isVariable', function () {
        it('should return true for a valid Variable instance', function () {
            expect(Variable.isVariable(new Variable({ type: 'string', key: 'foo', value: 'bar' }))).to.be(true);
        });

        it('should return false for a raw variable object', function () {
            expect(Variable.isVariable({ type: 'string', key: 'foo', value: 'bar' })).to.be(false);
        });

        it('should return false when called without arguments', function () {
            expect(Variable.isVariable()).to.be(false);
        });
    });
});
<commit_msg>Added more tests for json recast and value functions<commit_after>var expect = require('expect.js'),
    Variable = require('../../lib/index.js').Variable;

/* global describe, it */
describe('Variable', function () {
    it('should initialise variable of type `any` and value `undefined`', function () {
        var v = new Variable();

        expect(v.value).to.be(undefined);
        expect(v.type).to.be('any');
    });

    it('should initialize variable with correct system value', function () {
        var v = new Variable();
        expect(v.system).to.be(undefined);

        v = new Variable({
            system: true
        });
        expect(v.system).to.be(true);

        v = new Variable({
            system: false
        });
        expect(v.system).to.be(false);
    });

    it('should update the sytem property of a variable', function () {
        var v = new Variable();
        v.update({ system: true });
        expect(v.system).to.be(true);

        v = new Variable({
            system: true
        });
        v.update({ system: false });
        expect(v.system).to.be(false);
    });

    it('should prepopulate value and type when passed to the constructor (string)', function () {
        var v = new Variable({
            value: 'Picard',
            type: 'string'
        });

        expect(v.value).to.be('Picard');
        expect(v.type).to.be('string');
    });

    it('should prepopulate value and type when passed to the constructor (number)', function () {
        var v = new Variable({
            value: 42,
            type: 'number'
        });

        expect(v.value).to.be(42);
        expect(v.type).to.be('number');
    });

    it('should prepopulate value and type when passed to the constructor (boolean)', function () {
        var v = new Variable({
            value: true,
            type: 'boolean'
        });

        expect(v.value).to.be(true);
        expect(v.type).to.be('boolean');
    });

    it('should prepopulate value and type when passed to the constructor (json)', function () {
        var vValue = { foo: 'bar' },
            v = new Variable({
                value: vValue,
                type: 'json'
            });

        expect(v.value).to.be(JSON.stringify(vValue));
        expect(v.type).to.be('json');
    });

    it('should typecast value during construction when type is provided (number)', function () {
        var v = new Variable({
            value: '108',
            type: 'number'
        });

        expect(v.value).to.be(108);
    });

    it('should typecast value during construction when type is provided (string)', function () {
        var v = new Variable({
            value: true,
            type: 'string'
        });

        expect(v.value).to.be('true');
    });

    it('should typecast value during construction when type is provided (boolean)', function () {
        var v = new Variable({
            value: 'foo',
            type: 'boolean'
        });

        expect(v.value).to.be(true);
    });

    it('should typecast value during construction when type is provided (json)', function () {
        var v = new Variable({
                value: null,
                type: 'json'
            }),
            v1 = new Variable({
                value: '{"foo":"bar"}',
                type: 'json'
            });

        expect(v.value).to.be('null');
        expect(v1.value).to.be('{"foo":"bar"}');
    });

    it('should support any data type if type is set to `any`', function () {
        var v = new Variable(),
            jsonValue = { iam: 'json' };

        v.set('Picard');
        expect(v.get()).to.be('Picard');

        v.set(3.142);
        expect(v.get()).to.be(3.142);

        v.set(jsonValue);
        expect(v.get()).to.be(jsonValue);
    });

    it('should type cast values to the specific type set', function () {
        var v = new Variable({
            type: 'string'
        });

        v.set('Picard');
        expect(v.get()).to.be('Picard');

        v.set(3.142);
        expect(v.get()).to.be('3.142');

        v.set({ foo: 'bar' });
        expect(v.get()).to.be('[object Object]');
    });

    it('should recast values when type is changed', function () {
        var v = new Variable({
            type: 'string'
        });

        v.set(3.142);
        expect(v.get()).to.be('3.142');

        v.valueType('number');
        expect(v.get()).to.be(3.142);
    });

    it('should recast values when type is changed (json)', function () {
        var v = new Variable({
            type: 'string'
        });

        v.set({ foo: 'bar' });
        expect(v.get()).to.be('[object Object]');

        v.valueType('json');
        expect(v.get()).to.be(null);
    });

    it('should handle functions correctly', function () {
        var v = new Variable({ type: 'string', key: 'foo', value: function () { return 'bar'; } });

        expect(v.get()).to.be('bar');
    });

    it('should not touch value functions when type is changed', function () {
        var v = new Variable({ type: 'string', key: 'foo', value: function () { return 'foo'; } });

        expect(v.get()).to.be('foo');

        v.valueType('boolean');

        expect(v.value).to.be.a('function');
        expect(v.get()).to.be(true);
    });

    it('should typecast returns of values as functions correctly', function () {
        var v = new Variable({ type: 'number', key: 'foo', value: function () { return '3.14'; } }),
            v2 = new Variable({ type: 'boolean', key: 'foo', value: function () { return 'bar'; } });

        // number
        expect(v.get()).to.be(3.14);

        // boolean
        expect(v2.get()).to.be(true);
    });

    describe('.set', function () {
        it('should handle functions correctly', function () {
            var variable = new Variable({ type: 'string' });

            expect(variable.set.bind(variable)).withArgs(function () {
                return 'random';
            }).to.not.throwError();
        });
    });

    describe('.valueOf', function () {
        it('should handle set arguments correctly', function () {
            var variable = new Variable({ type: 'string', key: 'foo', value: 'bar' });

            variable.valueOf('newVal');
            expect(variable.value).to.be('newVal');
        });
    });

    describe('.toString', function () {
        it('should handle the absence of .valueOf correctly', function () {
            var variable = new Variable({ key: 'foo', value: Object.create(null) });

            expect(variable.toString()).to.be('');
        });
    });

    describe('.cast', function () {
        it('should use a default type of any if there is no existing type', function () {
            var variable = new Variable({ key: 'foo', value: 'bar' });

            delete variable.type;
            expect(variable.cast(123)).to.be.a('number');
        });
    });

    describe('.valueType', function () {
        it('should use the current type if no type is provided', function () {
            var variable = new Variable({ type: 'string', key: 'foo', value: 'bar' });

            expect(variable.valueType()).to.be('string');
        });

        it('should use the default type if no type is provided, and no type exists', function () {
            var variable = new Variable({ type: 'string', key: 'foo', value: 'bar' });
            delete variable.type;

            expect(variable.valueType()).to.be('any');
        });

        it('should cast to the specified type when specified', function () {
            var variable = new Variable({ type: 'string', key: 'foo', value: '123' });

            expect(variable.valueType('number')).to.be('number');
        });

        it('should handle invalid types correctly', function () {
            var variable = new Variable({ type: 'string', key: 'foo', value: '123' });
            delete variable.type;

            expect(variable.valueType('random')).to.be('any');
        });
    });

    describe('sanity', function () {
        it('constructor must be exported', function () {
            expect(Variable).to.be.a('function');
        });

        it('should create a new instance', function () {
            var v = new Variable();
            expect(v instanceof Variable).to.be.ok();
        });

        it('should not update if a non-object parameter is provided', function () {
            var v = new Variable({ key: 'foo', value: 'bar' });

            v.update();
            expect(v.key).to.be('foo');
            expect(v.value).to.be('bar');
        });
    });

    describe('isVariable', function () {
        it('should return true for a valid Variable instance', function () {
            expect(Variable.isVariable(new Variable({ type: 'string', key: 'foo', value: 'bar' }))).to.be(true);
        });

        it('should return false for a raw variable object', function () {
            expect(Variable.isVariable({ type: 'string', key: 'foo', value: 'bar' })).to.be(false);
        });

        it('should return false when called without arguments', function () {
            expect(Variable.isVariable()).to.be(false);
        });
    });
});
<|endoftext|>


<commit_before>var xtend = require('xtend');
var jwt = require('jwt-simple');

var defaultOptions = {
  algorithm: 'HS256',
  succeedWithoutToken: false
};

function authenticate(options, verify) {
  var _this = this;
  this.options = xtend(defaultOptions, options);
  if (!this.options.secret) {
    throw new TypeError('SocketioJwtAuth requires a secret');
  }

  this.verify = verify;
  if (!this.verify) {
    throw new TypeError('SocketioJwtAuth requires a verify callback');
  }

  this.success = function(next) {
    next();
  }

  this.fail = function(err, next) {
    next(new Error(err));
  }

  return function(socket, next) {
    var token = socket.handshake.query.auth_token;
    var verified = function(err, user, message) {
      if (err) {
        return _this.fail(err, next);
      } else if (!user) {
        if (!_this.options.succeedWithoutToken) return _this.fail(message, next);
        socket.request.user = {logged_in: false};
        return _this.success(next)
      } else {
        user.logged_in = true;
        socket.request.user = user;
        return _this.success(next);
      }
    };
    try {
      var payload = {};
      if (!token) {
        if (!_this.options.succeedWithoutToken) {
          return _this.fail('No auth token', next);
        }
      } else {
        payload = jwt.decode(token, _this.options.secret, _this.options.algorithm);
      }
      _this.verify(payload, verified);
    } catch (ex) {
      _this.fail(ex, next);
    }
  }
}

exports.authenticate = authenticate;
<commit_msg>Apply fix<commit_after>var xtend = require('xtend');
var jwt = require('jwt-simple');

var defaultOptions = {
  algorithm: 'HS256',
  succeedWithoutToken: false
};

function authenticate(options, verify) {
  var _this = this;
  this.options = xtend(defaultOptions, options);
  if (!this.options.secret) {
    throw new TypeError('SocketioJwtAuth requires a secret');
  }

  this.verify = verify;
  if (!this.verify) {
    throw new TypeError('SocketioJwtAuth requires a verify callback');
  }

  this.success = function(next) {
    next();
  }

  this.fail = function(err, next) {
    next(new Error(err));
  }

  return function(socket, next) {
    var token = socket.handshake.query.auth_token;
    var verified = function(err, user, message) {
      if (err) {
        return _this.fail(err, next);
      } else if (!user) {
        if (!_this.options.succeedWithoutToken) return _this.fail(message, next);
        socket.request.user = {logged_in: false};
        return _this.success(next)
      } else {
        user.logged_in = true;
        socket.request.user = user;
        return _this.success(next);
      }
    };
    try {
      var payload = {};
      if (!token) {
        if (!_this.options.succeedWithoutToken) {
          return _this.fail('No auth token', next);
        }
      } else {
        payload = jwt.decode(token, _this.options.secret, false, _this.options.algorithm);
      }
      _this.verify(payload, verified);
    } catch (ex) {
      _this.fail(ex, next);
    }
  }
}

exports.authenticate = authenticate;
<|endoftext|>


<commit_before>/**
 * Phonegap DatePicker Plugin Copyright (c) Greg Allen 2011 MIT Licensed
 * Reused and ported to Android plugin by Daniel van 't Oever
 */

/**
 * Constructor
 */
function DatePicker() {
  //this._callback;
}

/**
 * show - true to show the ad, false to hide the ad
 */
DatePicker.prototype.show = function(options, cb) {

	if (options.date) {
		options.date = (options.date.getMonth() + 1) + "/" +
					   (options.date.getDate()) + "/" +
					   (options.date.getFullYear()) + "/" +
					   (options.date.getHours()) + "/" +
					   (options.date.getMinutes());
	}

	var defaults = {
		mode : 'date',
		date : '',
		minDate: 0,
		maxDate: 0
	};

	for (var key in defaults) {
		if (typeof options[key] !== "undefined") {
			defaults[key] = options[key];
		}
	}

	//this._callback = cb;

	var callback = function(message) {
		var timestamp = Date.parse(message);
		if(isNaN(timestamp) == false) {
			cb(new Date(message));
		}
	}

	cordova.exec(callback,
		null,
		"DatePickerPlugin",
		defaults.mode,
		[defaults]
	);
};

var datePicker = new DatePicker();
module.exports = datePicker;

// Make plugin work under window.plugins
if (!window.plugins) {
    window.plugins = {};
}
if (!window.plugins.datePicker) {
    window.plugins.datePicker = datePicker;
}<commit_msg>Fixed issue on Android where the cancel button did not trigger the callback<commit_after>/**
 * Phonegap DatePicker Plugin Copyright (c) Greg Allen 2011 MIT Licensed
 * Reused and ported to Android plugin by Daniel van 't Oever
 */

/**
 * Constructor
 */
function DatePicker() {
  //this._callback;
}

/**
 * show - true to show the ad, false to hide the ad
 */
DatePicker.prototype.show = function(options, cb) {

	if (options.date) {
		options.date = (options.date.getMonth() + 1) + "/" +
					   (options.date.getDate()) + "/" +
					   (options.date.getFullYear()) + "/" +
					   (options.date.getHours()) + "/" +
					   (options.date.getMinutes());
	}

	var defaults = {
		mode : 'date',
		date : '',
		minDate: 0,
		maxDate: 0
	};

	for (var key in defaults) {
		if (typeof options[key] !== "undefined") {
			defaults[key] = options[key];
		}
	}

	//this._callback = cb;

	var callback = function(message) {
		var timestamp = Date.parse(message);
		if(isNaN(timestamp) == false) {
			cb(new Date(message));
		}
        else {
            cb();
        }
	}

	cordova.exec(callback,
		null,
		"DatePickerPlugin",
		defaults.mode,
		[defaults]
	);
};

var datePicker = new DatePicker();
module.exports = datePicker;

// Make plugin work under window.plugins
if (!window.plugins) {
    window.plugins = {};
}
if (!window.plugins.datePicker) {
    window.plugins.datePicker = datePicker;
}
<|endoftext|>


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

if (typeof String.prototype.startsWith != 'function') {
    String.prototype.startsWith = function (str){
        return this.indexOf(str) === 0;
    };
}

exports.match = function(text) {
    return text.startsWith('/fawlty');
};

exports.help = function() {
    return '/fawlty : Fixes fawlty code. Probably.';
};

var quotes = [
    'Sybil Fawlty: [on the phone] I know... I know... I know... Oh, I know!\nBasil Fawlty: Then why is she telling you?',
    'Basil Fawlty: [about Sybil\'s laugh] Sounds like somebody machine-gunning a seal.',
    'Basil Fawlty: Next contestant, Mrs. Sybil Fawlty from Torquay. Specialist subject - the bleeding obvious.',
    'Basil Fawlty: Right, well I\'ll go and have a lie down then. No I won\'t; I\'ll go and hit some guests.',
    'Basil Fawlty: Manuel will show you to your rooms - if you\'re lucky.',
    'Basil Fawlty: Coming my little piranha fish.',
    'Basil Fawlty: You\'ll have to forgive him. He\'s from Barcelona.',
    'Basil Fawlty: Don\'t be alarmed, it\'s only my wife laughing.',
    'Basil Fawlty: Do you remember when we were first *manacled* together? We used to laugh quite a lot.\nSybil Fawlty: Yes, but not at the same time, Basil.',
    'Basil Fawlty: We have a Spanish porter at the moment, he\'s from Barcelona. It\'d be quicker to train an *ape*!',
    'Basil Fawlty: [to Manuel] Stupidissimo! Continental cretin!',
    'Miss Gatsby: And don\'t do anything *we* wouldn\'t do!\nBasil Fawlty: Oh, just a little breathing, surely.',
    'Basil Fawlty: [to Sybil, while having dinner] Why don\'t you have another vat of wine, dear?',
    'Basil Fawlty: Oh look at that, a satisfied customer. We should have him stuffed.'
    ];

exports.run = function(api, event) {
    var query = event.body.substr(6);

    var index = Math.floor(Math.random() * quotes.length),
    result = quotes[index];

    api.sendMessage(result, event.thread_id);
};

exports.load = function() {};<commit_msg>Cleans up some Fawlty code.<commit_after>var request = require('request');

if (typeof String.prototype.startsWith != 'function') {
    String.prototype.startsWith = function (str){
        return this.indexOf(str) === 0;
    };
}

exports.match = function(text) {
    return text.startsWith('/fawlty');
};

exports.help = function() {
    return '/fawlty : Fixes fawlty code. Probably.';
};

var quotes = [
    'Sybil Fawlty: [on the phone] I know... I know... I know... Oh, I know!\nBasil Fawlty: Then why is she telling you?',
    'Basil Fawlty: [about Sybil\'s laugh] Sounds like somebody machine-gunning a seal.',
    'Basil Fawlty: Next contestant, Mrs. Sybil Fawlty from Torquay. Specialist subject - the bleeding obvious.',
    'Basil Fawlty: Right, well I\'ll go and have a lie down then. No I won\'t; I\'ll go and hit some guests.',
    'Basil Fawlty: Manuel will show you to your rooms - if you\'re lucky.',
    'Basil Fawlty: Coming my little piranha fish.',
    'Basil Fawlty: You\'ll have to forgive him. He\'s from Barcelona.',
    'Basil Fawlty: Don\'t be alarmed, it\'s only my wife laughing.',
    'Basil Fawlty: Do you remember when we were first *manacled* together? We used to laugh quite a lot.\nSybil Fawlty: Yes, but not at the same time, Basil.',
    'Basil Fawlty: We have a Spanish porter at the moment, he\'s from Barcelona. It\'d be quicker to train an *ape*!',
    'Basil Fawlty: [to Manuel] Stupidissimo! Continental cretin!',
    'Miss Gatsby: And don\'t do anything *we* wouldn\'t do!\nBasil Fawlty: Oh, just a little breathing, surely.',
    'Basil Fawlty: [to Sybil, while having dinner] Why don\'t you have another vat of wine, dear?',
    'Basil Fawlty: Oh look at that, a satisfied customer. We should have him stuffed.'
    ];

exports.run = function(api, event) {
    var index = Math.floor(Math.random() * quotes.length),
    result = quotes[index];

    api.sendMessage(result, event.thread_id);
};

exports.load = function() {};<|endoftext|>


<commit_before>/**
 * @name      ElkArte Forum
 * @copyright ElkArte Forum contributors
 * @license   BSD http://opensource.org/licenses/BSD-3-Clause
 *
 * This software is a derived product, based on:
 *
 * Simple Machines Forum (SMF)
 * copyright:	2011 Simple Machines (http://www.simplemachines.org)
 * license:  	BSD, See included LICENSE.TXT for terms and conditions.
 *
 * @version 1.0 Beta
 *
 * This file contains javascript associated with the spellchecking ((pspell)
 */

// These are variables the popup is going to want to access...
var spell_formname, spell_fieldname, spell_full;

// Spell check the specified field in the specified form.
function spellCheck(formName, fieldName, bFull)
{
	// Grab the (hidden) spell checking form.
	var spellform = document.forms.spell_form;

	// Register the name of the editing form for future reference.
	spell_formname = formName;
	spell_fieldname = fieldName;
	spell_full = bFull || true;

	// This should match a word (most of the time).
	var regexpWordMatch = /(?:<[^>]+>)|(?:\[[^ ][^\]]*\])|(?:&[^; ]+;)|(?:[^0-9\s\]\[{};:"\\|,<.>\/?`~!@#$%^&*()_+=]+)/g;

	// These characters can appear within words.
	var aWordCharacters = ['-', '\''];

	var aWords = new Array(), aResult = new Array();
	var sText = (spell_full) ? $('#' + fieldName).data("sceditor").getText() : document.forms[formName][fieldName].value;
	var bInCode = false;
	var iOffset1, iOffset2;

	// Loop through all words.
	while ((aResult = regexpWordMatch.exec(sText)) && typeof(aResult) != 'undefined')
	{
		iOffset1 = 0;
		iOffset2 = aResult[0].length - 1;

		// Strip the dashes and hyphens from the begin of the word.
		while (in_array(aResult[0].charAt(iOffset1), aWordCharacters) && iOffset1 < iOffset2)
			iOffset1++;

		// Strip the dashes and hyphens from the end of the word.
		while (in_array(aResult[0].charAt(iOffset2), aWordCharacters) && iOffset1 < iOffset2)
			iOffset2--;

		// I guess there's only dashes and hyphens in this word...
		if (iOffset1 == iOffset2)
			continue;

		// Ignore code blocks.
		if (aResult[0].substr(0, 5).toLowerCase() == '[code')
			bInCode = true;

		// Glad we're out of that code block!
		else if (bInCode && aResult[0].substr(0, 7).toLowerCase() == '[/code]')
			bInCode = false;

		// Now let's get to business.
		else if (!bInCode && !in_array(aResult[0].charAt(0), ['[', '<']) && aResult[0].toUpperCase() != aResult[0])
			aWords[aWords.length] = aResult[0].substr(iOffset1, iOffset2 - iOffset1 + 1) + '|' + (iOffset1 + sText.substr(0, aResult.index).length) + '|' + (iOffset2 + sText.substr(0, aResult.index).length);
	}

	// Open the window...
	openSpellWin(640, 480);

	// Pass the data to a form...
	spellform.spellstring.value = aWords.join('\n');
	spellform.fulleditor.value = spell_full ? 'true' : 'false';

	//  and go!
	spellform.submit();

	return true;
}

// Private functions -------------------------------

// Globals...
var wordindex = -1, offsetindex = 0;
var ignoredWords = [];

// A "misspelled word" object.
function misp(word, start, end, suggestions)
{
	// The word, start index, end index, and array of suggestions.
	this.word = word;
	this.start = start;
	this.end = end;
	this.suggestions = suggestions;
}

// Replace the word in the misps array at the "wordindex" index.  The
// misps array is generated by a PHP script after the string to be spell
// checked is evaluated with pspell.
function replaceWord()
{
	var strstart = "";
	var strend;

	// If this isn't the beginning of the string then get all of the string
	// that is before the word we are replacing.
	if (misps[wordindex].start != 0)
		strstart = mispstr.slice(0, misps[wordindex].start + offsetindex);

	// Get the end of the string after the word we are replacing.
	strend = mispstr.slice(misps[wordindex].end + 1 + offsetindex);

	// Rebuild the string with the new word.
	mispstr = strstart + document.forms.spellingForm.changeto.value + strend;

	// Update offsetindex to compensate for replacing a word with a word
	// of a different length.
	offsetindex += document.forms.spellingForm.changeto.value.length - misps[wordindex].word.length;

	// Update the word so future replaceAll calls don't change it.
	misps[wordindex].word = document.forms.spellingForm.changeto.value;

	nextWord(false);
}

// Replaces all instances of currently selected word with contents chosen by user.
// Note: currently only replaces words after highlighted word.  I think we can re-index
// all words at replacement or ignore time to have it wrap to the beginning if we want
// to.
function replaceAll()
{
	var strend;
	var idx;
	var origword;
	var localoffsetindex = offsetindex;

	origword = misps[wordindex].word;

	// Re-index everything past the current word.
	for (idx = wordindex; idx < misps.length; idx++)
	{
		misps[idx].start += localoffsetindex;
		misps[idx].end += localoffsetindex;
	}

	localoffsetindex = 0;

	for (idx = 0; idx < misps.length; idx++)
	{
		if (misps[idx].word == origword)
		{
			var strstart = "";
			if (misps[idx].start != 0)
				strstart = mispstr.slice(0, misps[idx].start + localoffsetindex);

			// Get the end of the string after the word we are replacing.
			strend = mispstr.slice(misps[idx].end + 1 + localoffsetindex);

			// Rebuild the string with the new word.
			mispstr = strstart + document.forms.spellingForm.changeto.value + strend;

			// Update offsetindex to compensate for replacing a word with a word
			// of a different length.
			localoffsetindex += document.forms.spellingForm.changeto.value.length - misps[idx].word.length;
		}

		// We have to re-index everything after replacements.
		misps[idx].start += localoffsetindex;
		misps[idx].end += localoffsetindex;
	}

	// Add the word to the ignore array.
	ignoredWords[origword] = true;

	// Reset offsetindex since we re-indexed.
	offsetindex = 0;

	nextWord(false);
}

// Highlight the word that was selected using the nextWord function.
function highlightWord()
{
	var strstart = "";
	var strend;

	// If this isn't the beginning of the string then get all of the string
	// that is before the word we are replacing.
	if (misps[wordindex].start != 0)
		strstart = mispstr.slice(0, misps[wordindex].start + offsetindex);

	// Get the end of the string after the word we are replacing.
	strend = mispstr.slice(misps[wordindex].end + 1 + offsetindex);

	// Rebuild the string with a span wrapped around the misspelled word
	// so we can highlight it in the div the user is viewing the string in.
	var divptr, newValue;
	divptr = document.getElementById("spellview");

	newValue = htmlspecialchars(strstart) + '' + misps[wordindex].word + '' + htmlspecialchars(strend);
	setInnerHTML(divptr, newValue.replace(/_\|_/g, '
'));

	// We could use scrollIntoView, but it's just not that great anyway.
	var spellview_height = typeof(document.getElementById("spellview").currentStyle) != "undefined" ? parseInt(document.getElementById("spellview").currentStyle.height) : document.getElementById("spellview").offsetHeight;
	var word_position = document.getElementById("h1").offsetTop;
	var current_position = document.getElementById("spellview").scrollTop;

	// The spellview is not tall enough!  Scroll down!
	if (spellview_height <= (word_position + current_position))
		document.getElementById("spellview").scrollTop = word_position + current_position - spellview_height + 32;
}

// Display the next misspelled word to the user and populate the suggested spellings box.
function nextWord(ignoreall)
{
	// Push ignored word onto ignoredWords array.
	if (ignoreall)
		ignoredWords[misps[wordindex].word] = true;

	// Update the index of all words we have processed...
	// This must be done to accomodate the replaceAll function.
	if (wordindex >= 0)
	{
		misps[wordindex].start += offsetindex;
		misps[wordindex].end += offsetindex;
	}

	// Increment the counter for the array of misspelled words.
	wordindex++;

	// Draw it and quit if there are no more misspelled words to evaluate.
	if (misps.length <= wordindex)
	{
		var divptr;
		divptr = document.getElementById("spellview");
		setInnerHTML(divptr, htmlspecialchars(mispstr).replace(/_\|_/g, "
"));

		while (document.forms.spellingForm.suggestions.options.length > 0)
			document.forms.spellingForm.suggestions.options[0] = null;

		alert(txt['done']);
		document.forms.spellingForm.change.disabled = true;
		document.forms.spellingForm.changeall.disabled = true;
		document.forms.spellingForm.ignore.disabled = true;
		document.forms.spellingForm.ignoreall.disabled = true;

		// Put line feeds back...
		mispstr = mispstr.replace(/_\|_/g, "\n");

		// Get a handle to the field we need to re-populate.
		if (spell_full)
			window.opener.spellCheckSetText(mispstr, spell_fieldname);
		else
		{
			window.opener.document.forms[spell_formname][spell_fieldname].value = mispstr;
			if (!window.opener.spellCheckDone)
				window.opener.document.forms[spell_formname][spell_fieldname].focus();
			else
				window.opener.spellCheckDone();
		}

		window.close();
		return true;
	}

	// Check to see if word is supposed to be ignored.
	if (typeof(ignoredWords[misps[wordindex].word]) != "undefined")
	{
		nextWord(false);
		return false;
	}

	// Clear out the suggestions box!
	while (document.forms.spellingForm.suggestions.options.length > 0)
		document.forms.spellingForm.suggestions.options[0] = null;

	// Re-populate the suggestions box if there are any suggested spellings for the word.
	if (misps[wordindex].suggestions.length)
	{
		for (var sugidx = 0; sugidx < misps[wordindex].suggestions.length; sugidx++)
		{
			var newopt = new Option(misps[wordindex].suggestions[sugidx], misps[wordindex].suggestions[sugidx]);
			document.forms.spellingForm.suggestions.options[sugidx] = newopt;

			if (sugidx == 0)
			{
				newopt.selected = true;
				document.forms.spellingForm.changeto.value = newopt.value;
				document.forms.spellingForm.changeto.select();
			}
		}
	}

	if (document.forms.spellingForm.suggestions.options.length == 0)
		document.forms.spellingForm.changeto.value = "";

	highlightWord();

	return false;
}

// convert characters to HTML equivalents
function htmlspecialchars(thetext)
{
	thetext = thetext.replace(/\</g, "<");
	thetext = thetext.replace(/\>/g, ">");
	thetext = thetext.replace(/\n/g, "
");
	thetext = thetext.replace(/\ \ /g, "  ");

	return thetext;
}

// Open a new window
function openSpellWin(width, height)
{
	window.open("", "spellWindow", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=" + width + ",height=" + height);
}

// get the sceditor text
function spellCheckGetText(editorID)
{
	return $("#" + editorID).data("sceditor").getText();
}

// set the sceditor text
function spellCheckSetText(text, editorID)
{
	$("#" + editorID).data("sceditor").InsertText(text, true);
	if (!$("#" + editorID).data("sceditor").inSourceMode)
		$("#" + editorID).data("sceditor").toggleSourceMode();
}<commit_msg>! a little cleaning and docblock for the much maligned spellcheck.js<commit_after>/**
 * @name      ElkArte Forum
 * @copyright ElkArte Forum contributors
 * @license   BSD http://opensource.org/licenses/BSD-3-Clause
 *
 * This software is a derived product, based on:
 *
 * Simple Machines Forum (SMF)
 * copyright:	2011 Simple Machines (http://www.simplemachines.org)
 * license:		BSD, See included LICENSE.TXT for terms and conditions.
 *
 * @version 1.0 Beta
 *
 * This file contains javascript associated with the spellchecking ((pspell)
 */

// These are variables the popup is going to want to access...
var spell_formname,
	spell_fieldname,
	spell_full;

/**
 * Spell check the specified field in the specified form.
 *
 * @param {string} formName
 * @param {string} fieldName
 * @param {boolean} bFull
 */
function spellCheck(formName, fieldName, bFull)
{
	// Grab the (hidden) spell checking form.
	var spellform = document.forms.spell_form;

	// Register the name of the editing form for future reference.
	spell_formname = formName;
	spell_fieldname = fieldName;
	spell_full = bFull || true;

	// This should match a word (most of the time).
	var regexpWordMatch = /(?:<[^>]+>)|(?:\[[^ ][^\]]*\])|(?:&[^; ]+;)|(?:[^0-9\s\]\[{};:"\\|,<.>\/?`~!@#$%^&*()_+=]+)/g;

	// These characters can appear within words.
	var aWordCharacters = ['-', '\''];

	var aWords = [],
		aResult = [],
		sText = (spell_full) ? $('#' + fieldName).data("sceditor").getText() : document.forms[formName][fieldName].value,
		bInCode = false,
		iOffset1,
		iOffset2;

	// Loop through all words.
	while ((aResult = regexpWordMatch.exec(sText)) && typeof (aResult) !== 'undefined')
	{
		iOffset1 = 0;
		iOffset2 = aResult[0].length - 1;

		// Strip the dashes and hyphens from the begin of the word.
		while (in_array(aResult[0].charAt(iOffset1), aWordCharacters) && iOffset1 < iOffset2)
			iOffset1++;

		// Strip the dashes and hyphens from the end of the word.
		while (in_array(aResult[0].charAt(iOffset2), aWordCharacters) && iOffset1 < iOffset2)
			iOffset2--;

		// I guess there's only dashes and hyphens in this word...
		if (iOffset1 == iOffset2)
			continue;

		// Ignore code blocks.
		if (aResult[0].substr(0, 5).toLowerCase() === '[code')
			bInCode = true;

		// Glad we're out of that code block!
		else if (bInCode && aResult[0].substr(0, 7).toLowerCase() === '[/code]')
			bInCode = false;

		// Now let's get to business.
		else if (!bInCode && !in_array(aResult[0].charAt(0), ['[', '<']) && aResult[0].toUpperCase() !== aResult[0])
			aWords[aWords.length] = aResult[0].substr(iOffset1, iOffset2 - iOffset1 + 1) + '|' + (iOffset1 + sText.substr(0, aResult.index).length) + '|' + (iOffset2 + sText.substr(0, aResult.index).length);
	}

	// Open the window...
	openSpellWin(640, 480);

	// Pass the data to a form...
	spellform.spellstring.value = aWords.join('\n');
	spellform.fulleditor.value = spell_full ? 'true' : 'false';

	//  and go!
	spellform.submit();

	return true;
}

// Private functions -------------------------------

// Globals...
var wordindex = -1,
	offsetindex = 0,
	ignoredWords = [];

/**
 * A "misspelled word" object.
 *
 * @param {string} word
 * @param {type} start
 * @param {type} end
 * @param {type} suggestions
 */
function misp(word, start, end, suggestions)
{
	// The word, start index, end index, and array of suggestions.
	this.word = word;
	this.start = start;
	this.end = end;
	this.suggestions = suggestions;
}

/**
 * Replace the word in the misps array at the "wordindex" index.  The
 * misps array is generated by a PHP script after the string to be spell
 * checked is evaluated with pspell.
 */
function replaceWord()
{
	var strstart = "",
		strend;

	// If this isn't the beginning of the string then get all of the string
	// that is before the word we are replacing.
	if (misps[wordindex].start !== 0)
		strstart = mispstr.slice(0, misps[wordindex].start + offsetindex);

	// Get the end of the string after the word we are replacing.
	strend = mispstr.slice(misps[wordindex].end + 1 + offsetindex);

	// Rebuild the string with the new word.
	mispstr = strstart + document.forms.spellingForm.changeto.value + strend;

	// Update offsetindex to compensate for replacing a word with a word
	// of a different length.
	offsetindex += document.forms.spellingForm.changeto.value.length - misps[wordindex].word.length;

	// Update the word so future replaceAll calls don't change it.
	misps[wordindex].word = document.forms.spellingForm.changeto.value;

	nextWord(false);
}

/**
 * Replaces all instances of currently selected word with contents chosen by user.
 * Note: currently only replaces words after highlighted word.  I think we can re-index
 * all words at replacement or ignore time to have it wrap to the beginning if we want to.
 */
function replaceAll()
{
	var strend,
		idx,
		origword,
		localoffsetindex = offsetindex;

	origword = misps[wordindex].word;

	// Re-index everything past the current word.
	for (idx = wordindex; idx < misps.length; idx++)
	{
		misps[idx].start += localoffsetindex;
		misps[idx].end += localoffsetindex;
	}

	localoffsetindex = 0;

	for (idx = 0; idx < misps.length; idx++)
	{
		if (misps[idx].word === origword)
		{
			var strstart = "";
			if (misps[idx].start !== 0)
				strstart = mispstr.slice(0, misps[idx].start + localoffsetindex);

			// Get the end of the string after the word we are replacing.
			strend = mispstr.slice(misps[idx].end + 1 + localoffsetindex);

			// Rebuild the string with the new word.
			mispstr = strstart + document.forms.spellingForm.changeto.value + strend;

			// Update offsetindex to compensate for replacing a word with a word
			// of a different length.
			localoffsetindex += document.forms.spellingForm.changeto.value.length - misps[idx].word.length;
		}

		// We have to re-index everything after replacements.
		misps[idx].start += localoffsetindex;
		misps[idx].end += localoffsetindex;
	}

	// Add the word to the ignore array.
	ignoredWords[origword] = true;

	// Reset offsetindex since we re-indexed.
	offsetindex = 0;

	nextWord(false);
}

/**
 * Highlight the word that was selected using the nextWord function.
 */
function highlightWord()
{
	var strstart = "",
		strend;

	// If this isn't the beginning of the string then get all of the string
	// that is before the word we are replacing.
	if (misps[wordindex].start !== 0)
		strstart = mispstr.slice(0, misps[wordindex].start + offsetindex);

	// Get the end of the string after the word we are replacing.
	strend = mispstr.slice(misps[wordindex].end + 1 + offsetindex);

	// Rebuild the string with a span wrapped around the misspelled word
	// so we can highlight it in the div the user is viewing the string in.
	var divptr, newValue;
	divptr = document.getElementById("spellview");

	newValue = htmlspecialchars(strstart) + '' + misps[wordindex].word + '' + htmlspecialchars(strend);
	setInnerHTML(divptr, newValue.replace(/_\|_/g, '
'));

	// We could use scrollIntoView, but it's just not that great anyway.
	var spellview_height = typeof (document.getElementById("spellview").currentStyle) !== "undefined" ? parseInt(document.getElementById("spellview").currentStyle.height) : document.getElementById("spellview").offsetHeight,
		word_position = document.getElementById("h1").offsetTop,
		current_position = document.getElementById("spellview").scrollTop;

	// The spellview is not tall enough!  Scroll down!
	if (spellview_height <= (word_position + current_position))
		document.getElementById("spellview").scrollTop = word_position + current_position - spellview_height + 32;
}

/**
 * Display the next misspelled word to the user and populate the suggested spellings box.
 *
 * @param {string} ignoreall
 */
function nextWord(ignoreall)
{
	// Push ignored word onto ignoredWords array.
	if (ignoreall)
		ignoredWords[misps[wordindex].word] = true;

	// Update the index of all words we have processed...
	// This must be done to accomodate the replaceAll function.
	if (wordindex >= 0)
	{
		misps[wordindex].start += offsetindex;
		misps[wordindex].end += offsetindex;
	}

	// Increment the counter for the array of misspelled words.
	wordindex++;

	// Draw it and quit if there are no more misspelled words to evaluate.
	if (misps.length <= wordindex)
	{
		var divptr;
		divptr = document.getElementById("spellview");
		setInnerHTML(divptr, htmlspecialchars(mispstr).replace(/_\|_/g, "
"));

		while (document.forms.spellingForm.suggestions.options.length > 0)
			document.forms.spellingForm.suggestions.options[0] = null;

		alert(txt['done']);
		document.forms.spellingForm.change.disabled = true;
		document.forms.spellingForm.changeall.disabled = true;
		document.forms.spellingForm.ignore.disabled = true;
		document.forms.spellingForm.ignoreall.disabled = true;

		// Put line feeds back...
		mispstr = mispstr.replace(/_\|_/g, "\n");

		// Get a handle to the field we need to re-populate.
		if (spell_full)
			window.opener.spellCheckSetText(mispstr, spell_fieldname);
		else
		{
			window.opener.document.forms[spell_formname][spell_fieldname].value = mispstr;
			if (!window.opener.spellCheckDone)
				window.opener.document.forms[spell_formname][spell_fieldname].focus();
			else
				window.opener.spellCheckDone();
		}

		window.close();
		return true;
	}

	// Check to see if word is supposed to be ignored.
	if (typeof (ignoredWords[misps[wordindex].word]) !== "undefined")
	{
		nextWord(false);
		return false;
	}

	// Clear out the suggestions box!
	while (document.forms.spellingForm.suggestions.options.length > 0)
		document.forms.spellingForm.suggestions.options[0] = null;

	// Re-populate the suggestions box if there are any suggested spellings for the word.
	if (misps[wordindex].suggestions.length)
	{
		for (var sugidx = 0; sugidx < misps[wordindex].suggestions.length; sugidx++)
		{
			var newopt = new Option(misps[wordindex].suggestions[sugidx], misps[wordindex].suggestions[sugidx]);
			document.forms.spellingForm.suggestions.options[sugidx] = newopt;

			if (sugidx === 0)
			{
				newopt.selected = true;
				document.forms.spellingForm.changeto.value = newopt.value;
				document.forms.spellingForm.changeto.select();
			}
		}
	}

	if (document.forms.spellingForm.suggestions.options.length === 0)
		document.forms.spellingForm.changeto.value = "";

	highlightWord();

	return false;
}

/**
 * convert characters to HTML equivalents
 *
 * @param {string} thetext
 */
function htmlspecialchars(thetext)
{
	thetext = thetext.replace(/</g, "<");
	thetext = thetext.replace(/\>/g, ">");
	thetext = thetext.replace(/\n/g, "
");
	thetext = thetext.replace(/\ \ /g, "  ");

	return thetext;
}

/**
 * Open a new window
 *
 * @param {int} width
 * @param {int} height
 */
function openSpellWin(width, height)
{
	window.open("", "spellWindow", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=" + width + ",height=" + height);
}

/**
 * get the sceditor text
 *
 * @param {string} editorID
 */
function spellCheckGetText(editorID)
{
	return $("#" + editorID).data("sceditor").getText();
}

/**
 * set the sceditor text
 *
 * @param {string} text
 * @param {string} editorID
 */
function spellCheckSetText(text, editorID)
{
	$("#" + editorID).data("sceditor").InsertText(text, true);

	if (!$("#" + editorID).data("sceditor").inSourceMode)
		$("#" + editorID).data("sceditor").toggleSourceMode();
}<|endoftext|>


<commit_before>var gulp         = require('gulp'),
    assign       = require('lodash.assign'),
    browserify   = require('browserify'),
    browserSync  = require('browser-sync').create(),
    bower        = require('gulp-bower'),
    buffer       = require('vinyl-buffer'),
    childProcess = require('child_process'),
    del          = require('del'),
    gUtil        = require('gulp-util'),
    minifyCss    = require('gulp-minify-css'),
    nodemon      = require('gulp-nodemon'),
    notify       = require('gulp-notify'),
    rename       = require('gulp-rename'),
    reload       = browserSync.reload,
    sass         = require('gulp-sass'),
    source       = require('vinyl-source-stream'),
    sourcemaps   = require('gulp-sourcemaps'),
    uglify       = require('gulp-uglify'),
    watchify     = require('watchify');

var config = {
  sassPath        : './dev/sass',
  jsPath          : './dev/js',
  ngViewPath      : './dev/js/app/**/views',
  fontPath        : './assets/fonts',
  imgPath         : './assets/images',
  controllersPath : './app/controllers',
  modelsPath      : './app/models',
  routesPath      : './app/routes',
  viewsPath       : './app/views'
};

/* Clean Public Folder */
gulp.task('clean', function(){
  return del([
    './public/',
    '!./public/assets/fonts/**/*'
  ]);
});

/* Bower */
gulp.task('bower', function(){
  return bower();
});

/* Scripts */
gulp.task('scripts', ['clean'], function(){
  gulp.src(config.jsPath+'main.js')
    .pipe(sourcemaps.init())
      .pipe(uglify())
      .pipe(rename('main.min.js'))
    .pipe(sourcemaps.write('../../../maps/js'))
    .pipe(gulp.dest('./public/assets/js'));
});

gulp.task('script-watch', ['scripts'], reload);

gulp.task('ng-scripts', ['clean'], function(){
  gulp.src(config.jsPath+'/app/**/**/*.js')
  .pipe(sourcemaps.init())
  .pipe(sourcemaps.write('../../../../maps/js/angularApp'))
  .pipe(gulp.dest('./public/assets/js/app'));
});

gulp.task('ng-script-watch', ['ng-scripts'], reload);

gulp.task('ng-html', ['clean'], function(){
  gulp.src(config.ngViewPath+'/*.html')
  .pipe(gulp.dest('./public/assets/js/app/'));
});

gulp.task('ng-html-watch', ['ng-html'], reload);

/* Nodemon */
var BROWSER_SYNC_RELOAD_DELAY = 500;

gulp.task('nodemon', function (cb) {
  var called = false;
  return nodemon({

    // nodemon our expressjs server
    script: 'app.js',

    // watch core server file(s) that require server restart on change
    watch: ['app.js']
  })
    .on('start', function onStart() {
      // ensure start only got called once
      if (!called) { cb(); }
      called = true;
    })
    .on('restart', function onRestart() {
      // reload connected browsers after a slight delay
      setTimeout(function reload() {
        reload({
          stream: false   //
        });
      }, BROWSER_SYNC_RELOAD_DELAY);
    });
});

/* Startup the app server */
gulp.task('mongod', function(){
  childProcess.exec('mongod', function(err,stdout){
    console.log(stdout);
  });
});

/* Styles */
gulp.task('styles', function(){
  gulp.src(config.sassPath+'/main.scss')
  .pipe(sourcemaps.init())
    .pipe(sass())
    .pipe(minifyCss())
    .pipe(rename('main.min.css'))
  .pipe(sourcemaps.write('../../../maps/css'))
  .pipe(gulp.dest('./public/assets/css'))
  .pipe(browserSync.stream())
  .pipe(notify('Wubalubadubdub! Styles Done!'));
});

/* Styles task without browser-sync */
gulp.task('styles-no-bs', ['clean'], function(){
  gulp.src(config.sassPath+'/main.scss')
  .pipe(sourcemaps.init())
    .pipe(sass())
    .pipe(minifyCss())
    .pipe(rename('main.min.css'))
  .pipe(sourcemaps.write('../../../maps/css'))
  .pipe(gulp.dest('./public/assets/css'));
});

/* Images */
gulp.task('images', ['clean'], function(){
  gulp.src(config.imgPath+'/**/*.*')
  .pipe(gulp.dest('./public/assets/images'));
});

gulp.task('image-watch', ['images'], reload);

/* Fonts */
gulp.task('fonts', ['clean'], function(){
  gulp.src(config.fontPath+'/*/*')
  .pipe(gulp.dest('./public/assets/fonts'));
});

/* Browser Sync */
gulp.task('browser-sync', ['nodemon'], function(){
  browserSync.init({
    files   : ['./public/**/*.*'],
    proxy   : 'http://localhost:3000',
    port    : 4000,
    browser : ['google-chrome'],
    open    : false
  });

  gulp.watch(config.sassPath+'/**/**/*.scss',['styles']);
  gulp.watch(config.jsPath+'/*.js',['script-watch']);
  gulp.watch(config.jsPath+'/app/**/**/*.js', ['ng-script-watch']);
  gulp.watch(config.ngViewPath+'/*.html',['ng-html-watch']);
  gulp.watch(config.imgPath+'/*.*',['image-watch']);
  gulp.watch('./app/*/*',reload);
  gulp.watch('./app.js',reload);
  gulp.watch('./public/*',reload);
});

//Build Task
gulp.task('build',['images','fonts','ng-html','styles-no-bs','scripts','ng-scripts']);

//Default Task
//Cleans public folder
//Rebuilds public folder
//Starts mongod
//Runs browser-sync
gulp.task('default', ['browser-sync']);
<commit_msg>updated gulp file<commit_after>var gulp         = require('gulp'),
    assign       = require('lodash.assign'),
    browserify   = require('browserify'),
    browserSync  = require('browser-sync').create(),
    bower        = require('gulp-bower'),
    buffer       = require('vinyl-buffer'),
    childProcess = require('child_process'),
    del          = require('del'),
    gUtil        = require('gulp-util'),
    minifyCss    = require('gulp-minify-css'),
    nodemon      = require('gulp-nodemon'),
    notify       = require('gulp-notify'),
    rename       = require('gulp-rename'),
    reload       = browserSync.reload,
    sass         = require('gulp-sass'),
    source       = require('vinyl-source-stream'),
    sourcemaps   = require('gulp-sourcemaps'),
    uglify       = require('gulp-uglify'),
    watchify     = require('watchify');

var config = {
  sassPath        : './dev/sass',
  jsPath          : './dev/js',
  ngViewPath      : './dev/js/app/**/views',
  fontPath        : './assets/fonts',
  imgPath         : './assets/images',
  controllersPath : './app/controllers',
  modelsPath      : './app/models',
  routesPath      : './app/routes',
  viewsPath       : './app/views'
};

/* Clean Public Folder */
gulp.task('clean', function(){
  return del([
    './public/',
    '!./public/assets/fonts/**/*'
  ]);
});

/* Bower */
gulp.task('bower', function(){
  return bower();
});

/* Scripts */
gulp.task('scripts', ['clean'], function(){
  gulp.src(config.jsPath+'main.js')
    .pipe(sourcemaps.init())
      .pipe(uglify())
      .pipe(rename('main.min.js'))
    .pipe(sourcemaps.write('../../../maps/js'))
    .pipe(gulp.dest('./public/assets/js'));
});

gulp.task('script-watch', ['scripts'], reload);

gulp.task('ng-scripts', ['clean'], function(){
  gulp.src(config.jsPath+'/app/**/**/*.js')
  .pipe(sourcemaps.init())
  .pipe(sourcemaps.write('../../../../maps/js/angularApp'))
  .pipe(gulp.dest('./public/assets/js/app'));
});

gulp.task('ng-script-watch', ['ng-scripts'], reload);

gulp.task('ng-html', ['clean'], function(){
  gulp.src(config.ngViewPath+'/*.html')
  .pipe(gulp.dest('./public/assets/js/app/'));
});

gulp.task('ng-html-watch', ['ng-html'], reload);

/* Nodemon */
var BROWSER_SYNC_RELOAD_DELAY = 500;

gulp.task('nodemon', function (cb) {
  var called = false;
  return nodemon({

    // nodemon our expressjs server
    script: 'app.js',

    // watch core server file(s) that require server restart on change
    watch: ['app.js']
  })
    .on('start', function onStart() {
      // ensure start only got called once
      if (!called) { cb(); }
      called = true;
    })
    .on('restart', function onRestart() {
      // reload connected browsers after a slight delay
      setTimeout(function reload() {
        reload({
          stream: false   //
        });
      }, BROWSER_SYNC_RELOAD_DELAY);
    });
});

/* Startup the app server */
gulp.task('mongod', function(){
  childProcess.exec('mongod', function(err,stdout){
    console.log(stdout);
  });
});

/* Styles */
gulp.task('styles', function(){
  gulp.src(config.sassPath+'/main.scss')
  .pipe(sourcemaps.init())
    .pipe(sass())
    .pipe(minifyCss())
    .pipe(rename('main.min.css'))
  .pipe(sourcemaps.write('../../../maps/css'))
  .pipe(gulp.dest('./public/assets/css'))
  .pipe(browserSync.stream())
  .pipe(notify('Wubalubadubdub! Styles Done!'));
});

/* Styles task without browser-sync */
gulp.task('styles-no-bs', ['clean'], function(){
  gulp.src(config.sassPath+'/main.scss')
  .pipe(sourcemaps.init())
    .pipe(sass())
    .pipe(minifyCss())
    .pipe(rename('main.min.css'))
  .pipe(sourcemaps.write('../../../maps/css'))
  .pipe(gulp.dest('./public/assets/css'));
});

/* Images */
gulp.task('images', ['clean'], function(){
  gulp.src(config.imgPath+'/**/*.*')
  .pipe(gulp.dest('./public/assets/images'));
});

gulp.task('image-watch', ['images'], reload);

/* Fonts */
gulp.task('fonts', ['clean'], function(){
  gulp.src(config.fontPath+'/*/*')
  .pipe(gulp.dest('./public/assets/fonts'));
});

/* Browser Sync */
gulp.task('browser-sync', ['nodemon'], function(){
  browserSync.init({
    files   : ['./public/**/*.*'],
    proxy   : 'http://localhost:3000',
    port    : 4000,
    browser : ['google-chrome'],
    open    : false
  });

  gulp.watch(config.sassPath+'/**/**/*.scss',['styles']);
  gulp.watch(config.jsPath+'/*.js',['script-watch']);
  gulp.watch(config.jsPath+'/app/**/**/*.js', ['ng-script-watch']);
  gulp.watch(config.ngViewPath+'/*.html',['ng-html-watch']);
  gulp.watch(config.imgPath+'/*.*',['image-watch']);
  gulp.watch('./app/*/*',reload);
  gulp.watch('./app.js',reload);
  gulp.watch('./public/*',reload);
});

//Build Task
gulp.task('build',['images','ng-html','styles-no-bs','scripts','ng-scripts']);

//Default Task
//Cleans public folder
//Rebuilds public folder
//Starts mongod
//Runs browser-sync
gulp.task('default', ['browser-sync']);
<|endoftext|>


<commit_before>var NODE_ENV = process.env.NODE_ENV_APP || process.env.NODE_ENV || 'development',
  ENV_VAR_RE = /^\$ENV:(.+)/,
  globalService; // instantiated at the bottom

module.exports = PropertyService;

/**
 * Property Service
 *
 * The purpose of this service is to provide a place
 * to store environment-specific configuration.
 *
 * Usage:
 *     properties = propertyService.getProperties('my.namespace')
 *
 *     properties.setMany({
 *       serviceVersion: {
 *         'development,staging': '1.0.0',
 *         'production': '2.0.0',
 *         'production.dc1': '3.0.0',
 *         'production.*.az1': '4.0.0'
 *       }
 *     })
 *
 *     // NODE_ENV = 'staging'  or  NODE_ENV = 'development'
 *     properties.get('serviceVersion') // 1.0.0
 *
 *     // NODE_ENV = 'production.dc1'
 *     properties.get('serviceVersion') // 3.0.0
 *
 *     // NODE_ENV = 'production.dc2'
 *     properties.get('serviceVersion') // 2.0.0
 *
 *     // NODE_ENV = 'production.dc1.az1'
 *     properties.get('serviceVersion') // 4.0.0
 */

function PropertyService(environment) {
  if (!(this instanceof PropertyService)) {
    return new PropertyService(environment);
  }
  environment = environment || NODE_ENV;
  this._env2rank = this._calculateRanks(environment);
  this._coreKey2rank = {};
  this._cache = {};
}

PropertyService.$inject = [
  'internal.environment'
];

PropertyService.get = function (namespace) {
  return globalService.get(namespace);
};

PropertyService.create = function () {
  return globalService.create('');
};

PropertyService.prototype.get = function (namespace) {
  return this.getProperties(namespace, {scope: 'singleton'});
};

PropertyService.prototype.create = function (namespace) {
  return this.getProperties(namespace);
};

/**
 * @deprecated use PropertyService#get or PropertyService#create instead
 */

PropertyService.prototype.getProperties = function (namespace, options) {
  var cache, key2rank;
  options = options || {};
  switch (options.scope) {
    case 'singleton':
      key2rank = this._coreKey2rank;
      cache = this._cache;
      break;
    default:
      key2rank = {};
      cache = {};
      break;
  }
  return new Properties(this._env2rank, namespace, key2rank, cache);
};

function Properties(env2rank, namespace, key2rank, cache) {
  this._env2rank = env2rank;
  this.namespace = namespace;
  this._key2rank = key2rank;
  this._cache = cache;
}

/**
 * Set a property.
 *
 * @param {String} env environment
 * @param {String} key
 * @param {String|Number|Boolean|Object} value
 */

Properties.prototype.set = function (env, key, value) {
  var rank = this._env2rank[env.trim()],
    propKey, highest, match;

  // don't set any keys for other environments
  if ('undefined' === typeof rank) return;

  propKey = (this.namespace + ':' + key);
  highest = (this._key2rank[propKey] || -1);

  if (rank < highest) return;
  this._key2rank[propKey] = rank;

  // check if the value is an environment variable
  if ('string' === typeof value) {
    match = value.match(ENV_VAR_RE);
    value = match ? process.env[match[1]] : value;
  }

  // Override with propery in ENV if available. The env arg is meanless since
  // you only have one active env so why worry and set it for all values
  this._cache[propKey] = value;
};

/**
 * Set many properties at once.
 *
 * Example:
 *
 *     this.properties.setMany({
 *       transport: 'Console',
 *       filename: {
 *         'test,development,local': undefined,
 *         'fdev,sat,prod': '/var/log/tesla'
 *       },
 *       level: {
 *         'test': 'error',
 *         'development,local': undefined,
 *          fdev': 'warn',
 *          'sat,prod': 'error'
 *       }
 *     });
 *
 * @param {Object} properties
 */

Properties.prototype.setMany = function (properties) {
  var trimRegExp = this._trimRegExp,
    hasOwn = Object.hasOwnProperty;

  for (var name in properties) {
    if (!hasOwn.call(properties, name)) continue;
    var property = properties[name];

    if ('object' !== typeof property ||
      Array.isArray(property)) {
      this.set('all', name, property);
      continue;
    }

    for (var envNames in property) {
      if (!hasOwn.call(property, envNames)) continue;
      var value = property[envNames],
        envs = envNames.split(',');

      for (var i = 0, l = envs.length; i < l; i++) {
        this.set(envs[i], name, value);
      }
    }
  }
};

/**
 * Retrieve a property.
 *
 * @param {String} key
 * @param {String|Number|Boolean|Object} defaultValue (optional)
 */

Properties.prototype.get = function (key, defaultValue) {
  var propKey = (this.namespace + ':' + key),
    prop = this._cache[propKey];
  return ('undefined' !== typeof prop) ? prop :
    ('undefined' !== typeof defaultValue) ? defaultValue :
    null;
};

/**
 * Pre-calculate the environments to allow environment segments
 * and set-up rank to establish their precedence.
 */

PropertyService.prototype._calculateRanks = function (environment) {
  var env2rank = {},
    segments = environment.split('.'),
    weight = 1;

  function modify(key) {
    var r = env2rank[key];
    if (r > 0 && r < weight / 2) {
      var s = key;
      while (r < weight / 2) {
        s += '.*';
        r *= 2;
      }
      env2rank[s + '.' + segments[i]] = weight + r;
    } else {
      env2rank[key + '.' + segments[i]] = weight + r;
      env2rank[key + segments[i]] = weight + r;
    }
  }

  for (var i = 0, l = segments.length; i < l; i++) {
    Object.keys(env2rank).forEach(modify);

    if (i === 0) env2rank[segments[i]] = weight;
    weight *= 2; //higher than all previous combinations
  }

  env2rank.all = 0;
  return env2rank;
};

// creating a global service
globalService = new PropertyService();
<commit_msg>remove injection<commit_after>var NODE_ENV = process.env.NODE_ENV_APP || process.env.NODE_ENV || 'development',
  ENV_VAR_RE = /^\$ENV:(.+)/,
  globalService; // instantiated at the bottom

module.exports = PropertyService;

/**
 * Property Service
 *
 * The purpose of this service is to provide a place
 * to store environment-specific configuration.
 *
 * Usage:
 *     properties = propertyService.getProperties('my.namespace')
 *
 *     properties.setMany({
 *       serviceVersion: {
 *         'development,staging': '1.0.0',
 *         'production': '2.0.0',
 *         'production.dc1': '3.0.0',
 *         'production.*.az1': '4.0.0'
 *       }
 *     })
 *
 *     // NODE_ENV = 'staging'  or  NODE_ENV = 'development'
 *     properties.get('serviceVersion') // 1.0.0
 *
 *     // NODE_ENV = 'production.dc1'
 *     properties.get('serviceVersion') // 3.0.0
 *
 *     // NODE_ENV = 'production.dc2'
 *     properties.get('serviceVersion') // 2.0.0
 *
 *     // NODE_ENV = 'production.dc1.az1'
 *     properties.get('serviceVersion') // 4.0.0
 */

function PropertyService(environment) {
  if (!(this instanceof PropertyService)) {
    return new PropertyService(environment);
  }
  environment = environment || NODE_ENV;
  this._env2rank = this._calculateRanks(environment);
  this._coreKey2rank = {};
  this._cache = {};
}

PropertyService.get = function (namespace) {
  return globalService.get(namespace);
};

PropertyService.create = function () {
  return globalService.create('');
};

PropertyService.prototype.get = function (namespace) {
  return this.getProperties(namespace, {scope: 'singleton'});
};

PropertyService.prototype.create = function (namespace) {
  return this.getProperties(namespace);
};

/**
 * @deprecated use PropertyService#get or PropertyService#create instead
 */

PropertyService.prototype.getProperties = function (namespace, options) {
  var cache, key2rank;
  options = options || {};
  switch (options.scope) {
    case 'singleton':
      key2rank = this._coreKey2rank;
      cache = this._cache;
      break;
    default:
      key2rank = {};
      cache = {};
      break;
  }
  return new Properties(this._env2rank, namespace, key2rank, cache);
};

function Properties(env2rank, namespace, key2rank, cache) {
  this._env2rank = env2rank;
  this.namespace = namespace;
  this._key2rank = key2rank;
  this._cache = cache;
}

/**
 * Set a property.
 *
 * @param {String} env environment
 * @param {String} key
 * @param {String|Number|Boolean|Object} value
 */

Properties.prototype.set = function (env, key, value) {
  var rank = this._env2rank[env.trim()],
    propKey, highest, match;

  // don't set any keys for other environments
  if ('undefined' === typeof rank) return;

  propKey = (this.namespace + ':' + key);
  highest = (this._key2rank[propKey] || -1);

  if (rank < highest) return;
  this._key2rank[propKey] = rank;

  // check if the value is an environment variable
  if ('string' === typeof value) {
    match = value.match(ENV_VAR_RE);
    value = match ? process.env[match[1]] : value;
  }

  // Override with propery in ENV if available. The env arg is meanless since
  // you only have one active env so why worry and set it for all values
  this._cache[propKey] = value;
};

/**
 * Set many properties at once.
 *
 * Example:
 *
 *     this.properties.setMany({
 *       transport: 'Console',
 *       filename: {
 *         'test,development,local': undefined,
 *         'fdev,sat,prod': '/var/log/tesla'
 *       },
 *       level: {
 *         'test': 'error',
 *         'development,local': undefined,
 *          fdev': 'warn',
 *          'sat,prod': 'error'
 *       }
 *     });
 *
 * @param {Object} properties
 */

Properties.prototype.setMany = function (properties) {
  var trimRegExp = this._trimRegExp,
    hasOwn = Object.hasOwnProperty;

  for (var name in properties) {
    if (!hasOwn.call(properties, name)) continue;
    var property = properties[name];

    if ('object' !== typeof property ||
      Array.isArray(property)) {
      this.set('all', name, property);
      continue;
    }

    for (var envNames in property) {
      if (!hasOwn.call(property, envNames)) continue;
      var value = property[envNames],
        envs = envNames.split(',');

      for (var i = 0, l = envs.length; i < l; i++) {
        this.set(envs[i], name, value);
      }
    }
  }
};

/**
 * Retrieve a property.
 *
 * @param {String} key
 * @param {String|Number|Boolean|Object} defaultValue (optional)
 */

Properties.prototype.get = function (key, defaultValue) {
  var propKey = (this.namespace + ':' + key),
    prop = this._cache[propKey];
  return ('undefined' !== typeof prop) ? prop :
    ('undefined' !== typeof defaultValue) ? defaultValue :
    null;
};

/**
 * Pre-calculate the environments to allow environment segments
 * and set-up rank to establish their precedence.
 */

PropertyService.prototype._calculateRanks = function (environment) {
  var env2rank = {},
    segments = environment.split('.'),
    weight = 1;

  function modify(key) {
    var r = env2rank[key];
    if (r > 0 && r < weight / 2) {
      var s = key;
      while (r < weight / 2) {
        s += '.*';
        r *= 2;
      }
      env2rank[s + '.' + segments[i]] = weight + r;
    } else {
      env2rank[key + '.' + segments[i]] = weight + r;
      env2rank[key + segments[i]] = weight + r;
    }
  }

  for (var i = 0, l = segments.length; i < l; i++) {
    Object.keys(env2rank).forEach(modify);

    if (i === 0) env2rank[segments[i]] = weight;
    weight *= 2; //higher than all previous combinations
  }

  env2rank.all = 0;
  return env2rank;
};

// creating a global service
globalService = new PropertyService();
<|endoftext|>


<commit_before>var Hoek = require('hoek');
var Boom = require('boom');
var Joi = require('joi');
var Path = require('path');
var Schema = require('./schema');
var _ = require('lodash');
var utils = require('./utils');

var SWAGGER_VERSION = '1.2';
var defaultOptions = {
    endpoint: '/swagger'
};

module.exports.register = function (plugin, options, next) {
    var settings = Hoek.applyToDefaults(defaultOptions, options || {});
    settings.pluginRoutePrefix = (plugin.config.route.prefix || '');

    var internals = {
        apiDeclaration: require('./apiDeclaration')(settings),
        apiList: require('./apiListing')(settings)
    };

    var handler = {};

    handler.resourceListing = function (request, reply) {
        var apiRefs = internals.apiList(request.server.table(), request.query.tags);

        reply({
            swaggerVersion: SWAGGER_VERSION,
            apiVersion: settings.apiVersion,
            apis: apiRefs,
            info: settings.info,
            authorizations: settings.authorizations
        });
    };

    handler.apiDeclaration = function (request, reply) {
        var models = {};
        var apis = internals.apiDeclaration(request.server.table(), request.params.path, models);

        var apiDeclaration = {
            swaggerVersion: SWAGGER_VERSION,
            apiVersion: settings.apiVersion,
            basePath: utils.extractBaseHost(settings, request),
            resourcePath: '/' + request.params.path,
            produces: [ 'application/json' ],
            apis: apis,
            models: models
        };

        reply(apiDeclaration);
    };

    plugin.route({
        method: 'GET',
        path: options.endpoint,
        config: {
            tags: ['api', 'swagger'],
            auth: settings.auth,
            validate: {
                query: {
                    path: Joi.string().optional(),
                    tags: Joi.string().optional(),
                    api_key: Joi.string().optional()
                }
            },
            handler: handler.resourceListing,
            response: {
                schema: Schema.ResourceListing
            }
        }
    });

    plugin.route({
        method: 'GET',
        path: options.endpoint + '/{path}',
        config: {
            tags: ['api', 'swagger'],
            auth: settings.auth,
            validate: {
                params: {
                    path: Joi.string().required()
                },
                query: {
                    //tags: Joi.string().optional(),
                    //api_key: Joi.string().optional()
                }
            },
            handler: handler.apiDeclaration,
            response: {
                schema: Schema.APIDeclaration
            }
        }
    });

    next();
};

module.exports.register.attributes = {
    pkg: require('../package.json')
};<commit_msg>Remove properties<commit_after>var Hoek = require('hoek');
var Boom = require('boom');
var Joi = require('joi');
var Path = require('path');
var Schema = require('./schema');
var _ = require('lodash');
var utils = require('./utils');

var SWAGGER_VERSION = '1.2';
var defaultOptions = {
    endpoint: '/swagger'
};

module.exports.register = function (plugin, options, next) {
    var settings = Hoek.applyToDefaults(defaultOptions, options || {});
    settings.pluginRoutePrefix = (plugin.config.route.prefix || '');

    var internals = {
        apiDeclaration: require('./apiDeclaration')(settings),
        apiList: require('./apiListing')(settings)
    };

    var handler = {};

    handler.resourceListing = function (request, reply) {
        var apiRefs = internals.apiList(request.server.table(), request.query.tags);

        reply({
            swaggerVersion: SWAGGER_VERSION,
            apiVersion: settings.apiVersion,
            apis: apiRefs,
            info: settings.info,
            authorizations: settings.authorizations
        });
    };

    handler.apiDeclaration = function (request, reply) {
        var models = {};
        var apis = internals.apiDeclaration(request.server.table(), request.params.path, models);

        var apiDeclaration = {
            swaggerVersion: SWAGGER_VERSION,
            apiVersion: settings.apiVersion,
            basePath: utils.extractBaseHost(settings, request),
            resourcePath: '/' + request.params.path,
            produces: [ 'application/json' ],
            apis: apis,
            models: models
        };

        reply(apiDeclaration);
    };

    plugin.route({
        method: 'GET',
        path: options.endpoint,
        config: {
            tags: ['api', 'swagger'],
            auth: settings.auth,
            validate: {
                query: {
                    tags: Joi.string().optional()
                    //api_key: Joi.string().optional()
                }
            },
            handler: handler.resourceListing,
            response: {
                schema: Schema.ResourceListing
            }
        }
    });

    plugin.route({
        method: 'GET',
        path: options.endpoint + '/{path}',
        config: {
            tags: ['api', 'swagger'],
            auth: settings.auth,
            validate: {
                params: {
                    path: Joi.string().required()
                },
                query: {
                    //tags: Joi.string().optional(),
                    //api_key: Joi.string().optional()
                }
            },
            handler: handler.apiDeclaration,
            response: {
                schema: Schema.APIDeclaration
            }
        }
    });

    next();
};

module.exports.register.attributes = {
    pkg: require('../package.json')
};<|endoftext|>


<commit_before>(function()
{
  angular
    .module('foosey')
    .factory('FooseyService', FooseyService);

  FooseyService.$inject = ['$http'];

  function FooseyService($http)
  {
    var oldUrl = "http://api.foosey.futbol/app";
    var url = "http://beta.foosey.futbol/v1/";

    return {
      getAllPlayers     : getAllPlayers,
      getPlayer         : getPlayer,
      getPlayersByID    : getPlayersByID,
      getPlayerGames    : getPlayerGames,
      getAllGames       : getAllGames,
      getGame           : getGame,
      getGamesByID      : getGamesByID,
      getGames          : getGames,
      getEloHistory     : getEloHistory,
      getWinRateHistory : getWinRateHistory,
      addGame           : addGame,
      addPlayer         : addPlayer,
      editGame          : editGame,
      editPlayer        : editPlayer,
      removeGame        : removeGame,
      undo              : undo
    }

    // filter is an argument to filter out inactive players
    // true will filter to just active players, false will not
    function getAllPlayers(filter)
    {
      return $http.get(url + 'players').then(
        function(response)
        {
          if (!filter) return response.data;
          response = _.filter(response.data, function(player)
          {
            return player.active;
          });
          return response;
        });
    }

    function getPlayer(playerID)
    {
      return $http.get(url + 'players/' + playerID);
    }

    function getPlayersByID(playerIDs)
    {
      return $http.get(url + 'players?ids=' + playerIDs);
    }

    function getPlayerGames(playerID)
    {
      return $http.get(url + 'players/' + playerID + '/games');
    }

    function getAllGames()
    {
      return $http.get(url + 'games');
    }

    function getGame(gameID)
    {
      return $http.get(url + 'games/' + gameID);
    }

    function getGamesByID(gameIDs)
    {
      return $http.get(url + 'games?ids=' + gameIDs);
    }

    function getGames(limit, offset)
    {
      return $http.get(url + 'games?limit=' + limit + '&offset=' + offset).then(
        function (response)
        {
          return _.map(response.data, addDateInfo);
        });;
    }

    function addDateInfo(game)
    {
      var gameMoment = moment.unix(game.timestamp)

      game.date = gameMoment.format("MM/DD/YYYY");
      game.time = gameMoment.format("h:mma");
      return game;
    }

    function getAllEloHistory()
    {
      return $http.get(url + 'stats/elo');
    }

    function getEloHistory(playerID)
    {
      return $http.get(url + 'stats/elo/' + playerID).then(
        function(response)
        {
          _.each(response.data, function(point)
          {
            point.date = moment.unix(point.timestamp).format("MM/DD");
          })
          return response;
        });
    }

    function getWinRateHistory(playerID)
    {
      return $http.get(url + 'stats/winrate/' + playerID).then(
        function(response)
        {
          _.each(response.data, function(point)
          {
            point.date = moment.unix(point.timestamp).format("MM/DD");
          })
          return response;
        });
    }

    function addGame(game)
    {
      return $http.post(url + 'games', game);
    }

    function addPlayer(player)
    {
      return $http.post(url + 'players', player);
    }

    function editGame(game)
    {
      return $http.post(url + 'games/' + game.id, game);
    }

    function editPlayer(player)
    {
      return $http.post(url + 'players/' + player.id, player);
    }

    function removeGame(gameID)
    {
      return $http.delete(url + 'games/' + gameID);
    }

    function undo()
    {
      // Will maybe implement again
    }
  }
})();<commit_msg>add local url and change two posts to puts<commit_after>(function()
{
  angular
    .module('foosey')
    .factory('FooseyService', FooseyService);

  FooseyService.$inject = ['$http'];

  function FooseyService($http)
  {
    // var url = "http://localhost:4006/v1/";
    var url = "http://beta.foosey.futbol/v1/";

    return {
      getAllPlayers     : getAllPlayers,
      getPlayer         : getPlayer,
      getPlayersByID    : getPlayersByID,
      getPlayerGames    : getPlayerGames,
      getAllGames       : getAllGames,
      getGame           : getGame,
      getGamesByID      : getGamesByID,
      getGames          : getGames,
      getEloHistory     : getEloHistory,
      getWinRateHistory : getWinRateHistory,
      addGame           : addGame,
      addPlayer         : addPlayer,
      editGame          : editGame,
      editPlayer        : editPlayer,
      removeGame        : removeGame,
      undo              : undo
    }

    // filter is an argument to filter out inactive players
    // true will filter to just active players, false will not
    function getAllPlayers(filter)
    {
      return $http.get(url + 'players').then(
        function(response)
        {
          if (!filter) return response.data;
          response = _.filter(response.data, function(player)
          {
            return player.active;
          });
          return response;
        });
    }

    function getPlayer(playerID)
    {
      return $http.get(url + 'players/' + playerID);
    }

    function getPlayersByID(playerIDs)
    {
      return $http.get(url + 'players?ids=' + playerIDs);
    }

    function getPlayerGames(playerID)
    {
      return $http.get(url + 'players/' + playerID + '/games');
    }

    function getAllGames()
    {
      return $http.get(url + 'games');
    }

    function getGame(gameID)
    {
      return $http.get(url + 'games/' + gameID);
    }

    function getGamesByID(gameIDs)
    {
      return $http.get(url + 'games?ids=' + gameIDs);
    }

    function getGames(limit, offset)
    {
      return $http.get(url + 'games?limit=' + limit + '&offset=' + offset).then(
        function (response)
        {
          return _.map(response.data, addDateInfo);
        });;
    }

    function addDateInfo(game)
    {
      var gameMoment = moment.unix(game.timestamp)

      game.date = gameMoment.format("MM/DD/YYYY");
      game.time = gameMoment.format("h:mma");
      return game;
    }

    function getAllEloHistory()
    {
      return $http.get(url + 'stats/elo');
    }

    function getEloHistory(playerID)
    {
      return $http.get(url + 'stats/elo/' + playerID).then(
        function(response)
        {
          _.each(response.data, function(point)
          {
            point.date = moment.unix(point.timestamp).format("MM/DD");
          })
          return response;
        });
    }

    function getWinRateHistory(playerID)
    {
      return $http.get(url + 'stats/winrate/' + playerID).then(
        function(response)
        {
          _.each(response.data, function(point)
          {
            point.date = moment.unix(point.timestamp).format("MM/DD");
          })
          return response;
        });
    }

    function addGame(game)
    {
      return $http.post(url + 'games', game);
    }

    function addPlayer(player)
    {
      return $http.post(url + 'players', player);
    }

    function editGame(game)
    {
      return $http.put(url + 'games/' + game.id, game);
    }

    function editPlayer(player)
    {
      return $http.put(url + 'players/' + player.id, player);
    }

    function removeGame(gameID)
    {
      return $http.delete(url + 'games/' + gameID);
    }

    function undo()
    {
      // Will maybe implement again
    }
  }
})();<|endoftext|>


<commit_before>/* @author Ulrik Moe */
/* eslint-env node */
const fs = require('fs');
const Path = require('path');
const gulp = require('gulp');
const connect = require('gulp-connect');
const mo3 = require('mo3place')();
const through = require('through2');
const sass = require('node-sass');
const concat = require('gulp-concat');
const sourcemaps = require('gulp-sourcemaps');
const env = require('minimist')(process.argv.slice(2));
if (!env.git) { env.git = '1'; }

//  Last changed
const months = ['jan', 'feb', 'mar', 'apr', 'maj', 'juni',
    'juli', 'aug', 'sept', 'okt', 'nov', 'dec'];
const date = new Date();
env.lastUpdate = date.getDate() + '. ' + months[date.getMonth()] + ', ' +
    date.getFullYear();

function assets() {
    return gulp.src(['src/assets/**'], { base: 'src/assets' })
    .pipe(through.obj((file, enc, cb) => {
        if (/\.scss$/.test(file.path)) {
            file.contents = sass.renderSync({ data: file.contents.toString() }).css;
            file.path = file.path.slice(0, -4) + 'css';
        }
        cb(null, file);
    }))
    .pipe(gulp.dest('www'))
    .pipe(connect.reload());
}

function scripts() {
    return gulp.src(['src/js/data/dk.js', 'src/js/currency.js',
        'src/js/tools.js', 'src/js/main.js'])
        .pipe(through.obj((file, enc, cb) => {
            mo3.render(file, env);
            cb(null, file);
        }))
        .pipe(sourcemaps.init())
        .pipe(concat('all.js'))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest('www/js/'))
        .pipe(connect.reload());
}

function html() {
    return gulp.src(['src/*.html'])
        .pipe(through.obj((file, enc, cb) => {
            mo3.render(file, env);
            if (file.path.substring(__dirname.length) === '/src/index.html') {
                file.stat.mtime = fs.statSync('www/js/all.js').mtime;
            }
            cb(null, file);
        }))
        .pipe(gulp.dest('www'))
        .pipe(connect.reload());
}

gulp.task('sitemap', (cb) => {
    const index = JSON.parse(fs.readFileSync('./i18n/index.json')).da;
    let map = '<?xml version="1.0" encoding="UTF-8"?><urlset ' +
    'xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';

    for (const x in index) {
        const o = index[x];
        if (o.hidden) { continue; }
        let path = o.url.substring(o.url.indexOf('/'));
        path += (path.slice(-1) === '/') ? 'index.html' : '.html';
        const stat = fs.statSync(Path.join(__dirname, 'www', path));
        map += '<url><loc>https://' + o.url + '</loc>';
        map += '<lastmod>' + stat.mtime.toISOString() + '</lastmod></url>';
    }
    map += '</urlset>';
    const fd = fs.openSync(Path.join(__dirname, 'www', 'sitemap.xml'), 'w');
    fs.writeSync(fd, map);
    fs.closeSync(fd);
    cb(null);
});

gulp.task('serve', () => {
    connect.server({ root: 'www', livereload: true });
    gulp.watch(['src/assets/**'], assets);
    gulp.watch(['src/*.html'], html);
    gulp.watch(['src/js/**/*.js'], gulp.series(scripts, html));
});

gulp.task('build', gulp.series(assets, scripts, html, 'sitemap'));
gulp.task('default', gulp.series('build', 'serve'));
<commit_msg>Handle URLs without .html<commit_after>/* @author Ulrik Moe */
/* eslint-env node */
const fs = require('fs');
const Path = require('path');
const gulp = require('gulp');
const connect = require('gulp-connect');
const mo3 = require('mo3place')();
const through = require('through2');
const sass = require('node-sass');
const concat = require('gulp-concat');
const sourcemaps = require('gulp-sourcemaps');
const env = require('minimist')(process.argv.slice(2));
if (!env.git) { env.git = '1'; }

//  Last changed
const months = ['jan', 'feb', 'mar', 'apr', 'maj', 'juni',
    'juli', 'aug', 'sept', 'okt', 'nov', 'dec'];
const date = new Date();
env.lastUpdate = date.getDate() + '. ' + months[date.getMonth()] + ', ' +
    date.getFullYear();

function assets() {
    return gulp.src(['src/assets/**'], { base: 'src/assets' })
    .pipe(through.obj((file, enc, cb) => {
        if (/\.scss$/.test(file.path)) {
            file.contents = sass.renderSync({ data: file.contents.toString() }).css;
            file.path = file.path.slice(0, -4) + 'css';
        }
        cb(null, file);
    }))
    .pipe(gulp.dest('www'))
    .pipe(connect.reload());
}

function scripts() {
    return gulp.src(['src/js/data/dk.js', 'src/js/currency.js',
        'src/js/tools.js', 'src/js/main.js'])
        .pipe(through.obj((file, enc, cb) => {
            mo3.render(file, env);
            cb(null, file);
        }))
        .pipe(sourcemaps.init())
        .pipe(concat('all.js'))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest('www/js/'))
        .pipe(connect.reload());
}

function html() {
    return gulp.src(['src/*.html'])
        .pipe(through.obj((file, enc, cb) => {
            mo3.render(file, env);
            if (file.path.substring(__dirname.length) === '/src/index.html') {
                file.stat.mtime = fs.statSync('www/js/all.js').mtime;
            }
            cb(null, file);
        }))
        .pipe(gulp.dest('www'))
        .pipe(connect.reload());
}

gulp.task('sitemap', (cb) => {
    const index = JSON.parse(fs.readFileSync('./i18n/index.json')).da;
    let map = '<?xml version="1.0" encoding="UTF-8"?><urlset ' +
    'xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';

    for (const x in index) {
        const o = index[x];
        if (o.hidden) { continue; }
        let path = o.url.substring(o.url.indexOf('/'));
        path += (path.slice(-1) === '/') ? 'index.html' : '.html';
        const stat = fs.statSync(Path.join(__dirname, 'www', path));
        map += '<url><loc>https://' + o.url + '</loc>';
        map += '<lastmod>' + stat.mtime.toISOString() + '</lastmod></url>';
    }
    map += '</urlset>';
    const fd = fs.openSync(Path.join(__dirname, 'www', 'sitemap.xml'), 'w');
    fs.writeSync(fd, map);
    fs.closeSync(fd);
    cb(null);
});

gulp.task('serve', () => {
    connect.server({
        root: 'www',
        livereload: true,
        middleware: () => ([(req, res, next) => {
            if (req.url.slice(-1) !== '/' && req.url.indexOf('.') === -1) {
                req.url += '.html';
            }
            next();
        }])
    });

    gulp.watch(['src/assets/**'], assets);
    gulp.watch(['src/*.html'], html);
    gulp.watch(['src/js/**/*.js'], gulp.series(scripts, html));
});

gulp.task('build', gulp.series(assets, scripts, html, 'sitemap'));
gulp.task('default', gulp.series('build', 'serve'));
<|endoftext|>