<commit_before>var step = require('step');
var queue = require('queue-async');
var _ = require('underscore');

const INCOMPATIBLE_LAYERS_ERROR =
'The layergroup contains incompatible layers: don\'t mix styled layers with non styled layers (without cartocss)';

var MapConfigProviderProxy = require('../models/providers/mapconfig_provider_proxy');

/**
 * @param {TileBackend} tileBackend
 * @param {AttributesBackend} attributesBackend
 * @constructor
 * @type {MapValidatorBackend}
 */
function MapValidatorBackend(tileBackend, attributesBackend) {
    this.tileBackend = tileBackend;
    this.attributesBackend = attributesBackend;
}

module.exports = MapValidatorBackend;

MapValidatorBackend.prototype.validate = function(mapConfigProvider, callback) {
    var self = this;

    mapConfigProvider.getMapConfig(function(err, mapConfig, params) {
        if (err) {
            return callback(err, false);
        }

        var token = mapConfig.id();

        if (mapConfig.isVectorLayergroup()) {
            return self.validateVectorLayergroup(mapConfigProvider, params, token, callback);
        }

        if (mapConfig.hasIncompatibleLayers()) {
            return callback(new Error(INCOMPATIBLE_LAYERS_ERROR));
        }

        function validateMapnikTile(layerId) {
            return function(done) {
                self.tryFetchTileOrGrid(mapConfigProvider, _.clone(params), token, 'png', layerId, done);
            };
        }

        function validateMapnikGridJson(layerId) {
            return function(done) {
                self.tryFetchTileOrGrid(mapConfigProvider, _.clone(params), token, 'grid.json', layerId, done);
            };
        }

        function validateTorqueJson(layerId) {
            return function(done) {
                self.tryFetchTileOrGrid(mapConfigProvider, _.clone(params), token, 'json.torque', layerId, done);
            };
        }

        function validateAttributes(layerId) {
            return function(done) {
                self.tryFetchFeatureAttributes(mapConfigProvider, _.clone(params), token, layerId, done);
            };
        }

        var mapnikLayersIds = getMapnikLayerIds(mapConfig);

        step(
            function validate$allMapnikTileLayers () {
              var next = this;

              if (!mapnikLayersIds.length) {
                  return next();
              }

              var validateAllMapnikTileLayers = validateMapnikTile();
              validateAllMapnikTileLayers(next);
            },
            function validate$checkFailingMapnikTileLayer (errAllLayers) {
                var next = this;

                if (!errAllLayers) {
                    return next();
                }

                var checkFailingMapnikTileLayerFns = [];
                mapnikLayersIds.forEach(function (layerId) {
                    checkFailingMapnikTileLayerFns.push(validateMapnikTile(layerId));
                });

                var checkFailingMapnikLayerQueue = queue(checkFailingMapnikTileLayerFns.length);
                checkFailingMapnikTileLayerFns.forEach(function (validateFn) {
                    checkFailingMapnikLayerQueue.defer(validateFn);
                });

                checkFailingMapnikLayerQueue.awaitAll(function (err) {
                    // err from failing layer || err from all mapnik layers
                    return next(err || errAllLayers);
                });
            },
            function validate$remaningFormatLayers (err) {
                var next = this;

                if (err) {
                    return next(err);
                }

                var validateRemainingFormatLayerFns = [];

                mapConfig.getLayers().forEach(function(layer, layerId) {
                    var lyropt = layer.options;
                    var layerType = mapConfig.layerType(layerId);

                    if (layerType === 'mapnik') {
                        if ( lyropt.interactivity ) {
                            validateRemainingFormatLayerFns.push(validateMapnikGridJson(layerId));
                        }
                    } else if (layerType === 'torque') {
                        validateRemainingFormatLayerFns.push(validateTorqueJson(layerId));
                    }

                    // both 'cartodb' or 'torque' types can have attributes
                    if (lyropt.attributes) {
                        validateRemainingFormatLayerFns.push(validateAttributes(layerId));
                    }
                });

                var validationQueue = queue(validateRemainingFormatLayerFns.length);
                validateRemainingFormatLayerFns.forEach(function(validateFn) {
                    validationQueue.defer(validateFn);
                });

                validationQueue.awaitAll(function (err) {
                    return next(err);
                });
            },
            function validate$finish (err) {
                return callback(err, !err);
            }
        );
    });
};

function getMapnikLayerIds(mapConfig) {
    var mapnikLayerIds = [];

    mapConfig.getLayers().forEach(function(layer, layerId) {
        if (mapConfig.layerType(layerId) === 'mapnik') {
            mapnikLayerIds.push(layerId);
        }
    });

    return mapnikLayerIds;
}

MapValidatorBackend.prototype.tryFetchTileOrGrid = function (mapConfigProvider, params, token, format, layerId,
                                                             callback) {
    params.token = token;
    params.format = format;
    params.layer = layerId;
    params.x = 0;
    params.y = 0;
    params.z = 30;

    this.tileBackend.getTile(new MapConfigProviderProxy(mapConfigProvider, params), params, function (err) {
        if (err) {
            // Grainstore returns styles error indicating layer index, since validation is performed
            // one by one instead of all blended layers of MapConfig, this fixes the error message to
            // show the right layer index.
            if (err.message.match(/^style0: CartoCSS is empty/) && layerId > 0) {
                err.message = err.message.replace(/style0/i, 'style' + layerId);
            }
            err.layerIndex = layerId;
            return callback(err);
        }
        callback();
    });
};

MapValidatorBackend.prototype.tryFetchFeatureAttributes = function(mapConfigProvider, params, token, layernum,
                                                                   callback) {
    params.token = token;
    params.layer = layernum;

    var proxyProvider = new MapConfigProviderProxy(mapConfigProvider, params);
    this.attributesBackend.getFeatureAttributes(proxyProvider, params, true, function (err) {
        if (err) {
            err.layerIndex = layernum;
            return callback(err);
        }
        callback();
    });
};

MapValidatorBackend.prototype.validateVectorLayergroup = function (mapConfigProvider, params, token, callback) {
    let allLayers; // if layer is undefined then it fetchs all layers

    this.tryFetchTileOrGrid(mapConfigProvider, _.clone(params), token, 'mvt', allLayers, (err) => {
        if (err && err.message === 'Tile does not exist') {
            return callback(null, true);
        }

        if (err) {
            return callback(err, false);
        }

        callback(null, true);
    });
};
<commit_msg>Improve error while creating a map with incompatible layers<commit_after>var step = require('step');
var queue = require('queue-async');
var _ = require('underscore');

const INCOMPATIBLE_LAYERS_ERROR =
'The layergroup contains incompatible layers: don\'t mix styled layers with non styled layers (without cartocss)';

var MapConfigProviderProxy = require('../models/providers/mapconfig_provider_proxy');

/**
 * @param {TileBackend} tileBackend
 * @param {AttributesBackend} attributesBackend
 * @constructor
 * @type {MapValidatorBackend}
 */
function MapValidatorBackend(tileBackend, attributesBackend) {
    this.tileBackend = tileBackend;
    this.attributesBackend = attributesBackend;
}

module.exports = MapValidatorBackend;

MapValidatorBackend.prototype.validate = function(mapConfigProvider, callback) {
    var self = this;

    mapConfigProvider.getMapConfig(function(err, mapConfig, params) {
        if (err) {
            return callback(err, false);
        }

        var token = mapConfig.id();

        if (mapConfig.isVectorLayergroup()) {
            return self.validateVectorLayergroup(mapConfigProvider, params, token, callback);
        }

        if (mapConfig.hasIncompatibleLayers()) {
            const error = new Error(INCOMPATIBLE_LAYERS_ERROR);
            error.type = 'layergroup';
            error.http_status = 400;
            return callback(error);
        }

        function validateMapnikTile(layerId) {
            return function(done) {
                self.tryFetchTileOrGrid(mapConfigProvider, _.clone(params), token, 'png', layerId, done);
            };
        }

        function validateMapnikGridJson(layerId) {
            return function(done) {
                self.tryFetchTileOrGrid(mapConfigProvider, _.clone(params), token, 'grid.json', layerId, done);
            };
        }

        function validateTorqueJson(layerId) {
            return function(done) {
                self.tryFetchTileOrGrid(mapConfigProvider, _.clone(params), token, 'json.torque', layerId, done);
            };
        }

        function validateAttributes(layerId) {
            return function(done) {
                self.tryFetchFeatureAttributes(mapConfigProvider, _.clone(params), token, layerId, done);
            };
        }

        var mapnikLayersIds = getMapnikLayerIds(mapConfig);

        step(
            function validate$allMapnikTileLayers () {
              var next = this;

              if (!mapnikLayersIds.length) {
                  return next();
              }

              var validateAllMapnikTileLayers = validateMapnikTile();
              validateAllMapnikTileLayers(next);
            },
            function validate$checkFailingMapnikTileLayer (errAllLayers) {
                var next = this;

                if (!errAllLayers) {
                    return next();
                }

                var checkFailingMapnikTileLayerFns = [];
                mapnikLayersIds.forEach(function (layerId) {
                    checkFailingMapnikTileLayerFns.push(validateMapnikTile(layerId));
                });

                var checkFailingMapnikLayerQueue = queue(checkFailingMapnikTileLayerFns.length);
                checkFailingMapnikTileLayerFns.forEach(function (validateFn) {
                    checkFailingMapnikLayerQueue.defer(validateFn);
                });

                checkFailingMapnikLayerQueue.awaitAll(function (err) {
                    // err from failing layer || err from all mapnik layers
                    return next(err || errAllLayers);
                });
            },
            function validate$remaningFormatLayers (err) {
                var next = this;

                if (err) {
                    return next(err);
                }

                var validateRemainingFormatLayerFns = [];

                mapConfig.getLayers().forEach(function(layer, layerId) {
                    var lyropt = layer.options;
                    var layerType = mapConfig.layerType(layerId);

                    if (layerType === 'mapnik') {
                        if ( lyropt.interactivity ) {
                            validateRemainingFormatLayerFns.push(validateMapnikGridJson(layerId));
                        }
                    } else if (layerType === 'torque') {
                        validateRemainingFormatLayerFns.push(validateTorqueJson(layerId));
                    }

                    // both 'cartodb' or 'torque' types can have attributes
                    if (lyropt.attributes) {
                        validateRemainingFormatLayerFns.push(validateAttributes(layerId));
                    }
                });

                var validationQueue = queue(validateRemainingFormatLayerFns.length);
                validateRemainingFormatLayerFns.forEach(function(validateFn) {
                    validationQueue.defer(validateFn);
                });

                validationQueue.awaitAll(function (err) {
                    return next(err);
                });
            },
            function validate$finish (err) {
                return callback(err, !err);
            }
        );
    });
};

function getMapnikLayerIds(mapConfig) {
    var mapnikLayerIds = [];

    mapConfig.getLayers().forEach(function(layer, layerId) {
        if (mapConfig.layerType(layerId) === 'mapnik') {
            mapnikLayerIds.push(layerId);
        }
    });

    return mapnikLayerIds;
}

MapValidatorBackend.prototype.tryFetchTileOrGrid = function (mapConfigProvider, params, token, format, layerId,
                                                             callback) {
    params.token = token;
    params.format = format;
    params.layer = layerId;
    params.x = 0;
    params.y = 0;
    params.z = 30;

    this.tileBackend.getTile(new MapConfigProviderProxy(mapConfigProvider, params), params, function (err) {
        if (err) {
            // Grainstore returns styles error indicating layer index, since validation is performed
            // one by one instead of all blended layers of MapConfig, this fixes the error message to
            // show the right layer index.
            if (err.message.match(/^style0: CartoCSS is empty/) && layerId > 0) {
                err.message = err.message.replace(/style0/i, 'style' + layerId);
            }
            err.layerIndex = layerId;
            return callback(err);
        }
        callback();
    });
};

MapValidatorBackend.prototype.tryFetchFeatureAttributes = function(mapConfigProvider, params, token, layernum,
                                                                   callback) {
    params.token = token;
    params.layer = layernum;

    var proxyProvider = new MapConfigProviderProxy(mapConfigProvider, params);
    this.attributesBackend.getFeatureAttributes(proxyProvider, params, true, function (err) {
        if (err) {
            err.layerIndex = layernum;
            return callback(err);
        }
        callback();
    });
};

MapValidatorBackend.prototype.validateVectorLayergroup = function (mapConfigProvider, params, token, callback) {
    let allLayers; // if layer is undefined then it fetchs all layers

    this.tryFetchTileOrGrid(mapConfigProvider, _.clone(params), token, 'mvt', allLayers, (err) => {
        if (err && err.message === 'Tile does not exist') {
            return callback(null, true);
        }

        if (err) {
            return callback(err, false);
        }

        callback(null, true);
    });
};
<|endoftext|>


<commit_before>'use strict'

const Joi = require('joi')

const parseResponse = response => {
  const parsed = {
    statusCode: response.statusCode
  }

  if (response.body) {
    if (typeof response.body === 'object') {
      parsed.body = parseKeys(response.body)
    } else if (response.body.startsWith('Joi')) {
      parsed.body = eval(response.body)
    } else {
      parsed.body = response.body
    }
  }

  if (response.headers) {
    parsed.headers = parseKeys(response.headers)
  }

  return parsed
}

module.exports = parseResponse

const parseKeys = object => {
  const keys = Object.keys(object)

  const joiSpec = keys.map(key => {
    if (typeof object[key] === 'object') {
      return parseKeys(object[key])
    } else if (object[key].startsWith('Joi')) {
      return eval(object[key])
    } else {
      return object[key]
    }
  })

  return Joi.object(keys.reduce((acc, key, index) => {
    acc[key] = joiSpec[index]
    return acc
  }, {})).unknown(true)
}
<commit_msg>Adding support for response body to contain arrays<commit_after>'use strict'

const Joi = require('joi')

const parseResponse = response => {
  const parsed = {
    statusCode: response.statusCode
  }

  if (response.body) {
    if (typeof response.body === 'object') {
      parsed.body = parseObject(response.body)
    } else if (Array.isArray(response.body)) {
      parsed.body = parseArray(response.body)
    } else if (response.body.startsWith('Joi')) {
      parsed.body = eval(response.body)
    } else {
      parsed.body = response.body
    }
  }

  if (response.headers) {
    parsed.headers = parseObject(response.headers)
  }

  return parsed
}

module.exports = parseResponse

const parseArray = array => {
  const joiSpec = array.map(item => {
    if (typeof item === 'object') {
      return parseObject(item)
    } else if (Array.isArray(item)) {
      return parseArray(item)
    } else if (item.startsWith('Joi')) {
      return eval(item)
    } else {
      return item
    }
  })

  return Joi.array().items(...joiSpec)
}

const parseObject = object => {
  const keys = Object.keys(object)

  const joiSpec = keys.map(key => {
    if (typeof object[key] === 'object') {
      return parseObject(object[key])
    } else if (Array.isArray(object[key])) {
      return parseArray(object[key])
    } else if (object[key].startsWith('Joi')) {
      return eval(object[key])
    } else {
      return object[key]
    }
  })

  return Joi.object(keys.reduce((acc, key, index) => {
    acc[key] = joiSpec[index]
    return acc
  }, {})).unknown(true)
}
<|endoftext|>


<commit_before>'use strict';

const gulp = require('gulp');
const tslint = require('gulp-tslint');
const gitignore = require('gitignore-to-glob')();

gitignore.push('**/*.ts');

gulp.task('tslint', () =>
  gulp
    .src(gitignore)
    .pipe(tslint({
      formatter: 'verbose',
      emitError: true,
      summarizeFailureOutput: true,
      reportLimit: 50
    }))
    .pipe(tslint.report())
);

gulp.task('lint', ['tslint']);
<commit_msg>chore(build): Exclude all node_modules contents on lint (#987)<commit_after>'use strict';

const gulp = require('gulp');
const tslint = require('gulp-tslint');
const gitignore = require('gitignore-to-glob')();

gitignore.push('!node_modules/**/*');
gitignore.push('**/*.ts');

gulp.task('tslint', () =>
  gulp
    .src(gitignore)
    .pipe(tslint({
      formatter: 'verbose',
      emitError: true,
      summarizeFailureOutput: true,
      reportLimit: 50
    }))
    .pipe(tslint.report())
);

gulp.task('lint', ['tslint']);
<|endoftext|>


<commit_before>(function() {
    "use strict";

    angular
        .module('VinculacionApp')
        .controller('ActivateProfessorController', ActivateProfessorController);

    ActivateProfessorController.$inject = ['$rootScope', '$state', '$stateParams', 'professors', 'TbUtils', 'authentication'];

    function ActivateProfessorController($rootScope, $state, $stateParams, professors, TbUtils, authentication) {

        var vm = this;

        vm.professor = {
            AccountId: '',
            Password: ''
        };

        vm.accountId;
        vm.confirmPass = '';

        vm.activateProfessor = activateProfessor;
        $rootScope.globals.guest = true;

        leaveIfSessionStarted();
        getToken();

        function activateProfessor() {
            professors.activateProfessor(vm.professor, activateProfessorSuccess, activateProfessorFail);
        }

        function activateProfessorSuccess(response) {
            $state.go('landing');
            TBUtils.displayNotification('success', 'Usuario activado!', 'Ya puede navegar el sitio.');
        }

        function activateProfessorFail(response) {
            console.log(response);
            TbUtils.showErrorMessage('error', response, 'No se ha podido activar el profesor.', 'Error!');
            $state.go('landing');
        }

        function getToken() {
            if($stateParams.accountId == undefined || $stateParams.accountId == '') $state.go('landing');

            console.log($stateParams.accountId);
            vm.professor.AccountId = $stateParams.accountId;
        }

        function leaveIfSessionStarted() {
            if($rootScope.globals.token) {
                authentication.ClearCredentials();
                $state.go('landing');
            }
        }
    }
})();<commit_msg>Fix typo in activateProfessorSuccess<commit_after>(function() {
    "use strict";

    angular
        .module('VinculacionApp')
        .controller('ActivateProfessorController', ActivateProfessorController);

    ActivateProfessorController.$inject = ['$rootScope', '$state', '$stateParams', 'professors', 'TbUtils', 'authentication'];

    function ActivateProfessorController($rootScope, $state, $stateParams, professors, TbUtils, authentication) {

        var vm = this;

        vm.professor = {
            AccountId: '',
            Password: ''
        };

        vm.accountId;
        vm.confirmPass = '';

        vm.activateProfessor = activateProfessor;
        $rootScope.globals.guest = true;

        leaveIfSessionStarted();
        getToken();

        function activateProfessor() {
            professors.activateProfessor(vm.professor, activateProfessorSuccess, activateProfessorFail);
        }

        function activateProfessorSuccess(response) {
            $state.go('landing');
            TbUtils.displayNotification('success', 'Usuario activado!', 'Ya puede navegar el sitio.');
        }

        function activateProfessorFail(response) {
            console.log(response);
            TbUtils.showErrorMessage('error', response, 'No se ha podido activar el profesor.', 'Error!');
            $state.go('landing');
        }

        function getToken() {
            if($stateParams.accountId == undefined || $stateParams.accountId == '') $state.go('landing');

            console.log($stateParams.accountId);
            vm.professor.AccountId = $stateParams.accountId;
        }

        function leaveIfSessionStarted() {
            if($rootScope.globals.token) {
                authentication.ClearCredentials();
                $state.go('landing');
            }
        }
    }
})();<|endoftext|>


<commit_before>// Karma configuration
// Generated on Mon Feb 01 2016 22:48:23 GMT-0500 (EST)

var BROWSERS = ["HeadlessChrome", "HeadlessFirefox", "Safari"];
// var BROWSERS = ['Safari']

if (process.env.BROWSER === "chrome"){
	BROWSERS = ["HeadlessChrome"];
} else if (process.env.BROWSER === "firefox"){
	BROWSERS = ["HeadlessFirefox"];
} else if (process.env.BROWSER === "safari"){
	BROWSERS = ["Safari"];
} else {
	BROWSERS = ["HeadlessChrome"];
}

module.exports = function(config){
	var configuration = {

		// base path that will be used to resolve all patterns (eg. files, exclude)
		basePath : "../",

		// frameworks to use
		// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
		frameworks : ["mocha"],

		// list of files / patterns to load in the browser
		files : [
			"./build/test.js",
			// { pattern : "test/*/*.js", included : false },
			// { pattern : "examples/*.html", included : false },
			// { pattern : "examples/scripts/*.js", included : false },
			// { pattern : "examples/style/*.css", included : false },
			// { pattern : "examples/audio/*/*.mp3", included : false },
			// { pattern : "examples/audio/*.mp3", included : false },
			// { pattern : "examples/audio/*/*.png", included : false },
			// { pattern : "build/*.js", included : false },
			{ pattern : "test/audio/*", included : false },
			{ pattern : "test/audio/*/*", included : false },
			// { pattern : "Tone/*/*.js", included : false },
		],

		// list of files to exclude
		exclude : [],

		// preprocess matching files before serving them to the browser
		// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
		preprocessors : {
			"Tone/!(shim)/*.js" : ["coverage"]
		},

		// test results reporter to use
		// possible values: 'dots', 'progress'
		// available reporters: https://npmjs.org/browse/keyword/karma-reporter
		reporters : ["dots", "coverage"],

		coverageReporter : {
			type : "lcov",
			dir : "test/coverage/"
		},

		//plugins
		plugins : [
			"karma-coverage",
			"karma-mocha",
			"karma-requirejs",
			"karma-chrome-launcher",
			"karma-firefox-launcher",
			"karma-safari-launcher"
		],

		client : {
			mocha : {
				reporter : "html", // change Karma's debug.html to the mocha web reporter
				ui : "bdd"
			}
		},

		// web server port
		port : 9876,

		// enable / disable colors in the output (reporters and logs)
		colors : true,

		// set the inactivity level to longer
		browserNoActivityTimeout : 40000,

		// level of logging
		// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
		logLevel : config.LOG_ERROR,

		// enable / disable watching file and executing tests whenever any file changes
		autoWatch : false,

		// start these browsers
		// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
		browsers : BROWSERS,

		// Continuous Integration mode
		// if true, Karma captures browsers, runs the tests and exits
		singleRun : true,

		// Concurrency level
		// how many browser should be started simultaneous
		// concurrency: process.env.TRAVIS ? 1 : Infinity,
		concurrency : Infinity,

		//custom launcher for travis
		customLaunchers : {
			HeadlessChrome : {
				base : "ChromeHeadless",
				flags : ["--no-sandbox", "--use-fake-ui-for-media-stream", "--use-fake-device-for-media-stream", "--autoplay-policy=no-user-gesture-required"]
			},
			HeadlessFirefox : {
				base : "Firefox",
				flags : ["-headless"],
				prefs : {
					"media.navigator.permission.disabled" : true,
					"focusmanager.testmode" : true
				}
			}
		}
	};

	config.set(configuration);
};
<commit_msg>no need for karma-requirejs<commit_after>// Karma configuration
// Generated on Mon Feb 01 2016 22:48:23 GMT-0500 (EST)

var BROWSERS = ["HeadlessChrome", "HeadlessFirefox", "Safari"];
// var BROWSERS = ['Safari']

if (process.env.BROWSER === "chrome"){
	BROWSERS = ["HeadlessChrome"];
} else if (process.env.BROWSER === "firefox"){
	BROWSERS = ["HeadlessFirefox"];
} else if (process.env.BROWSER === "safari"){
	BROWSERS = ["Safari"];
} else {
	BROWSERS = ["HeadlessChrome"];
}

module.exports = function(config){
	var configuration = {

		// base path that will be used to resolve all patterns (eg. files, exclude)
		basePath : "../",

		// frameworks to use
		// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
		frameworks : ["mocha"],

		// list of files / patterns to load in the browser
		files : [
			"./build/test.js",
			// { pattern : "test/*/*.js", included : false },
			// { pattern : "examples/*.html", included : false },
			// { pattern : "examples/scripts/*.js", included : false },
			// { pattern : "examples/style/*.css", included : false },
			// { pattern : "examples/audio/*/*.mp3", included : false },
			// { pattern : "examples/audio/*.mp3", included : false },
			// { pattern : "examples/audio/*/*.png", included : false },
			// { pattern : "build/*.js", included : false },
			{ pattern : "test/audio/*", included : false },
			{ pattern : "test/audio/*/*", included : false },
			// { pattern : "Tone/*/*.js", included : false },
		],

		// list of files to exclude
		exclude : [],

		// preprocess matching files before serving them to the browser
		// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
		preprocessors : {
			"Tone/!(shim)/*.js" : ["coverage"]
		},

		// test results reporter to use
		// possible values: 'dots', 'progress'
		// available reporters: https://npmjs.org/browse/keyword/karma-reporter
		reporters : ["dots", "coverage"],

		coverageReporter : {
			type : "lcov",
			dir : "test/coverage/"
		},

		//plugins
		plugins : [
			"karma-coverage",
			"karma-mocha",
			"karma-chrome-launcher",
			"karma-firefox-launcher",
			"karma-safari-launcher"
		],

		client : {
			mocha : {
				reporter : "html", // change Karma's debug.html to the mocha web reporter
				ui : "bdd"
			}
		},

		// web server port
		port : 9876,

		// enable / disable colors in the output (reporters and logs)
		colors : true,

		// set the inactivity level to longer
		browserNoActivityTimeout : 40000,

		// level of logging
		// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
		logLevel : config.LOG_ERROR,

		// enable / disable watching file and executing tests whenever any file changes
		autoWatch : false,

		// start these browsers
		// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
		browsers : BROWSERS,

		// Continuous Integration mode
		// if true, Karma captures browsers, runs the tests and exits
		singleRun : true,

		// Concurrency level
		// how many browser should be started simultaneous
		// concurrency: process.env.TRAVIS ? 1 : Infinity,
		concurrency : Infinity,

		//custom launcher for travis
		customLaunchers : {
			HeadlessChrome : {
				base : "ChromeHeadless",
				flags : ["--no-sandbox", "--use-fake-ui-for-media-stream", "--use-fake-device-for-media-stream", "--autoplay-policy=no-user-gesture-required"]
			},
			HeadlessFirefox : {
				base : "Firefox",
				flags : ["-headless"],
				prefs : {
					"media.navigator.permission.disabled" : true,
					"focusmanager.testmode" : true
				}
			}
		}
	};

	config.set(configuration);
};
<|endoftext|>


<commit_before>/** SearchWidget used in every page in the entire administrator interface.
 *
 * Enables users to search for everything (like the dashboard) or just within
 * the current item.
 * */
Ext.define('devilry.administrator.AdministratorSearchWidget', {
    extend: 'devilry.extjshelpers.searchwidget.SearchWidget',
    requires: [
        'devilry.extjshelpers.searchwidget.FilterConfigDefaults',
    ],

    config: {
        /**
         * @cfg
         * Url prefix. Should be the absolute URL path to /administrator/.
         */
        urlPrefix: '',

        /**
         * @cfg
         * ``Ext.XTemplate`` for Node rows.
         */
        nodeRowTpl: '',

        /**
         * @cfg
         * ``Ext.XTemplate`` for Subject rows.
         */
        subjectRowTpl: '',

        /**
         * @cfg
         * ``Ext.XTemplate`` for Period rows.
         */
        periodRowTpl: '',

        /**
         * @cfg
         * ``Ext.XTemplate`` for Assignment rows.
         */
        assignmentRowTpl: '',

        /**
         * @cfg
         * ``Ext.XTemplate`` for AssignmentGroup rows.
         */
        assignmentgroupRowTpl: '',

        /**
         * @cfg
         * ``Ext.XTemplate`` for Delivery rows.
         */
        deliveryRowTpl: ''
    },

    initComponent: function() {
        Ext.apply(this, {
            searchResultItems: [{
                xtype: 'searchresults',
                title: 'Nodes',
                store: Ext.data.StoreManager.lookup('devilry.apps.administrator.simplified.SimplifiedNodeStoreSearch'),
                filterconfig: {
                    type: 'node'
                },
                resultitemConfig: {
                    tpl: this.nodeRowTpl,
                    defaultbutton: {
                        text: 'Edit',
                        clickLinkTpl: this.urlPrefix + 'node/{id}'
                    }
                }
            }, {
                xtype: 'searchresults',
                title: 'Subjects',
                store: Ext.data.StoreManager.lookup('devilry.apps.administrator.simplified.SimplifiedSubjectStoreSearch'),
                filterconfig: {
                    type: 'subject'
                },
                resultitemConfig: {
                    tpl: this.subjectRowTpl,
                    defaultbutton: {
                        text: 'Edit',
                        clickLinkTpl: this.urlPrefix + 'subject/{id}'
                    }
                }
            }, {
                xtype: 'searchresults',
                title: 'Periods',
                store: Ext.data.StoreManager.lookup('devilry.apps.administrator.simplified.SimplifiedPeriodStoreSearch'),
                filterconfig: {
                    type: 'period'
                },
                resultitemConfig: {
                    tpl: this.periodRowTpl,
                    defaultbutton: {
                        text: 'Edit',
                        clickLinkTpl: this.urlPrefix + 'period/{id}'
                    }
                }
            }, {
                xtype: 'searchresults',
                title: 'Assignments',
                store: Ext.data.StoreManager.lookup('devilry.apps.administrator.simplified.SimplifiedAssignmentStoreSearch'),
                filterconfig: devilry.extjshelpers.searchwidget.FilterConfigDefaults.assignment,
                resultitemConfig: {
                    tpl: this.assignmentRowTpl,
                    defaultbutton: {
                        text: 'Edit',
                        clickLinkTpl: this.urlPrefix + 'assignment/{id}'
                    },
                    menuitems: [{
                        text: 'Show deliveries',
                        clickFilter: 'type:delivery assignment:{id}'
                    }]
                }
            }, {
                xtype: 'searchresults',
                title: 'Assignment groups',
                store: Ext.data.StoreManager.lookup('devilry.apps.administrator.simplified.SimplifiedAssignmentGroupStoreSearch'),
                filterconfig: devilry.extjshelpers.searchwidget.FilterConfigDefaults.assignmentgroup,
                resultitemConfig: {
                    tpl: this.assignmentgroupRowTpl,
                    defaultbutton: {
                        text: 'Edit',
                        clickLinkTpl: this.urlPrefix + 'assignmentgroup/{id}'
                    }
                }
            }, {
                xtype: 'searchresults',
                title: 'Delivery',
                store: Ext.data.StoreManager.lookup('devilry.apps.administrator.simplified.SimplifiedDeliveryStoreSearch'),
                filterconfig: devilry.extjshelpers.searchwidget.FilterConfigDefaults.delivery,
                resultitemConfig: {
                    tpl: this.deliveryRowTpl
                }
            }]
        });
        this.callParent(arguments);
    }
});
<commit_msg>apps.administrator: Updated search urls.<commit_after>/** SearchWidget used in every page in the entire administrator interface.
 *
 * Enables users to search for everything (like the dashboard) or just within
 * the current item.
 * */
Ext.define('devilry.administrator.AdministratorSearchWidget', {
    extend: 'devilry.extjshelpers.searchwidget.SearchWidget',
    requires: [
        'devilry.extjshelpers.searchwidget.FilterConfigDefaults',
    ],

    config: {
        /**
         * @cfg
         * Url prefix. Should be the absolute URL path to /administrator/.
         */
        urlPrefix: '',

        /**
         * @cfg
         * ``Ext.XTemplate`` for Node rows.
         */
        nodeRowTpl: '',

        /**
         * @cfg
         * ``Ext.XTemplate`` for Subject rows.
         */
        subjectRowTpl: '',

        /**
         * @cfg
         * ``Ext.XTemplate`` for Period rows.
         */
        periodRowTpl: '',

        /**
         * @cfg
         * ``Ext.XTemplate`` for Assignment rows.
         */
        assignmentRowTpl: '',

        /**
         * @cfg
         * ``Ext.XTemplate`` for AssignmentGroup rows.
         */
        assignmentgroupRowTpl: '',

        /**
         * @cfg
         * ``Ext.XTemplate`` for Delivery rows.
         */
        deliveryRowTpl: ''
    },

    initComponent: function() {
        Ext.apply(this, {
            searchResultItems: [{
                xtype: 'searchresults',
                title: 'Nodes',
                store: Ext.data.StoreManager.lookup('devilry.apps.administrator.simplified.SimplifiedNodeStoreSearch'),
                filterconfig: {
                    type: 'node'
                },
                resultitemConfig: {
                    tpl: this.nodeRowTpl,
                    defaultbutton: {
                        text: 'Edit',
                        clickLinkTpl: this.urlPrefix + 'node/view/{id}'
                    }
                }
            }, {
                xtype: 'searchresults',
                title: 'Subjects',
                store: Ext.data.StoreManager.lookup('devilry.apps.administrator.simplified.SimplifiedSubjectStoreSearch'),
                filterconfig: {
                    type: 'subject'
                },
                resultitemConfig: {
                    tpl: this.subjectRowTpl,
                    defaultbutton: {
                        text: 'Edit',
                        clickLinkTpl: this.urlPrefix + 'subject/view/{id}'
                    }
                }
            }, {
                xtype: 'searchresults',
                title: 'Periods',
                store: Ext.data.StoreManager.lookup('devilry.apps.administrator.simplified.SimplifiedPeriodStoreSearch'),
                filterconfig: {
                    type: 'period'
                },
                resultitemConfig: {
                    tpl: this.periodRowTpl,
                    defaultbutton: {
                        text: 'Edit',
                        clickLinkTpl: this.urlPrefix + 'period/view/{id}'
                    }
                }
            }, {
                xtype: 'searchresults',
                title: 'Assignments',
                store: Ext.data.StoreManager.lookup('devilry.apps.administrator.simplified.SimplifiedAssignmentStoreSearch'),
                filterconfig: devilry.extjshelpers.searchwidget.FilterConfigDefaults.assignment,
                resultitemConfig: {
                    tpl: this.assignmentRowTpl,
                    defaultbutton: {
                        text: 'Edit',
                        clickLinkTpl: this.urlPrefix + 'assignment/view/{id}'
                    },
                    menuitems: [{
                        text: 'Show deliveries',
                        clickFilter: 'type:delivery assignment:{id}'
                    }]
                }
            }, {
                xtype: 'searchresults',
                title: 'Assignment groups',
                store: Ext.data.StoreManager.lookup('devilry.apps.administrator.simplified.SimplifiedAssignmentGroupStoreSearch'),
                filterconfig: devilry.extjshelpers.searchwidget.FilterConfigDefaults.assignmentgroup,
                resultitemConfig: {
                    tpl: this.assignmentgroupRowTpl,
                    defaultbutton: {
                        text: 'Edit',
                        clickLinkTpl: this.urlPrefix + 'assignmentgroup/{id}'
                    }
                }
            }, {
                xtype: 'searchresults',
                title: 'Delivery',
                store: Ext.data.StoreManager.lookup('devilry.apps.administrator.simplified.SimplifiedDeliveryStoreSearch'),
                filterconfig: devilry.extjshelpers.searchwidget.FilterConfigDefaults.delivery,
                resultitemConfig: {
                    tpl: this.deliveryRowTpl
                }
            }]
        });
        this.callParent(arguments);
    }
});
<|endoftext|>


<commit_before>/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2013 VillageReach
 *
 *  This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
 *  You should have received a copy of the GNU Affero General Public License along with this program.  If not, see http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */

function ChildCoverageController($scope, $routeParams, distributionService) {

  $scope.distribution = distributionService.distribution;
  $scope.selectedFacilityId = $routeParams.facility;
  $scope.childCoverage = $scope.distribution.facilityDistributions[$scope.selectedFacilityId].childCoverage;

  var getValue = function (obj) {
    return (!isUndefined(obj)) ? ((!isUndefined(obj.value)) ? parseInt(obj.value, 10) : 0) : 0;
  };

  var syncNR = function (product1, product2) {
    if (!isUndefined($scope.openedVialMap[product2].openedVial))
      $scope.openedVialMap[product1].openedVial = {notRecorded: $scope.openedVialMap[product2].openedVial.notRecorded};
  };

  var convertListToMap = function (list, key) {
    var map = {};
    list.forEach(function (lineItem) {
      map[lineItem[key]] = lineItem;
    });
    return map;
  };

  $scope.childCoverageMap = convertListToMap($scope.childCoverage.childCoverageLineItems, 'vaccination');
  $scope.openedVialMap = convertListToMap($scope.childCoverage.openedVialLineItems, 'productVialName');

  $scope.columns = {
    vaccination: "label.child.vaccination.doses",
    targetGroup: "label.child.coverage.target.Group",
    childrenAgeGroup0To11: "label.children.age.group.zero.eleven.months",
    childrenAgeGroup12To23: "label.children.age.group.twelve.twenty.three.months",
    categoryOneHealthCenter: "label.coverage.health.center",
    categoryOneMobileBrigade: "label.coverage.outreach",
    categoryOneTotal: "label.child.coverage.first.total",
    coverageRate: "label.child.coverage.coverage.rate",
    categoryTwoHealthCenter: "label.coverage.health.center",
    categoryTwoMobileBrigade: "label.coverage.outreach",
    categoryTwoTotal: "label.child.coverage.first.total",
    totalVaccination: "label.child.coverage.total.vaccination",
    openedVials: "label.child.coverage.opened.vials",
    openedVialsWastageRate: "label.child.coverage.opened.vials.wastage.rate"
  };

  $scope.productsMap = {
    "BCG": {
      products: ['BCG'],
      vaccinations: ['BCG'],
      rowSpan: 1
    },
    "Polio (Newborn)": {
      products: ['Polio10', 'Polio20'],
      vaccinations: ['Polio (Newborn)', 'Polio 1st dose', 'Polio 2nd dose', 'Polio 3rd dose'],
      rowSpan: 4
    },
    "Penta 1st dose": {
      products: ['Penta1', 'Penta10'],
      vaccinations: ['Penta 1st dose', 'Penta 2nd dose', 'Penta 3rd dose'],
      rowSpan: 3
    },
    "PCV10 1st dose": {
      products: ['PCV'],
      vaccinations: ['PCV10 1st dose', 'PCV10 1st dose', 'PCV10 1st dose'],
      rowSpan: 3
    },
    "Measles": {
      products: ['Measles'],
      vaccinations: ['Measles'],
      rowSpan: 1
    }
  };

  $scope.hideCell = function (vaccination) {
    return Object.keys($scope.productsMap).indexOf(vaccination) === -1;
  };

  $scope.$watch("openedVialMap['Polio20'].openedVial.notRecorded", function () {
    syncNR('Polio10', 'Polio20');
  });

  $scope.$watch("openedVialMap['Penta10'].openedVial.notRecorded", function () {
    syncNR('Penta1', 'Penta10');
  });

  $scope.getTotal = function (obj1, obj2) {
    return getValue(obj1) + getValue(obj2);
  };

  $scope.getTotalVaccinations = function (childCoverageLineItem) {
    return $scope.getTotal(childCoverageLineItem.healthCenter11Months, childCoverageLineItem.outReach11Months) +
      $scope.getTotal(childCoverageLineItem.healthCenter23Months, childCoverageLineItem.outReach23Months);
  };

  $scope.calculateCoverageRate = function (total, targetGroup) {
    return (isUndefined(targetGroup) ? null : (targetGroup === 0 ? null : Math.round((total / targetGroup) * 100)));
  };

  $scope.calculateWastageRate = function (productsForVaccination) {
    var totalDosesConsumed = 0;
    var totalVaccinations = 0;
    if (!isUndefined(productsForVaccination)) {
      $.each(productsForVaccination.products, function (index, product) {
        var openedVialLineItem = $scope.openedVialMap[product];
        if (!isUndefined(openedVialLineItem.packSize) && !isUndefined(openedVialLineItem.openedVial) && !isUndefined(openedVialLineItem.openedVial.value)) {
          totalDosesConsumed += openedVialLineItem.packSize * openedVialLineItem.openedVial.value;
        }
      });

      $.each(productsForVaccination.vaccinations, function (index, vaccination) {
        var childCoverageLineItem = $scope.childCoverageMap[vaccination];
        totalVaccinations += $scope.getTotalVaccinations(childCoverageLineItem);
      });
    }
    return totalDosesConsumed === 0 ? null : Math.round(((totalDosesConsumed - totalVaccinations) / totalDosesConsumed) * 100);
  };

  $scope.applyNRAll = function () {
    distributionService.applyNR(function () {
      $scope.childCoverage.setNotRecorded();
    });
  };
}<commit_msg>|#00| +RahulK| fixing wastage rate calculation for PCV on child coverage screen<commit_after>/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2013 VillageReach
 *
 *  This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
 *  You should have received a copy of the GNU Affero General Public License along with this program.  If not, see http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */

function ChildCoverageController($scope, $routeParams, distributionService) {

  $scope.distribution = distributionService.distribution;
  $scope.selectedFacilityId = $routeParams.facility;
  $scope.childCoverage = $scope.distribution.facilityDistributions[$scope.selectedFacilityId].childCoverage;

  var getValue = function (obj) {
    return (!isUndefined(obj)) ? ((!isUndefined(obj.value)) ? parseInt(obj.value, 10) : 0) : 0;
  };

  var syncNR = function (product1, product2) {
    if (!isUndefined($scope.openedVialMap[product2].openedVial))
      $scope.openedVialMap[product1].openedVial = {notRecorded: $scope.openedVialMap[product2].openedVial.notRecorded};
  };

  var convertListToMap = function (list, key) {
    var map = {};
    list.forEach(function (lineItem) {
      map[lineItem[key]] = lineItem;
    });
    return map;
  };

  $scope.childCoverageMap = convertListToMap($scope.childCoverage.childCoverageLineItems, 'vaccination');
  $scope.openedVialMap = convertListToMap($scope.childCoverage.openedVialLineItems, 'productVialName');

  $scope.columns = {
    vaccination: "label.child.vaccination.doses",
    targetGroup: "label.child.coverage.target.Group",
    childrenAgeGroup0To11: "label.children.age.group.zero.eleven.months",
    childrenAgeGroup12To23: "label.children.age.group.twelve.twenty.three.months",
    categoryOneHealthCenter: "label.coverage.health.center",
    categoryOneMobileBrigade: "label.coverage.outreach",
    categoryOneTotal: "label.child.coverage.first.total",
    coverageRate: "label.child.coverage.coverage.rate",
    categoryTwoHealthCenter: "label.coverage.health.center",
    categoryTwoMobileBrigade: "label.coverage.outreach",
    categoryTwoTotal: "label.child.coverage.first.total",
    totalVaccination: "label.child.coverage.total.vaccination",
    openedVials: "label.child.coverage.opened.vials",
    openedVialsWastageRate: "label.child.coverage.opened.vials.wastage.rate"
  };

  $scope.productsMap = {
    "BCG": {
      products: ['BCG'],
      vaccinations: ['BCG'],
      rowSpan: 1
    },
    "Polio (Newborn)": {
      products: ['Polio10', 'Polio20'],
      vaccinations: ['Polio (Newborn)', 'Polio 1st dose', 'Polio 2nd dose', 'Polio 3rd dose'],
      rowSpan: 4
    },
    "Penta 1st dose": {
      products: ['Penta1', 'Penta10'],
      vaccinations: ['Penta 1st dose', 'Penta 2nd dose', 'Penta 3rd dose'],
      rowSpan: 3
    },
    "PCV10 1st dose": {
      products: ['PCV'],
      vaccinations: ['PCV10 1st dose', 'PCV10 2nd dose', 'PCV10 3rd dose'],
      rowSpan: 3
    },
    "Measles": {
      products: ['Measles'],
      vaccinations: ['Measles'],
      rowSpan: 1
    }
  };

  $scope.hideCell = function (vaccination) {
    return Object.keys($scope.productsMap).indexOf(vaccination) === -1;
  };

  $scope.$watch("openedVialMap['Polio20'].openedVial.notRecorded", function () {
    syncNR('Polio10', 'Polio20');
  });

  $scope.$watch("openedVialMap['Penta10'].openedVial.notRecorded", function () {
    syncNR('Penta1', 'Penta10');
  });

  $scope.getTotal = function (obj1, obj2) {
    return getValue(obj1) + getValue(obj2);
  };

  $scope.getTotalVaccinations = function (childCoverageLineItem) {
    return $scope.getTotal(childCoverageLineItem.healthCenter11Months, childCoverageLineItem.outReach11Months) +
      $scope.getTotal(childCoverageLineItem.healthCenter23Months, childCoverageLineItem.outReach23Months);
  };

  $scope.calculateCoverageRate = function (total, targetGroup) {
    return (isUndefined(targetGroup) ? null : (targetGroup === 0 ? null : Math.round((total / targetGroup) * 100)));
  };

  $scope.calculateWastageRate = function (productsForVaccination) {
    var totalDosesConsumed = 0;
    var totalVaccinations = 0;
    if (!isUndefined(productsForVaccination)) {
      $.each(productsForVaccination.products, function (index, product) {
        var openedVialLineItem = $scope.openedVialMap[product];
        if (!isUndefined(openedVialLineItem.packSize) && !isUndefined(openedVialLineItem.openedVial) && !isUndefined(openedVialLineItem.openedVial.value)) {
          totalDosesConsumed += openedVialLineItem.packSize * openedVialLineItem.openedVial.value;
        }
      });

      $.each(productsForVaccination.vaccinations, function (index, vaccination) {
        var childCoverageLineItem = $scope.childCoverageMap[vaccination];
        totalVaccinations += $scope.getTotalVaccinations(childCoverageLineItem);
      });
    }
    return totalDosesConsumed === 0 ? null : Math.round(((totalDosesConsumed - totalVaccinations) / totalDosesConsumed) * 100);
  };

  $scope.applyNRAll = function () {
    distributionService.applyNR(function () {
      $scope.childCoverage.setNotRecorded();
    });
  };
}<|endoftext|>


<commit_before>import React, {Component} from 'react';
import {Button, Checkbox, Field, Fields, Form, Input, Message} from 'stardust';

export default class FormValidatingOnBlurAndOtherEventsExample extends Component {
  formSettings = {
    inline: true,
    on: 'blur',
    fields: {
      'first-name': {
        identifier: 'first-name',
        rules: [
          {type: 'empty'}
        ],
      },
      'last-name': {
        identifier: 'last-name',
        rules: [
          {type: 'empty'}
        ],
      },
      'username': {
        identifier: 'username',
        rules: [
          {type: 'empty'}
        ],
      },
      'password': {
        identifier: 'password',
        rules: [
          {type: 'empty'},
          {type: 'minLength[6]'},
        ],
      },
      'terms': {
        identifier: 'terms',
        rules: [
          {type: 'checked'}
        ],
      },
    }
  }

  render() {
    return (
      <Form settings={this.formSettings} className='segment'>

Let's go ahead and get you signed up.

        <Fields evenlyDivided>
          <Field>
            Name
            <Input placeholder='First Name' name='first-name' type='text' />
          </Field>
          <Field>
            Name
            <Input placeholder='First Name' name='last-name' type='text' />
          </Field>
        </Fields>
        <Fields evenlyDivided>
          <Field label='Username'>
            <Input placeholder='Username' name='username' type='text' />
          </Field>
          <Field label='Password'>
            <Input type='password' name='password' />
          </Field>
        </Fields>
        <Field className='inline'>
          <Checkbox name='terms' className='hidden' label='I agree to the terms and conditions' />
        </Field>
        <Button className='blue submit'>Submit</Button>
        <Message className='error' />
      </Form>
    );
  }
}
<commit_msg>HOTFIX: doc site validation example label and placeholder name<commit_after>import React, {Component} from 'react';
import {Button, Checkbox, Field, Fields, Form, Input, Message} from 'stardust';

export default class FormValidatingOnBlurAndOtherEventsExample extends Component {
  formSettings = {
    inline: true,
    on: 'blur',
    fields: {
      'first-name': {
        identifier: 'first-name',
        rules: [
          {type: 'empty'}
        ],
      },
      'last-name': {
        identifier: 'last-name',
        rules: [
          {type: 'empty'}
        ],
      },
      'username': {
        identifier: 'username',
        rules: [
          {type: 'empty'}
        ],
      },
      'password': {
        identifier: 'password',
        rules: [
          {type: 'empty'},
          {type: 'minLength[6]'},
        ],
      },
      'terms': {
        identifier: 'terms',
        rules: [
          {type: 'checked'}
        ],
      },
    }
  }

  render() {
    return (
      <Form settings={this.formSettings} className='segment'>

Let's go ahead and get you signed up.

        <Fields evenlyDivided>
          <Field>
            First Name
            <Input placeholder='First Name' name='first-name' type='text' />
          </Field>
          <Field>
            Last Name
            <Input placeholder='Last Name' name='last-name' type='text' />
          </Field>
        </Fields>
        <Fields evenlyDivided>
          <Field label='Username'>
            <Input placeholder='Username' name='username' type='text' />
          </Field>
          <Field label='Password'>
            <Input type='password' name='password' />
          </Field>
        </Fields>
        <Field className='inline'>
          <Checkbox name='terms' className='hidden' label='I agree to the terms and conditions' />
        </Field>
        <Button className='blue submit'>Submit</Button>
        <Message className='error' />
      </Form>
    );
  }
}
<|endoftext|>


<commit_before>angular.module('starter.controllers', ['starter.services'])

.controller('AppCtrl', function($scope, $ionicModal, $timeout) {

  // Form data for the login modal
  $scope.loginData = {};

  // Create the login modal that we will use later
  $ionicModal.fromTemplateUrl('templates/login.html', {
    scope: $scope
  }).then(function(modal) {
    $scope.modal = modal;
  });

  // Triggered in the login modal to close it
  $scope.closeLogin = function() {
    $scope.modal.hide();
  };

  // Open the login modal
  $scope.login = function() {
    $scope.modal.show();
  };

  // Perform the login action when the user submits the login form
  $scope.doLogin = function() {
    console.log('Doing login', $scope.loginData);

    // Simulate a login delay. Remove this and replace with your login
    // code if using a login system
    $timeout(function() {
      $scope.closeLogin();
    }, 1000);
  };
})

.controller('ContactsCtrl', function(contactService, SOCKET_EVENTS, $scope) {

  var contacts = this;

  contacts.contacts = [];

  contactService.getContacts()
  .then(function(serverContacts) {

    contacts.contacts = serverContacts;

  });

  function updateData(resp) {
    switch (resp.verb) {
      case SOCKET_EVENTS.ADDED:
        console.log('element added', resp);
        contacts.contacts.push(resp.data);
        break;
      case SOCKET_EVENTS.UPDATED:
        console.log('element updated', resp);
        var id = parseInt(resp.id);
        var contactContainer = contacts.contacts.filter(function(c) {
          return c.id === id;
        });
        if (contactContainer){
          angular.merge(contactContainer[0], resp.data);
        }
        break;
      case SOCKET_EVENTS.REMOVED:
        console.log('element removed', resp);
        var id = parseInt(resp.id);
        var contactContainer = contacts.contacts.filter(function(c) {
          return c.id === id;
        });
        if (contactContainer){
          contacts.splice(indexOf(contactContainer[0]),1);
        }
        break;
      default:
        throw new Error('That event type is not recognized');
        break;
    }
  }

  contactService.bind(updateData);
})

.controller('ContactCtrl', function($stateParams, contactService) {
  var contact = this;
  contactService.getContact($stateParams.contactId)
    .then(function(resp) {
      contact.contact = resp;
    });

  function updateData(resp) {
    switch (resp.verb) {
      case SOCKET_EVENTS.ADDED:
        console.log('element added', resp);
        break;
      case SOCKET_EVENTS.UPDATED:
        console.log('element updated', resp);
        // TODO update contact
        break;
      case SOCKET_EVENTS.REMOVED:
        console.log('element removed', resp);
        // TODO removed contact from the list
        break;
      default:
        throw new Error('That event type is not recognized');
      break;
    }
  }

  contactService.bind(updateData);
});
<commit_msg>Fixed the app to update the views when a change happens on the server<commit_after>angular.module('starter.controllers', ['starter.services'])

.controller('AppCtrl', function($scope, $ionicModal, $timeout) {

  // Form data for the login modal
  $scope.loginData = {};

  // Create the login modal that we will use later
  $ionicModal.fromTemplateUrl('templates/login.html', {
    scope: $scope
  }).then(function(modal) {
    $scope.modal = modal;
  });

  // Triggered in the login modal to close it
  $scope.closeLogin = function() {
    $scope.modal.hide();
  };

  // Open the login modal
  $scope.login = function() {
    $scope.modal.show();
  };

  // Perform the login action when the user submits the login form
  $scope.doLogin = function() {
    console.log('Doing login', $scope.loginData);

    // Simulate a login delay. Remove this and replace with your login
    // code if using a login system
    $timeout(function() {
      $scope.closeLogin();
    }, 1000);
  };
})

.controller('ContactsCtrl', function(contactService, SOCKET_EVENTS, $scope) {

  var contacts = this;

  contacts.contacts = [];

  contactService.getContacts()
  .then(function(serverContacts) {

    contacts.contacts = serverContacts;

  });

  function updateData(resp) {
    switch (resp.verb) {
      case SOCKET_EVENTS.ADDED:
        console.log('element added', resp);
        contacts.contacts.push(resp.data);
        break;
      case SOCKET_EVENTS.UPDATED:
        console.log('element updated', resp);
        var id = parseInt(resp.id);
        var contactContainer = contacts.contacts.filter(function(c) {
          return c.id === id;
        });
        if (contactContainer){
          angular.merge(contactContainer[0], resp.data);
        }
        break;
      case SOCKET_EVENTS.REMOVED:
        console.log('element removed', resp);
        var id = parseInt(resp.id);
        var contactContainer = contacts.contacts.filter(function(c) {
          return c.id === id;
        });
        if (contactContainer){
          contacts.contacts.splice(contacts.contacts.indexOf(contactContainer[0]),1);
        }
        break;
      default:
        throw new Error('That event type is not recognized');
        break;
    }
    $scope.$apply();
  }

  contactService.bind(updateData);
})

.controller('ContactCtrl', function($stateParams, contactService) {
  var contact = this;
  contactService.getContact($stateParams.contactId)
    .then(function(resp) {
      contact.contact = resp;
    });

  function updateData(resp) {
    switch (resp.verb) {
      case SOCKET_EVENTS.ADDED:
        console.log('element added', resp);
        break;
      case SOCKET_EVENTS.UPDATED:
        console.log('element updated', resp);
        // TODO update contact
        break;
      case SOCKET_EVENTS.REMOVED:
        console.log('element removed', resp);
        // TODO removed contact from the list
        break;
      default:
        throw new Error('That event type is not recognized');
      break;
    }
  }

  contactService.bind(updateData);
});
<|endoftext|>


<commit_before>var version = '18-02-01';
var piecePawn = 0x01;
var pieceKnight = 0x02;
var pieceBishop = 0x03;
var pieceRook = 0x04;
var pieceQueen = 0x05;
var pieceKing = 0x06;
var colorBlack = 0x08;
var colorWhite = 0x10;
var colorEmpty = 0x20;
var moveflagPassing = 0x02 << 16;
var moveflagCastleKing = 0x04 << 16;
var moveflagCastleQueen = 0x08 << 16;
var moveflagPromotion = 0xf0 << 16;
var moveflagPromoteQueen = 0x10 << 16;
var moveflagPromoteRook  = 0x20 << 16;
var moveflagPromoteBishop = 0x40 << 16;
var moveflagPromoteKnight = 0x80 << 16;
var maskCastle = moveflagCastleKing | moveflagCastleQueen;
var maskColor = colorBlack | colorWhite;
var g_captured = 0;
var g_castleRights = 0xf;
var g_depth = 0;
var g_hash = 0;
var g_passing = 0;
var g_move50 = 0;
var g_moveNumber = 0;
var g_pv = '';
var g_phase = 32;
var g_totalNodes = 0;
var g_startTime = 0;
var g_inCheck = false;
var g_depthout = 0;
var g_timeout = 0;
var g_nodeout = 0;
var g_stop = false;
var g_scoreFm = '';
var g_lastCastle = 0;
var adjInsufficient = false;
var adjMobility = 0;
var g_countMove = 0;
var undoStack = [];
var undoIndex = 0;
var arrField = [];
var g_board = new Array(256);
var g_hashBoard =  new Array(256);
var boardCheck = new Array(256);
var boardCastle = new Array(256);
var whiteTurn = 1;
var usColor = 0;
var enColor = 0;
var eeColor = 0;
var tmpMaterial = [[],[171,240],[764,848],[826,891],[1282,1373],[2526,2646],[0xffff,0xffff]];
var arrMaterial = new Array(32);
var tmpMobility = [[],[],
[[-75,-76],[-57,-54],[-9,-28],[-2,-10],[6,5],[14,12],[22, 26],[29,29],[36, 29]],//knight
[[-48,-59],[-20,-23],[16, -3],[26, 13],[38, 24],[51, 42],[55, 54],[63, 57],[63, 65],[68, 73],[81, 78],[81, 86],[91, 88],[98, 97]],//bishop
[[-58,-76],[-27,-18],[-15, 28],[-10, 55],[-5, 69],[-2, 82],[9,112],[16,118],[30,132],[29,142],[32,155],[38,165],[46,166],[48,169],[58,171]],//rook
[[-39,-36],[-21,-15],[3,  8],[3, 18],[14, 34],[22, 54],[28, 61],[41, 73],[43, 79],[48, 92],[56, 94],[60,104],[60,113],[66,120],[67,123],[70,126],[71,133],[73,136],[79,140],[88,143],[88,148],[99,166],[102,170],[102,175],[106,184],[109,191],[113,206],[116,212]],//queen
[[90,9],[80,8],[70,7],[60,6],[50,5],[40,4],[30,3],[20,2],[10,1]]];//king
var arrMobility = new Array(32);

function RAND_32(){
return (Math.floor(Math.random() * 0x10000) << 16) | Math.floor(Math.random() * 0x10000);
}

function StrToSquare(s){
var fl = {a:0, b:1, c:2, d:3, e:4,f:5, g:6, h:7};
var x = fl[s.charAt(0)];
var y = 12 - parseInt(s.charAt(1));
return (x + 4) | (y << 4);
}

function FormatSquare(square){
return ['a','b','c','d','e','f','g','h'][(square & 0xf) - 4] + (12 - (square >>4));
}

function FormatMove(move){
var result = FormatSquare(move & 0xFF) + FormatSquare((move >> 8) & 0xFF);
if (move & moveflagPromotion){
	if (move & moveflagPromoteQueen) result += 'q';
	else if (move & moveflagPromoteRook) result += 'r';
	else if (move & moveflagPromoteBishop) result += 'b';
	else result += 'n';
}
return result;
}

function GetMoveFromString(moveString) {
var moves = GenerateAllMoves(whiteTurn,false);
for (var i = 0; i < moves.length; i++){
	if (FormatMove(moves[i]) == moveString)
		return moves[i];
}
}

function Initialize(){
g_hash = RAND_32();
arrField = [];
for(var y = 0;y < 8; y++)
	for(var x = 0;x < 8;x++)
		arrField.push((y + 4) * 16 + x + 4);
for(var n = 0; n < 256; n++){
	boardCheck[n] = 0;
	boardCastle[n]=15;
	g_board[n] = 0;
	g_hashBoard[n] = new Array(16);
	for(var p = 0;p < 16;p++)
		g_hashBoard[n][p] = RAND_32();
}
for(var n = 0;n < 6;n++){
	boardCastle[[68,72,75,180,184,187][n]] = [7,3,11,13,12,14][n];
	boardCheck[[71,72,73,183,184,185][n]] = [colorBlack | moveflagCastleQueen,colorBlack | maskCastle,colorBlack | moveflagCastleKing,colorWhite | moveflagCastleQueen,colorWhite | maskCastle,colorWhite | moveflagCastleKing][n];
}
for(var ph = 2;ph < 33;ph++){
	arrMaterial[ph] = new Array(7);
	arrMobility[ph] = new Array(7);
	var f = ph / 32;
	for(var p = 1;p < 7;p++){
		arrMaterial[ph][p] = Math.floor(tmpMaterial[p][0] * f + tmpMaterial[p][1] * (1 - f));
		arrMobility[ph][p] = new Array(tmpMobility[p].length);
		for(var n = 0;n < tmpMobility[p].length;n++)
			arrMobility[ph][p][n] = Math.floor(tmpMobility[p][n][0] * f + tmpMobility[p][n][1] * (1 - f));
	}
}
}

function InitializeFromFen(fen){
g_phase = 0;
for(var n = 0;n < 64;n++)
	g_board[arrField[n]] = colorEmpty;
if(!fen)fen = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1';
var chunks = fen.split(' ');
var row = 0;
var col = 0;
var pieces = chunks[0];
for (var i = 0; i < pieces.length; i++){
	var c = pieces.charAt(i);
	if (c == '/') {
		row++;
		col = 0;
	}else if(c >= '0' && c <= '9') {
		for (var j = 0; j < parseInt(c); j++)
			col++;
	}else{
		g_phase++;
		var b = c.toLowerCase();
		var isWhite = b != c;
		var piece = isWhite ? colorWhite : colorBlack;
		var index = (row + 4) * 16 + col + 4;
		switch(b){
			case 'p':
				piece |= piecePawn;
			break;
			case 'b':
				piece |= pieceBishop;
			break;
			case 'n':
				piece |= pieceKnight;
			break;
			case 'r':
				piece |= pieceRook;
			break;
			case 'q':
				piece |= pieceQueen;
			break;
			case 'k':
				piece |= pieceKing;
			break;
		}
		g_board[index] = piece;
		col++;
	}
}
whiteTurn = chunks[1].charAt(0) == 'w' | 0;
g_castleRights = 0;
if (chunks[2].indexOf('K') != -1)
	g_castleRights |= 1;
if (chunks[2].indexOf('Q') != -1)
	g_castleRights |= 2;
if (chunks[2].indexOf('k') != -1)
	g_castleRights |= 4;
if (chunks[2].indexOf('q') != -1)
	g_castleRights |= 8;
g_passing = 0;
if (chunks[3].indexOf('-') == -1)
	g_passing = StrToSquare(chunks[3]);
g_move50 = parseInt(chunks[4]);
g_moveNumber = parseInt(chunks[5]);
if(g_moveNumber)g_moveNumber--;
g_moveNumber *= 2;
if(!whiteTurn)g_moveNumber++;
undoStack=[];
for(undoIndex = 0;undoIndex  <= g_moveNumber;undoIndex++)
	undoStack[undoIndex] = new cUndo();
}

function IsRepetition(){
for(var n = undoIndex - 4;n >= undoIndex - g_move50;n -= 2)
	if(undoStack[n].hash == g_hash)
		return true;
return false;
}

function GenerateMove(moveStack,fr,to,add,flags){
g_countMove++;
if(((g_board[to] & 7) == pieceKing) || (((boardCheck[to] & g_lastCastle) == g_lastCastle) && g_lastCastle & maskCastle))
	g_inCheck = true;
else if(add)
	moveStack[moveStack.length] = fr | (to << 8) | flags;
}

function GenerateAllMoves(wt,attack){
adjMobility = 0;
g_inCheck = false;
usColor = wt ?  colorWhite : colorBlack;
enColor = wt ? colorBlack : colorWhite;
eeColor = enColor | colorEmpty;
var pieceM = 0;
var pieceN = 0;
var pieceB = 0;
var moves = [];
for(var n = 0;n < 64;n++){
	var fr = arrField[n];
	var f = g_board[fr];
	if(f & usColor)f &= 7;else continue;
	g_countMove = 0;
	adjMobility += arrMaterial[g_phase][f];
	switch(f){
		case 1:
		pieceM++;
		var del = wt ? -16 : 16;
		var to = fr + del;
		if(g_board[to] & colorEmpty){
			GeneratePwnMoves(moves,fr,to,!attack)
			if(!g_board[fr-del-del] && g_board[to + del] & colorEmpty)
				GeneratePwnMoves(moves,fr,to + del,!attack);
		}
		if(g_board[to - 1] & enColor)GeneratePwnMoves(moves,fr,to - 1,true);
		else if((to - 1) == g_passing)GeneratePwnMoves(moves,fr,g_passing,true,moveflagPassing);
		else if(g_board[to - 1] & colorEmpty)GeneratePwnMoves(moves,fr,to - 1,false);
		if(g_board[to + 1] & enColor)GeneratePwnMoves(moves,fr,to + 1,true);
		else if((to + 1) == g_passing)GeneratePwnMoves(moves,fr,g_passing,true,moveflagPassing);
		else if(g_board[to + 1] & colorEmpty)GeneratePwnMoves(moves,fr,to + 1,false);
		break;
		case 2:
		pieceN++;
		GenerateShrMoves(moves,attack,fr,[14,-14,18,-18,31,-31,33,-33]);
		adjMobility += arrMobility[g_phase][f][g_countMove];
		break;
		case 3:
		pieceB++;
		GenerateStdMoves(moves,attack,fr,[15,-15,17,-17]);
		adjMobility += arrMobility[g_phase][f][g_countMove];
		break;
		case 4:
		pieceM++;
		GenerateStdMoves(moves,attack,fr,[1,-1,16,-16]);
		adjMobility += arrMobility[g_phase][f][g_countMove];
		break;
		case 5:
		pieceM++;
		GenerateStdMoves(moves,attack,fr,[1,-1,15,-15,16,-16,17,-17]);
		adjMobility += arrMobility[g_phase][f][g_countMove];
		break;
		case 6:
		GenerateShrMoves(moves,attack,fr,[1,-1,15,-15,16,-16,17,-17]);
		var cr = wt ? g_castleRights : g_castleRights >> 2;
		if (cr & 1)
			if(g_board[fr + 1] & colorEmpty && g_board[fr + 2] & colorEmpty)
				GenerateMove(moves,fr,fr + 2,true,moveflagCastleKing);
		if (cr & 2)
			if(g_board[fr - 1] & colorEmpty && g_board[fr - 2] & colorEmpty && g_board[fr - 3] & colorEmpty)
				GenerateMove(moves,fr,fr - 2,true,moveflagCastleQueen);
		adjMobility += arrMobility[g_phase][f][g_countMove];
		break;
	}
}
adjInsufficient = (!pieceM) && (pieceN + (pieceB << 1) < 3);
if(!(pieceN | pieceB | pieceM))
	adjMobility -= 64;
if(pieceB > 1)
	adjMobility += 64;
return moves;
}

function GeneratePwnMoves(moves,fr,to,add,flag){
var y = to >> 4;
if (((y == 4) || (y == 11)) && add){
	GenerateMove(moves,fr,to,add,moveflagPromoteQueen);
	GenerateMove(moves,fr,to,add,moveflagPromoteRook);
	GenerateMove(moves,fr,to,add,moveflagPromoteBishop);
	GenerateMove(moves,fr,to,add,moveflagPromoteKnight);
}else
	GenerateMove(moves,fr,to,add,flag);
}

function GenerateShrMoves(moves,attack,fr,dir){
for(var n = 0;n < dir.length;n++){
	var to = fr + dir[n];
	if(g_board[to] & colorEmpty)
		GenerateMove(moves,fr,to,!attack);
	else if(g_board[to] & enColor)
		GenerateMove(moves,fr,to,true);
}
}

function GenerateStdMoves(moves,attack,fr,dir){
for(var n=0;n<dir.length;n++){
	var to = fr + dir[n];
	while (g_board[to] & colorEmpty){
		GenerateMove(moves,fr,to,!attack);
		to += dir[n];
	}
	if (g_board[to] & enColor)
		GenerateMove(moves,fr,to,true);
}
}

function MakeMove(move){
var fr = move & 0xFF;
var to = (move >> 8) & 0xFF;
var flags = move & 0xFF0000;
var piecefr = g_board[fr];
var piece = piecefr & 0xf;
var capi = to;
g_captured = g_board[to];
g_lastCastle = (move & maskCastle) | (piecefr & maskColor);
if(flags & moveflagCastleKing){
	g_board[to - 1] =  g_board[to + 1];
	g_board[to + 1] = colorEmpty;
}else if(flags & moveflagCastleQueen){
	g_board[to + 1] = rook = g_board[to - 2];
	g_board[to - 2] = colorEmpty;
}else if(flags & moveflagPassing){
	capi = whiteTurn ? to + 16 : to - 16;
	g_captured = g_board[capi];
	g_board[capi]=colorEmpty;
}
undoStack[undoIndex++] = new cUndo();
g_hash ^= g_hashBoard[fr][piece];
g_passing = 0;
var capturedType = g_captured & 0xF;
if(capturedType){
	g_move50 = 0;
	g_phase--;
}else if((piece & 7) == piecePawn) {
	if(to == (fr + 32))g_passing = (fr + 16);
	if(to == (fr - 32))g_passing = (fr - 16);
	g_move50 = 0;
}else
	g_move50++;
if (flags & moveflagPromotion){
	var newPiece = piecefr & (~0x7);
	if (flags & moveflagPromoteKnight)
		newPiece |= pieceKnight;
	else if (flags & moveflagPromoteQueen)
		newPiece |= pieceQueen;
	else if (flags & moveflagPromoteBishop)
		newPiece |= pieceBishop;
	else
		newPiece |= pieceRook;
	g_board[to] = newPiece;
	g_hash ^= g_hashBoard[to][newPiece & 7];
}else{
	g_board[to] = g_board[fr];
	g_hash ^= g_hashBoard[to][piece];
}
g_board[fr] = colorEmpty;
g_castleRights &= boardCastle[fr] & boardCastle[to];
whiteTurn ^= 1;
g_moveNumber++;
}

function UnmakeMove(move){
var fr = move & 0xFF;
var to = (move >> 8) & 0xFF;
var flags = move & 0xFF0000;
var piece = g_board[to];
var capi = to;
var undo = undoStack[--undoIndex];
g_passing = undo.passing;
g_castleRights = undo.castle;
g_move50 = undo.move50;
g_lastCastle = undo.lastCastle;
g_hash = undo.hash;
var captured = undo.captured;
if (flags & moveflagCastleKing) {
	g_board[to + 1] = g_board[to - 1];
	g_board[to - 1] = colorEmpty;
}else if (flags & moveflagCastleQueen){
	g_board[to - 2] = g_board[to + 1];
	g_board[to + 1] = colorEmpty;
}
if (flags & moveflagPromotion) {
	piece = (g_board[to] & (~0x7)) | piecePawn;
	g_board[fr] = piece;
}else g_board[fr] = g_board[to];
if(flags & moveflagPassing){
	capi = whiteTurn ? to - 16 : to + 16;
	g_board[to] = colorEmpty;
}
g_board[capi] = captured;
if(captured & 7)
	g_phase++;
whiteTurn ^= 1;
g_moveNumber--;
}

var bsIn = -1;
var bsFm = '';
var bsPv = '';

function Quiesce(mu,depth,depthL,alpha,beta,score){
var myMobility = adjMobility;
var n = mu.length;;
var alphaDe = 0;
var alphaFm = '';
var alphaPv = '';
if(alpha < score)
	alpha = score;
if(alpha >= beta)
	alpha = score;
else while(n--){
	if(!(++g_totalNodes & 0x1fff))
		g_stop = ((g_timeout && (Date.now() - g_startTime > g_timeout)) ||  (g_nodeout && (g_totalNodes > g_nodeout)));
	var cm = mu[n];
	MakeMove(cm);
	var me = GenerateAllMoves(whiteTurn,true);
	var osScore = myMobility - adjMobility;
	g_depth = 0;
	g_pv = '';
	if(g_inCheck)
		osScore = -0xffff;
	else if(depth < depthL)
		osScore = -Quiesce(me,depth + 1,depthL,-beta,-alpha,-osScore);
	UnmakeMove(cm);
	if(g_stop)return -0xffff;
	if(alpha < osScore){
		alpha = osScore;
		alphaDe = g_depth + 1;
		alphaFm = FormatMove(cm);
		alphaPv = alphaFm + ' ' + g_pv;
	}
	if(alpha >= beta)break;
}
g_depth = alphaDe;
g_pv = alphaPv;
return alpha;
}

function GetScore(mu,depth,depthL,alpha,beta){
var myInsufficient = adjInsufficient;
var myMobility = adjMobility;
var check = 0;
var n = mu.length;;
var myMoves = n;
var alphaDe = 0;
var alphaFm = '';
var alphaPv = '';
while(n--){
	if(!(++g_totalNodes & 0x1fff))
		g_stop = ((depthL > 1) && ((g_timeout && (Date.now() - g_startTime > g_timeout)) ||  (g_nodeout && (g_totalNodes > g_nodeout))));
	var cm = mu[n];
	MakeMove(cm);
	var me = GenerateAllMoves(whiteTurn,depth == depthL);
	g_depth = 0;
	g_pv = '';
	var osScore = myMobility - adjMobility;
	if(g_inCheck){
		myMoves--;
		osScore = -0xffff;
	}else if((g_move50 > 99) || IsRepetition() || ((myInsufficient  || osScore < 0 ) && adjInsufficient))
		osScore = 0;
	else if(depth < depthL)
		osScore = -GetScore(me,depth + 1,depthL,-beta,-alpha);
	else
		osScore =  -Quiesce(me,1,depthL,-beta,-alpha,-osScore);
	UnmakeMove(cm);
	if(g_stop)return -0xffff;
	if(alpha < osScore){
		alpha = osScore;
		alphaFm = FormatMove(cm);
		alphaPv = alphaFm + ' ' + g_pv;
		alphaDe = g_depth + 1;
		if(depth == 1){
			if(osScore > 0xf000)
				g_scoreFm = 'mate ' + ((0xffff - osScore) >> 1);
			else if(osScore < -0xf000)
				g_scoreFm = 'mate ' + ((-0xfffe - osScore) >> 1);
			else
				g_scoreFm = 'cp ' + (osScore >> 2);
			bsIn = n;
			bsFm = alphaFm;
			bsPv = alphaPv;
			var time = Date.now() - g_startTime;
			var nps = Math.floor((g_totalNodes / time) * 1000);
			postMessage('info currmove ' + bsFm + ' currmovenumber ' + n + ' nodes ' + g_totalNodes + ' time ' + time + ' nps ' + nps + ' depth ' + g_depthout + ' seldepth ' + alphaDe + ' score ' + g_scoreFm + ' pv ' + bsPv);
		}
	}
	if(alpha >= beta)break;
}
if(!myMoves){
	GenerateAllMoves(whiteTurn ^ 1,true);
	if(!g_inCheck)alpha = 0;else alpha = -0xffff + depth;
}
g_depth = alphaDe;
g_pv = alphaPv;
return alpha;
}

function Search(depth,time,nodes){
var mu = GenerateAllMoves(whiteTurn,false);
var myInsufficient = adjInsufficient;
var myMobility = adjMobility;
var m1 = mu.length - 1;
g_stop = false;
g_totalNodes = 0;
g_depthout = depth ? depth : 1;
g_timeout = time;
g_nodeout = nodes;
do{
	bsIn = m1;
	adjInsufficient = myInsufficient;
	adjMobility = myMobility;
	var os = GetScore(mu,1,g_depthout,-0xffff,0xffff);
	if(bsIn != m1){
		var m = mu[m1];
		mu[m1] = mu[bsIn];
		mu[bsIn] = m;
	}
	if((g_depth < g_depthout++) || (os < - 0xf000) || (os > 0xf000))break;
}while((!depth || (g_depthout < depth)) && !g_stop && m1);
var time = Date.now() - g_startTime;
var nps = Math.floor((g_totalNodes / time) * 1000);
var ponder = bsPv.split(' ');
var pm = ponder.length > 1 ? ' ponder ' + ponder[1] : '';
postMessage('info nodes ' + g_totalNodes + ' time ' + time + ' nps ' + nps);
postMessage('bestmove ' + bsFm + pm);
return true;
}

var cUndo = function(){
this.captured = g_captured;
this.hash = g_hash;
this.passing = g_passing;
this.castle = g_castleRights;
this.move50 = g_move50;
this.lastCastle = g_lastCastle;
}

Initialize();

function GetNumber(msg,re,def){
var r = re.exec(msg);
return r ? r[1] | 0 : def;
}

onmessage = function(e){
(/^(.*?)\n?$/).exec(e.data);
var msg = RegExp.$1;
if(msg == 'uci'){
	postMessage('id name Rapsimple ' + version);
	postMessage('id author Thibor Raven');
	postMessage('uciok');
}else if (msg == 'isready') postMessage('readyok');
else if ((/^position (?:(startpos)|fen (.*?))\s*(?:moves\s*(.*))?$/).exec(msg)){
	InitializeFromFen((RegExp.$1 == 'startpos') ? '' : RegExp.$2);
	if(RegExp.$3){
		var m =  (RegExp.$3).split(' ');
		for(var i = 0;i < m.length;i++)
			MakeMove(GetMoveFromString(m[i]));
	}
}else if((/^go /).exec(msg)){
	g_startTime = Date.now();
	var t = GetNumber(msg,/movetime (\d+)/,0);
	var d = GetNumber(msg,/depth (\d+)/,0);
	var n = GetNumber(msg,/nodes (\d+)/,0);
	if(!t && !d && !n){
		var ct = whiteTurn ? GetNumber(msg,/wtime (\d+)/,0) : GetNumber(msg,/btime (\d+)/,0);
		var ci = whiteTurn ? GetNumber(msg,/winc (\d+)/,0) : GetNumber(msg,/binc (\d+)/,0);
		var mg = GetNumber(msg,/movestogo (\d+)/,32);
		t = Math.floor(ct / mg) + ci - 0xff;
	}
	Search(d,t,n);
}
}
<commit_msg>Delete rapsimple.js<commit_after><|endoftext|>


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

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// `another-raw-example.js`
//
// This is ANOTHER example demonstrating how to use Waterline
// from a vanilla Node.js script.
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// Import dependencies
var util = require('util');
var _ = require('@sailshq/lodash');
var setupWaterline = require('./bootstrap');
var SailsDiskAdapter = require('sails-disk');

// Set up Waterline.
setupWaterline({

  adapters: {

    'sails-disk': SailsDiskAdapter

  },

  datastores: {

    myDb: {
      adapter: 'sails-disk'
    }

  },

  models: {

    user: {
      // connection: 'myDb',//<< the datastore this model should use
      datastore: 'myDb',// (^^^TODO: change this to `datastore` once it works)

      attributes: {
        id: { type: 'number' },
        numChickens: { type: 'number' },
        pets: { collection: 'pet' }
      },
      primaryKey: 'id',
      schema: true
    },

    pet: {
      // connection: 'myDb',//<< the datastore this model should use
      datastore: 'myDb',// (^^^TODO: change this to `datastore` once it works)

      attributes: {
        id: { type: 'number' },
        name: { type: 'string' }
      },
      primaryKey: 'id',
      schema: true
    }

  }

}, function waterlineReady (err, ontology) {
  if (err) {
    console.error('Could not set up Waterline: '+err.stack);
    return;
  }//--•

  // // Our model definitions
  // console.log(
  //   '\n'+
  //   '\n'+
  //   '==========================================================================\n'+
  //   '• Model definitions:                                                     •\n'+
  //   '==========================================================================\n',
  //   ontology.models
  // );
  // //
  // // e.g.
  // // models.user.find().exec(...)
  // // models.user.find().exec(...)

  // // Our datastore definitions
  // console.log(
  //   '\n'+
  //   '\n'+
  //   '==========================================================================\n'+
  //   '• Datastore definitions:                                                 •\n'+
  //   '==========================================================================\n',
  //   ontology.datastores
  // );
  // //
  // // e.g.
  // // datastores.myDb.config;

  console.log();
  console.log();
  console.log('--');
  console.log('Waterline is ready.');
  console.log('(this is where you could write come code)');

  // Now more example stuff.
  console.log(
    '\n'+
    '\n'+
    '==========================================================================\n'+
    '• EXAMPLE: Calling some model methods:                                   •\n'+
    '==========================================================================\n'
  );

  var Pet = ontology.models.pet;
  var User = ontology.models.user;

  // User.addToCollection([], 'chickens', [], function (err){
  //   if (err) {
  //     console.error(err.stack);
  //     return;
  //   }//--•

  //   console.log('k');

  // });

  // User.removeFromCollection([], 'chickens', [], function (err){
  //   if (err) {
  //     console.error(err.stack);
  //     return;
  //   }//--•

  //   console.log('k');

  // });

  // User.replaceCollection([], 'chickens', [], function (err){
  //   if (err) {
  //     console.error(err.stack);
  //     return;
  //   }//--•

  //   console.log('k');

  // });

  // User.sum('pets', {}, function (err, sum){
  //   if (err) {
  //     console.error('Uhoh:',err.stack);
  //     return;
  //   }//--•

  //   console.log('got '+sum);

  // });

  // User.stream({}, function eachRecord(user, next){

  //   console.log('Record:',user);
  //   return next();

  // }, function (err){
  //   if (err) {
  //     console.error('Uhoh:',err.stack);
  //     return;
  //   }//--•

  //   console.log('k');

  // });//</ User.stream() >

  Pet.createEach([
    { name: 'Rover' },
    { name: 'Samantha' }
  ]).exec(function (err, pets) {
    if (err) {
      console.log('Failed to create pets:', err);
      return;
    }

    User.create({
      numChickens: 74,
      pets: _.pluck(pets, 'id')
    }).exec(function (err) {
      if (err) {
        console.log('Failed to create records:',err);
        return;
      }

      // User.find({
      //   // select: ['*'],
      //   where: {},
      //   limit: 10,
      //   // limit: (Number.MAX_SAFE_INTEGER||9007199254740991),
      //   skip: 0,
      //   sort: 'id asc',
      //   // sort: {},
      //   // sort: [
      //   //   { name: 'ASC' }
      //   // ]
      // })
      // .populate('pets')
      // .exec(function (err, records) {
      //   if (err) {
      //     console.log('Failed to find records:',err);
      //     return;
      //   }

      //   console.log('found:',records);

      // });

      User.stream({
        select: ['*'],
        where: {},
        limit: 10,
        // limit: (Number.MAX_SAFE_INTEGER||9007199254740991),
        skip: 0,
        sort: 'id asc',
        // sort: {},
        // sort: [
        //   { name: 'ASC' }
        // ]
      }, function eachRecord(user, next){

        console.log('Record:',util.inspect(user,{depth: null}));
        return next();

      }, {
        populates: {

          pets: {
            select: ['*'],
            where: {},
            limit: 100000,
            skip: 0,
            sort: 'id asc',
          }

        }
      }, function (err){
        if (err) {
          console.error('Uhoh:',err.stack);
          return;
        }//--•

        console.log('k');

      });//</ User.stream().exec() >

    });//</ User.create().exec() >
  });//</ Pet.createEach().exec() >

});

<commit_msg>Remove no-longer-relevant TODO from 'another-raw-example.js'.<commit_after>#!/usr/bin/env node

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// `another-raw-example.js`
//
// This is ANOTHER example demonstrating how to use Waterline
// from a vanilla Node.js script.
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// Import dependencies
var util = require('util');
var _ = require('@sailshq/lodash');
var setupWaterline = require('./bootstrap');
var SailsDiskAdapter = require('sails-disk');

// Set up Waterline.
setupWaterline({

  adapters: {

    'sails-disk': SailsDiskAdapter

  },

  datastores: {

    myDb: {
      adapter: 'sails-disk'
    }

  },

  models: {

    user: {
      datastore: 'myDb',

      attributes: {
        id: { type: 'number' },
        numChickens: { type: 'number' },
        pets: { collection: 'pet' }
      },
      primaryKey: 'id',
      schema: true
    },

    pet: {
      datastore: 'myDb',

      attributes: {
        id: { type: 'number' },
        name: { type: 'string' }
      },
      primaryKey: 'id',
      schema: true
    }

  }

}, function waterlineReady (err, ontology) {
  if (err) {
    console.error('Could not set up Waterline: '+err.stack);
    return;
  }//--•

  // // Our model definitions
  // console.log(
  //   '\n'+
  //   '\n'+
  //   '==========================================================================\n'+
  //   '• Model definitions:                                                     •\n'+
  //   '==========================================================================\n',
  //   ontology.models
  // );
  // //
  // // e.g.
  // // models.user.find().exec(...)
  // // models.user.find().exec(...)

  // // Our datastore definitions
  // console.log(
  //   '\n'+
  //   '\n'+
  //   '==========================================================================\n'+
  //   '• Datastore definitions:                                                 •\n'+
  //   '==========================================================================\n',
  //   ontology.datastores
  // );
  // //
  // // e.g.
  // // datastores.myDb.config;

  console.log();
  console.log();
  console.log('--');
  console.log('Waterline is ready.');
  console.log('(this is where you could write come code)');

  // Now more example stuff.
  console.log(
    '\n'+
    '\n'+
    '==========================================================================\n'+
    '• EXAMPLE: Calling some model methods:                                   •\n'+
    '==========================================================================\n'
  );

  var Pet = ontology.models.pet;
  var User = ontology.models.user;

  // User.addToCollection([], 'chickens', [], function (err){
  //   if (err) {
  //     console.error(err.stack);
  //     return;
  //   }//--•

  //   console.log('k');

  // });

  // User.removeFromCollection([], 'chickens', [], function (err){
  //   if (err) {
  //     console.error(err.stack);
  //     return;
  //   }//--•

  //   console.log('k');

  // });

  // User.replaceCollection([], 'chickens', [], function (err){
  //   if (err) {
  //     console.error(err.stack);
  //     return;
  //   }//--•

  //   console.log('k');

  // });

  // User.sum('pets', {}, function (err, sum){
  //   if (err) {
  //     console.error('Uhoh:',err.stack);
  //     return;
  //   }//--•

  //   console.log('got '+sum);

  // });

  // User.stream({}, function eachRecord(user, next){

  //   console.log('Record:',user);
  //   return next();

  // }, function (err){
  //   if (err) {
  //     console.error('Uhoh:',err.stack);
  //     return;
  //   }//--•

  //   console.log('k');

  // });//</ User.stream() >

  Pet.createEach([
    { name: 'Rover' },
    { name: 'Samantha' }
  ]).exec(function (err, pets) {
    if (err) {
      console.log('Failed to create pets:', err);
      return;
    }

    User.create({
      numChickens: 74,
      pets: _.pluck(pets, 'id')
    }).exec(function (err) {
      if (err) {
        console.log('Failed to create records:',err);
        return;
      }

      // User.find({
      //   // select: ['*'],
      //   where: {},
      //   limit: 10,
      //   // limit: (Number.MAX_SAFE_INTEGER||9007199254740991),
      //   skip: 0,
      //   sort: 'id asc',
      //   // sort: {},
      //   // sort: [
      //   //   { name: 'ASC' }
      //   // ]
      // })
      // .populate('pets')
      // .exec(function (err, records) {
      //   if (err) {
      //     console.log('Failed to find records:',err);
      //     return;
      //   }

      //   console.log('found:',records);

      // });

      User.stream({
        select: ['*'],
        where: {},
        limit: 10,
        // limit: (Number.MAX_SAFE_INTEGER||9007199254740991),
        skip: 0,
        sort: 'id asc',
        // sort: {},
        // sort: [
        //   { name: 'ASC' }
        // ]
      }, function eachRecord(user, next){

        console.log('Record:',util.inspect(user,{depth: null}));
        return next();

      }, {
        populates: {

          pets: {
            select: ['*'],
            where: {},
            limit: 100000,
            skip: 0,
            sort: 'id asc',
          }

        }
      }, function (err){
        if (err) {
          console.error('Uhoh:',err.stack);
          return;
        }//--•

        console.log('k');

      });//</ User.stream().exec() >

    });//</ User.create().exec() >
  });//</ Pet.createEach().exec() >

});

<|endoftext|>


<commit_before>
var ryver = require('ryver');
var p = require('path');
fs = require('fs.extra');

var eventEC = ryver.eventEC;

eventEC.onCollect( 'filter', function( cb ){

  var f = function( fileData, cb ){

    var landing = fileData.info.landing;

    if( ! landing ){
      ryver.log("No landing set in fileInfo, skipping");
      return cb( null, fileData );
    }

    var source;

    var mainPath = fileData.system.filePath;
    var backupPath = p.join( ryver.getSrc(), ( ryver.getConfig().includesFolder || '_includes' ) );

    // Load the contents of the landing file
    ryver.readFile( mainPath, backupPath, landing, function( err, landingContentsAsBuffer, usedBackup ){
      if( err ) return cb( err );

      // Make a new fileData based on:
      //  * the file's own path, name
      //  * the landing's extension
      //  * the landing file's contents
      //  * the directory's initial info
      var s = fileData.system;
      var landingExt = '.' + fileData.info.landing.split('.').pop();
      ryver.makeFileData( s.filePath, s.fileName, landingExt, landingContentsAsBuffer, ryver.cloneObject( fileData.initialInfo ), function( err, landingFileData ){
        if( err ) return cb( err );

        // Rename the file currently being filtered
        var postFix = ( fileData.info.landingPostfix || "_real");
        ryver.setSystemData( fileData.system, 'fileName', fileData.system.fileName + postFix );

        // Add originalDestinaton to the landing file's info so that it knows where
        // to redirect users
        landingFileData.info.originalDestination = fileData.system.fileName;

        // Make the original destination's fileData available
        landingFileData.info.originalFileInfo = ryver.cloneObject( fileData.info );

        // Apply filters to the newly created landing page
        ryver.filter( landingFileData, function( err ){
          cb( null );
        })
      });
    });
  }

  // Return the function just defined as the filter
  cb( null, { name: 'landing', executor: f } );
});
<commit_msg>Added check for error in callback<commit_after>
var ryver = require('ryver');
var p = require('path');
fs = require('fs.extra');

var eventEC = ryver.eventEC;

eventEC.onCollect( 'filter', function( cb ){

  var f = function( fileData, cb ){

    var landing = fileData.info.landing;

    if( ! landing ){
      ryver.log("No landing set in fileInfo, skipping");
      return cb( null, fileData );
    }

    var source;

    var mainPath = fileData.system.filePath;
    var backupPath = p.join( ryver.getSrc(), ( ryver.getConfig().includesFolder || '_includes' ) );

    // Load the contents of the landing file
    ryver.readFile( mainPath, backupPath, landing, function( err, landingContentsAsBuffer, usedBackup ){
      if( err ) return cb( err );

      // Make a new fileData based on:
      //  * the file's own path, name
      //  * the landing's extension
      //  * the landing file's contents
      //  * the directory's initial info
      var s = fileData.system;
      var landingExt = '.' + fileData.info.landing.split('.').pop();
      ryver.makeFileData( s.filePath, s.fileName, landingExt, landingContentsAsBuffer, ryver.cloneObject( fileData.initialInfo ), function( err, landingFileData ){
        if( err ) return cb( err );

        // Rename the file currently being filtered
        var postFix = ( fileData.info.landingPostfix || "_real");
        ryver.setSystemData( fileData.system, 'fileName', fileData.system.fileName + postFix );

        // Add originalDestinaton to the landing file's info so that it knows where
        // to redirect users
        landingFileData.info.originalDestination = fileData.system.fileName;

        // Make the original destination's fileData available
        landingFileData.info.originalFileInfo = ryver.cloneObject( fileData.info );

        // Apply filters to the newly created landing page
        ryver.filter( landingFileData, function( err ){
          if( err )return cb( err );

          cb( null );
        })
      });
    });
  }

  // Return the function just defined as the filter
  cb( null, { name: 'landing', executor: f } );
});
<|endoftext|>


<commit_before>'use strict';

let types = ['json', 'javascript', 'css', 'image', 'svg', 'font', 'html'];

function processAsset(asset) {
  if (types.indexOf(asset.type) > -1) {
    const cacheControl = asset.headers.response['cache-control'] || '';
    if (cacheControl.indexOf('private') > -1) {
      return 10;
    }
  }
  return 0;
}

module.exports = {
  id: 'privateAssets',
  title: 'Don\'t use private headers on static content',
  description: 'Static content should be able to be cached & used by everyone.',
  weight: 5,
  tags: ['performance', 'server'],
  processPage: function(page) {
    let score = 100;
    let offending = [];
    page.assets.forEach(function(asset) {
      let myScore = processAsset(asset);
      if (myScore > 0) {
        score -= myScore;
        offending.push(asset.url);
      }
    });

    return {
      score: Math.max(0, score),
      offending: offending,
      advice: score < 100 ? 'The page has ' + offending.length + ' request(s) with private headers. Make sure that the assets really should be private and only used by one user. Else make it cacheable for everyone.' : ''
    }
  }
};
<commit_msg>should we skip the main request or not?<commit_after>'use strict';

let types = ['json', 'javascript', 'css', 'image', 'svg', 'font', 'html'];

function processAsset(asset) {
  if (types.indexOf(asset.type) > -1) {
    const cacheControl = asset.headers.response['cache-control'] || '';
    if (cacheControl.indexOf('private') > -1) {
      return 10;
    }
  }
  return 0;
}

module.exports = {
  id: 'privateAssets',
  title: 'Don\'t use private headers on static content',
  description: 'Static content should be able to be cached & used by everyone.',
  weight: 5,
  tags: ['performance', 'server'],
  processPage: function(page) {
    let score = 100;
    let offending = [];
    page.assets.forEach(function(asset) {
      // should we skip the main page?
      // if (page.url !== asset.url) {
        let myScore = processAsset(asset);
        if (myScore > 0) {
          score -= myScore;
          offending.push(asset.url);
        }
      // }
    });

    return {
      score: Math.max(0, score),
      offending: offending,
      advice: score < 100 ? 'The page has ' + offending.length + ' request(s) with private headers. Make sure that the assets really should be private and only used by one user. Else make it cacheable for everyone.' : ''
    }
  }
};
<|endoftext|>