<commit_before>/**
 * + Project Config
 * =====================================================================
 */

module.exports = (function(config) {

    var path = require('path');

    // project paths
    config.paths = (function(p) {
        p.root      = process.cwd();
        p.bower     = path.join(p.root, 'bower_components');
        p.node      = path.join(p.root, 'node_modules');
        p.app       = path.join(p.root, 'app');
        p.src       = path.join(p.root, 'src');
        p.web       = path.join(p.root, 'web');
        p.site      = path.join(p.src,  'site');
        p.templates = path.join(p.src,  'templates');
        p.assetsSrc = path.join(p.site, 'assets');
        p.assetsDev = path.join(p.src,  'assets-dev');
        p.assets    = path.join(p.web,  'assets');
        return p;
    })({});

    // metadata
    config.metadata = {
        siteTitle:          'simbo.ninja',
        siteDescription:    'Some informative description for search engine results.',
        baseUrl:            '//simbo.ninja/',
        styles:             [
                                'assets/css/main.css'
                            ],
        scripts:            [
                                'assets/js/main.js'
                            ],
        dateLocale:         'de',
        dateFormat:         'Do MMM YYYY',
        dateFormatShort:    'DD.MM.YY',
        dateFormatLong:     'dddd, Do MMMM YYYY'
    };

    // metadata changes depending on environment
    config.metadata.environments = {
        development: {
            baseUrl:            '//localhost:8080/',
            googleAnalytics:    false
        }
    };

    // get jQuery version from package.json
    config.metadata.jqueryVersion = (function() {
        var pkg = require(process.cwd() + '/package.json');
        return pkg.devDependencies.hasOwnProperty('jquery') ? pkg.devDependencies.jquery.replace(/[^.0-9]/g, '') : '';
    })();

    // template function to get the hash of a file
    config.metadata.hash = function(file, algorithm) {
        var crypto = require('crypto');
        if (!algorithm || crypto.getHashes().indexOf(algorithm)===-1) {
            algorithm = 'md5';
        }
        var fs = require('fs'),
            fileContents = fs.readFileSync(path.join(config.paths.root, file));
        return crypto
            .createHash(algorithm)
            .update(fileContents, 'utf8')
            .digest('hex');
    }

    // gulp default params
    config.gulpParams = {
        environment: 'production'
    };

    // global watch task options
    config.watch = {
        mode: 'auto'
    };

    // marked options
    config.marked = {
        gfm: true,
        tables: true,
        breaks: false,
        pedantic: false,
        sanitize: false,
        smartLists: true,
        smartypants: false
    };

    // stylus options
    config.stylus = {
        // add imports and vendor folders to @import path
        paths: [
            path.join(config.paths.assetsDev, 'stylus/imports'),
            path.join(config.paths.assetsDev, 'vendor'),
            path.join(config.paths.assetsSrc, 'img')
        ],
        // function for generating base64 data-uris
        url: {
            name: 'inline-url',
            limit: false
        },
        // create sourcemaps containing inline sources
        sourcemap: {
            inline: true,
            sourceRoot: '.',
            basePath: path.join(path.relative(config.paths.web, config.paths.assets), 'css')
        }
    };

    // autoprefixer options
    config.autoprefixer = {
        browsers: [
            'last 2 versions',
            '> 2%',
            'Opera 12.1',
            'Firefox ESR'
        ]
    };

    // csslint options
    // https://github.com/CSSLint/csslint/wiki/Rules-by-ID
    config.csslint = {
        'box-sizing': false,
        'bulletproof-font-face': false,
        'font-faces': false,
        'compatible-vendor-prefixes': false
    };

    // config sync options
    // https://github.com/danlevan/gulp-config-sync
    config.configSync = {
        fields: [
            'name',
            'version',
            'description',
            'keywords',
            'version',
            'private'
        ],
        space: 2
    };

    return config;
})({});

/* = Project Config */
<commit_msg>revise some comments<commit_after>/**
 * + Gulp Config
 * =====================================================================
 */

module.exports = (function(config) {

    var path = require('path');

    // project paths
    config.paths = (function(p) {
        p.root      = process.cwd();
        p.bower     = path.join(p.root, 'bower_components');
        p.node      = path.join(p.root, 'node_modules');
        p.app       = path.join(p.root, 'app');
        p.src       = path.join(p.root, 'src');
        p.web       = path.join(p.root, 'web');
        p.site      = path.join(p.src,  'site');
        p.templates = path.join(p.src,  'templates');
        p.assetsSrc = path.join(p.site, 'assets');
        p.assetsDev = path.join(p.src,  'assets-dev');
        p.assets    = path.join(p.web,  'assets');
        return p;
    })({});

    // metadata
    config.metadata = {
        siteTitle:          'simbo.ninja',
        siteDescription:    'Some informative description for search engine results.',
        baseUrl:            '//simbo.ninja/',
        styles:             [
                                'assets/css/main.css'
                            ],
        scripts:            [
                                'assets/js/main.js'
                            ],
        dateLocale:         'de',
        dateFormat:         'Do MMM YYYY',
        dateFormatShort:    'DD.MM.YY',
        dateFormatLong:     'dddd, Do MMMM YYYY'
    };

    // metadata changes depending on environment
    config.metadata.environments = {
        development: {
            baseUrl:            '//localhost:8080/',
            googleAnalytics:    false
        }
    };

    // get jQuery version from package.json
    config.metadata.jqueryVersion = (function() {
        var pkg = require(process.cwd() + '/package.json');
        return pkg.devDependencies.hasOwnProperty('jquery') ? pkg.devDependencies.jquery.replace(/[^.0-9]/g, '') : '';
    })();

    // template function to get the hash of a file
    config.metadata.hash = function(file, algorithm) {
        var crypto = require('crypto');
        if (!algorithm || crypto.getHashes().indexOf(algorithm)===-1) {
            algorithm = 'md5';
        }
        var fs = require('fs'),
            fileContents = fs.readFileSync(path.join(config.paths.root, file));
        return crypto
            .createHash(algorithm)
            .update(fileContents, 'utf8')
            .digest('hex');
    }

    // gulp default params
    config.gulpParams = {
        environment: 'production'
    };

    // global watch task options
    config.watch = {
        mode: 'auto'
    };

    // marked options
    config.marked = {
        gfm: true,
        tables: true,
        breaks: false,
        pedantic: false,
        sanitize: false,
        smartLists: true,
        smartypants: false
    };

    // stylus options
    config.stylus = {
        // add imports and vendor folders to @import path
        paths: [
            path.join(config.paths.assetsDev, 'stylus/imports'),
            path.join(config.paths.assetsDev, 'vendor'),
            path.join(config.paths.assetsSrc, 'img')
        ],
        // function for generating base64 data-uris
        url: {
            name: 'inline-url',
            limit: false
        },
        // create sourcemaps containing inline sources
        sourcemap: {
            inline: true,
            sourceRoot: '.',
            basePath: path.join(path.relative(config.paths.web, config.paths.assets), 'css')
        }
    };

    // autoprefixer options
    config.autoprefixer = {
        browsers: [
            'last 2 versions',
            '> 2%',
            'Opera 12.1',
            'Firefox ESR'
        ]
    };

    // csslint options
    // https://github.com/CSSLint/csslint/wiki/Rules-by-ID
    config.csslint = {
        'box-sizing': false,
        'bulletproof-font-face': false,
        'font-faces': false,
        'compatible-vendor-prefixes': false
    };

    // config sync options
    // https://github.com/danlevan/gulp-config-sync
    config.configSync = {
        fields: [
            'name',
            'version',
            'description',
            'keywords',
            'version',
            'private'
        ],
        space: 2
    };

    return config;
})({});

/* = Gulp Config */
<|endoftext|>


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

  angular.module('mytodo')
    .factory('ItemService', ['$http','$q', function ($http, $q) {
      var service = {};

      service.getItems = function(listId){
        console.log('getItems: ', listId);
        var deferred = $q.defer();
        $http.get('/api/items?list_id=' + listId)
           .success(function (data) {
               console.log(data);
               deferred.resolve(data);
           })
           .error(function(data) {
            console.log('Error: ', data);
            deferred.reject('Error: ' + data);
           });
           return deferred.promise;
      }

      // create item
      service.createItem = function (formData) {
        var deferred = $q.defer();
        $http.post('/api/item/create', formData)
           .success(function (data) {
              deferred.resolve(data);
              console.log(data);
           })
           .error(function (data) {
              deferred.reject(data);
              console.log('Error: ' + data);
           });
           return deferred.promise;
      };

      //delete item
      service.removeItem = function (id, listId) {
        var deferred = $q.defer();
        $http.post('/api/item/delete/' + id + '?list_id=' + listId)
           .success(function (data) {
              deferred.resolve(data);
               console.log(data);
           })
           .error(function (data) {
              deferred.reject(data);
              console.log('Error: ' + data);
           });
           return deferred.promise;
      };

      //update item
      service.editItem = function (id, item_title, listId) {
        var deferred = $q.defer();
        $http.post('/api/item/edit2/' + id + '?item_title=' + item_title + '&list_id=' + listId)
           .success(function (data) {
               deferred.resolve(data);
               console.log(data);
           })
           .error(function (data) {
              deferred.reject(data);
              console.log('Error: ' + data);
           });
           return deferred.promise;
      };

      return service;
    }]);
})();<commit_msg>minor bug fixed in itemService, works fully now<commit_after>(function() {
  'use strict';

  angular.module('mytodo')
    .factory('ItemService', ['$http','$q', function ($http, $q) {
      var service = {};

      service.getItems = function(listId){
        console.log('getItems: ', listId);
        var deferred = $q.defer();
        $http.get('/api/items?list_id=' + listId)
           .success(function (data) {
               console.log(data);
               deferred.resolve(data);
           })
           .error(function(data) {
            console.log('Error: ', data);
            deferred.reject('Error: ' + data);
           });
           return deferred.promise;
      }

      // create item
      service.createItem = function (formData) {
        var deferred = $q.defer();
        $http.post('/api/item/create', formData)
           .success(function (data) {
              deferred.resolve(data);
              console.log(data);
           })
           .error(function (data) {
              deferred.reject(data);
              console.log('Error: ' + data);
           });
           return deferred.promise;
      };

      //delete item
      service.removeItem = function (id, listId) {
        var deferred = $q.defer();
        $http.post('/api/item/delete/' + id + '?list_id=' + listId)
           .success(function (data) {
              deferred.resolve(data);
               console.log(data);
           })
           .error(function (data) {
              deferred.reject(data);
              console.log('Error: ' + data);
           });
           return deferred.promise;
      };

      //update item
      service.editItem = function (id, item_title, listId) {
        var deferred = $q.defer();
        $http.post('/api/item/edit/' + id + '?item_title=' + item_title + '&list_id=' + listId)
           .success(function (data) {
               deferred.resolve(data);
               console.log(data);
           })
           .error(function (data) {
              deferred.reject(data);
              console.log('Error: ' + data);
           });
           return deferred.promise;
      };

      return service;
    }]);
})();<|endoftext|>


<commit_before>var Imaginable = (function() {

    /**
     * @arg {input} <input> DOM element, or the ID (prefixed by #)
     * @arg {callback} function(Imag) which will be called having the
     * imag as argument
     */
    var onImageLoad = function(input, callback) {
        input = $(input);
        $(input).change(function() {
            var imag = new Imag(this);
            imag.onImageReady(callback, this, imag);
        });
    }

    // http://stackoverflow.com/questions/19032406/convert-html5-canvas-into-file-to-be-uploaded
    var dataURLToFile = function(dataURL) {
        var blobBin = atob(dataURL.split(',')[1]);
        var array = [];
        for(var i = 0; i < blobBin.length; i++) {
            array.push(blobBin.charCodeAt(i));
        }
        var file = new Blob([new Uint8Array(array)], {type: 'image/png'});

        return file;
    }

    /**
     * Wrapper around the image itself
     */
    function Imag(input) {
        // Instance variables
        this.image = null;
        this.input = null;
        this.canvas = null;

        this.height = 0;
        this.width = 0;

        this.callbackList = [];

        if (input) {
            this.load(input);
        }
    }

    /**
     *
     * Executes the callbacks queued in te callabckList in the order they were pushed
     * the format of a callback is
     * [functionName, thisContext, args...]
     */
    Imag.prototype.executeCallbacks = function() {
        this.callbackList.forEach(function(elem) {
            var callback = elem[0];
            var _this = elem[1];
            elem.splice(0, 2);
            callback.apply(_this, elem);
        });
    }

    Imag.prototype.onImageReady = function(callback, _this, image) {
        if (this.image && this.image.complete) {
            this.height = this.image.height;
            this.width = this.image.width;
            callback(this);
        } else {
            var _this = this;
            this.callbackList.push([_this.onImageReady, _this, callback, _this, image]);
        }
    }

    Imag.prototype.load = function(input) {
        if (!input || !input.files || !input.files[0]) {
            throw Error("No files given");
        }

        if (!input.files[0].type.match(/image.*/)) {
            throw Error("The file selected is not an image");
        }

        this.image = document.createElement('img');
        this.image.src = window.URL.createObjectURL(input.files[0]);

        this.input = input;

        var _this = this;
        this.image.onload = function() {
            _this.executeCallbacks();
        }

        return this.image;
    }

    /**
     * Keeps aspect ratio
     */
    Imag.prototype.resize = function(height, width) {
        var imageHeight = this.image.height;
        var imageWidth = this.image.width;

        height = height ? height : imageHeight;
        width = width ? width : imageWidth;

        if (imageWidth > imageHeight) {
          if (imageWidth > finalWidth) {
            imageHeight *= finalWidth / imageWidth;
            imageWidth = finalWidth;
          }
        } else {
          if (imageHeight > height) {
            imageWidth *= height / imageHeight;
            imageHeight = height;
          }
        }
        this.height = imageHeight;
        this.width = imageWidth;

        this.onRedraw();
    }

    Imag.prototype.synchronizeWithCanvas = function(canvas) {
        this.canvas = $(canvas)[0];
        this.onRedraw();
    }

    Imag.prototype.onRedraw = function() {
        if (!this.canvas) {
            return;
        }

        this.canvas.width = this.width;
        this.canvas.height = this.height;
        var ctx = this.canvas.getContext("2d");
        ctx.drawImage(this.image, 0, 0, this.width, this.height);
    }

    Imag.prototype.download = function(fileName) {
        if (!this.image || !this.image.complete) {
            console.error("Cannot drawOnCanvas an image which was not loaded yet");
        }

        if (!fileName) {
            fileName = "image.png";
        }

        if (!this.canvas) {
            throw Error("Canvas has not been created yet");
        }

        //TODO: remove the click HTML text
        var dataurl = this.canvas.toDataURL();
        var anchor = $("<a>", {
            href: dataurl,
            download: "file.png",
        }).html("click")[0].click();
    }

    Imag.prototype.prepareForServer = function(imageName) {
        if (!this.image || !this.image.complete) {
            console.error("Cannot drawOnCanvas an image which was not loaded yet");
        }

        if (!this.input) {
            throw Error("No arguments given");
        }

        if (!this.input.files) {
            throw Error("Element given is not a file input")
        }

        if (!this.input.files[0]) {
            throw Error("No files given");
        }

        if (!this.input.files[0].type.match(/image.*/)) {
            throw Error("The file selected is not an image");
        };

        if (!imageName) {
            imageName = "new_image";
        }

        if (!server) {
            throw Error("No server specified");
        }

        var data = new FormData();

        dataURL = this.canvas.toDataURL("image/jpeg");
        data.append(imageName, dataURLToFile(dataURL));

        return data;

        // jQuery.ajax({
        //     url: server,
        //     type: "POST",
        //     data: data,
        //     cache: false,
        //     contentType: false,
        //     processData: false,
        //     success: callback,
        // });
    }

    /**
     * Public methods
     */
    return {
        onImageLoad: onImageLoad,
    };

})();
<commit_msg>Indentation refactor<commit_after>var Imaginable = (function() {

    /**
     * @arg {input} <input> DOM element, or the ID (prefixed by #)
     * @arg {callback} function(Imag) which will be called having the
     * imag as argument
     */
    var onImageLoad = function(input, callback) {
        input = $(input);
        $(input).change(function() {
            var imag = new Imag(this);
            imag.onImageReady(callback, this, imag);
        });
    }

    // http://stackoverflow.com/questions/19032406/convert-html5-canvas-into-file-to-be-uploaded
    var dataURLToFile = function(dataURL) {
        var blobBin = atob(dataURL.split(',')[1]);
        var array = [];
        for (var i = 0; i < blobBin.length; i++) {
            array.push(blobBin.charCodeAt(i));
        }
        var file = new Blob([new Uint8Array(array)], {type: 'image/png'});

        return file;
    }

    /**
     * Wrapper around the image itself
     */
    function Imag(input) {
        // Instance variables
        this.image = null;
        this.input = null;
        this.canvas = null;

        this.height = 0;
        this.width = 0;

        this.callbackList = [];

        if (input) {
            this.load(input);
        }
    }

    /**
     *
     * Executes the callbacks queued in te callabckList in the order they were pushed
     * the format of a callback is
     * [functionName, thisContext, args...]
     */
    Imag.prototype.executeCallbacks = function() {
        this.callbackList.forEach(function(elem) {
            var callback = elem[0];
            var _this = elem[1];
            elem.splice(0, 2);
            callback.apply(_this, elem);
        });
    }

    Imag.prototype.onImageReady = function(callback, _this, image) {
        if (this.image && this.image.complete) {
            this.height = this.image.height;
            this.width = this.image.width;
            callback(this);
        } else {
            var _this = this;
            this.callbackList.push([_this.onImageReady, _this, callback, _this, image]);
        }
    }

    Imag.prototype.load = function(input) {
        if (!input || !input.files || !input.files[0]) {
            throw Error("No files given");
        }

        if (!input.files[0].type.match(/image.*/)) {
            throw Error("The file selected is not an image");
        }

        this.image = document.createElement('img');
        this.image.src = window.URL.createObjectURL(input.files[0]);

        this.input = input;

        var _this = this;
        this.image.onload = function() {
            _this.executeCallbacks();
        }

        return this.image;
    }

    /**
     * Keeps aspect ratio
     */
    Imag.prototype.resize = function(height, width) {
        var imageHeight = this.image.height;
        var imageWidth = this.image.width;

        height = height ? height : imageHeight;
        width = width ? width : imageWidth;

        if (imageWidth > imageHeight) {
            if (imageWidth > finalWidth) {
                imageHeight *= finalWidth / imageWidth;
                imageWidth = finalWidth;
            }
        } else {
            if (imageHeight > height) {
                imageWidth *= height / imageHeight;
                imageHeight = height;
            }
        }
        this.height = imageHeight;
        this.width = imageWidth;

        this.onRedraw();
    }

    Imag.prototype.synchronizeWithCanvas = function(canvas) {
        this.canvas = $(canvas)[0];
        this.onRedraw();
    }

    Imag.prototype.onRedraw = function() {
        if (!this.canvas) {
            return;
        }

        this.canvas.width = this.width;
        this.canvas.height = this.height;
        var ctx = this.canvas.getContext("2d");
        ctx.drawImage(this.image, 0, 0, this.width, this.height);
    }

    Imag.prototype.download = function(fileName) {
        if (!this.image || !this.image.complete) {
            console.error("Cannot drawOnCanvas an image which was not loaded yet");
        }

        if (!fileName) {
            fileName = "image.png";
        }

        if (!this.canvas) {
            throw Error("Canvas has not been created yet");
        }

        //TODO: remove the click HTML text
        var dataurl = this.canvas.toDataURL();
        var anchor = $("<a>", {
            href: dataurl,
            download: "file.png",
        }).html("click")[0].click();
    }

    Imag.prototype.prepareForServer = function(imageName) {
        if (!this.image || !this.image.complete) {
            console.error("Cannot drawOnCanvas an image which was not loaded yet");
        }

        if (!this.input) {
            throw Error("No arguments given");
        }

        if (!this.input.files) {
            throw Error("Element given is not a file input")
        }

        if (!this.input.files[0]) {
            throw Error("No files given");
        }

        if (!this.input.files[0].type.match(/image.*/)) {
            throw Error("The file selected is not an image");
        };

        if (!imageName) {
            imageName = "new_image";
        }

        if (!server) {
            throw Error("No server specified");
        }

        var data = new FormData();

        dataURL = this.canvas.toDataURL("image/jpeg");
        data.append(imageName, dataURLToFile(dataURL));

        return data;

        // jQuery.ajax({
        //     url: server,
        //     type: "POST",
        //     data: data,
        //     cache: false,
        //     contentType: false,
        //     processData: false,
        //     success: callback,
        // });
    }

    /**
     * Public methods
     */
    return {
        onImageLoad: onImageLoad,
    };

})();
<|endoftext|>


<commit_before>function integrate(tuples){
	var sum = 0;
	console.log(tuples);
	var boundB = tuples[tuples.length - 1].x;
	var boundA = tuples[0].x;
	for(var i=0;i<(tuples.length-1);i++){
		sum += ((tuples[i+1].x - tuples[i].x)*(tuples[i+1].y + tuples[i].y));
	}
	return (.5 * sum);
}
function xQuad(){
	var tempArr = [];
	var boundA = $("#boundb").val();
	var boundB = $("#bounda").val();
	for(var i=boundA;i<=boundB;i++){
		var tuple = {};
		tuple.x = i;
		tuple.y = Math.pow(i,2);
		tempArr.push(tuple);
	}
	return tempArr;
}
function xLin(){
	var tempArr = [];
	var boundA = $("#boundb").val();
	var boundB = $("#bounda").val();
	for(var i=boundA;i<=boundB;i++){
		var tuple = {};
		tuple.x = i;
		tuple.y = i;
		tempArr.push(tuple);
	}
	return tempArr;
}
//for testing, runs integrate() with xLin() as input
function integrateXLin(){
	document.getElementById("integral").innerHTML = integrate(xLin());
}
//for testing, runs integrate() with xQuad() as input
function integrateXQuad(){
	document.getElementById("integral").innerHTML = integrate(xQuad());
}
//final onpress function to run with parameters
function integrateFunc(){
	var func = document.getElementById("screen").innerHTML;
	console.log(func);
	//var boundA = $("#bounda").val(); //left
	//var boundB = $("#boundb").val(); //right
	var boundA_String = document.getElementById("bounda").innerHTML;
	var boundA_Int = parseInt(boundA_String);
	var boundB_String = document.getElementById("boundb").innerHTML;
	var boundB_Int = parseInt(boundB_String);

	//document.getElementById("integral").innerHTML = integrate(mapper(0,10,1));
	document.getElementById("integral").innerHTML = integrate(mapper(boundA_Int,boundB_Int,1));
}<commit_msg>Added files via upload<commit_after>function integrate(tuples){
	var sum = 0;
	console.log(tuples);
	var boundB = tuples[tuples.length - 1].x;
	var boundA = tuples[0].x;
	for(var i=0;i<(tuples.length-1);i++){
		sum += ((tuples[i+1].x - tuples[i].x)*(tuples[i+1].y + tuples[i].y));
	}
	return (.5 * sum);
}
function xQuad(){
	var tempArr = [];
//	var boundA = $("#boundb").val();
//	var boundB = $("#bounda").val();
	var boundA_String = document.getElementById("bounda").innerHTML;
	var boundA_Int = parseInt(boundA_String);
	var boundB_String = document.getElementById("boundb").innerHTML;
	var boundB_Int = parseInt(boundB_String);

//	for(var i=boundA;i<=boundB;i++){
	for(var i=boundA_Int;i<=boundB_Int;i++){
		var tuple = {};
		tuple.x = i;
		tuple.y = Math.pow(i,2);
		tempArr.push(tuple);
	}
	return tempArr;
}
function xLin(){
	var tempArr = [];
//	var boundA = $("#boundb").val();
//	var boundB = $("#bounda").val();
	var boundA_String = document.getElementById("bounda").innerHTML;
	var boundA_Int = parseInt(boundA_String);
	var boundB_String = document.getElementById("boundb").innerHTML;
	var boundB_Int = parseInt(boundB_String);

//	for(var i=boundA;i<=boundB;i++){
	for(var i=boundA_Int;i<=boundB_Int;i++){
		var tuple = {};
		tuple.x = i;
		tuple.y = i;
		tempArr.push(tuple);
	}
	return tempArr;
}
//for testing, runs integrate() with xLin() as input
function integrateXLin(){
	document.getElementById("integral").innerHTML = integrate(xLin());
}
//for testing, runs integrate() with xQuad() as input
function integrateXQuad(){
	document.getElementById("integral").innerHTML = integrate(xQuad());
}
//final onpress function to run with parameters
function integrateFunc(){
	var func = document.getElementById("screen").innerHTML;
	console.log(func);
	//var boundA = $("#bounda").val(); //left
	//var boundB = $("#boundb").val(); //right
	var boundA_String = document.getElementById("bounda").innerHTML;
	var boundA_Int = parseInt(boundA_String);
	var boundB_String = document.getElementById("boundb").innerHTML;
	var boundB_Int = parseInt(boundB_String);

	//document.getElementById("integral").innerHTML = integrate(mapper(0,10,1));
	document.getElementById("integral").innerHTML = integrate(mapper(boundA_Int,boundB_Int,1));
}<|endoftext|>


<commit_before>/**
 * Copyright (C) 2014 Ready Business System
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
(function ($)
{
	"use strict";

	/**
	 * @ngdoc service
	 * @name RbsChange.service:Keyboard
	 * @description Service to help special keys detection.
	 *
	 * This Service creates the following object in the `$rootScope`, and updates it in real time
	 * to reflect the keyboard status:
	 *

	 *   rbsChangeKeyboardStatus = {
	 *     'shift': false,
	 *     'ctrl': false,
	 *     'alt': false,
	 *     'meta': false
	 *   };
	 *

	 */
	function KeyboardService($rootScope)
	{
		$rootScope.rbsChangeKeyboardStatus = {
			'shift': false,
			'ctrl': false,
			'alt': false,
			'meta': false
		};

		function keyDown(event)
		{
			if (event.shiftKey)
			{
				$rootScope.rbsChangeKeyboardStatus.shift = true;
			}
			if (event.ctrlKey)
			{
				$rootScope.rbsChangeKeyboardStatus.ctrl = true;
			}
			if (event.altKey)
			{
				$rootScope.rbsChangeKeyboardStatus.alt = true;
			}
			if (event.metaKey)
			{
				$rootScope.rbsChangeKeyboardStatus.meta = true;
			}
			$rootScope.$digest();
		}

		function keyUp(event)
		{
			if (!event.shiftKey)
			{
				$rootScope.rbsChangeKeyboardStatus.shift = false;
			}
			if (!event.ctrlKey)
			{
				$rootScope.rbsChangeKeyboardStatus.ctrl = false;
			}
			if (!event.altKey)
			{
				$rootScope.rbsChangeKeyboardStatus.alt = false;
			}
			if (!event.metaKey)
			{
				$rootScope.rbsChangeKeyboardStatus.meta = false;
			}
			$rootScope.$digest();
		}

		this.watch = function (scope, key, callback)
		{
			var expr = 'rbsChangeKeyboardStatus.' +
				key.replace(/\+/g, ' && rbsChangeKeyboardStatus.').replace(/\-/g, ' && !rbsChangeKeyboardStatus.');
			var deregistrationFunc = $rootScope.$watch(expr, function (value, oldValue)
			{
				if (value === true || (value === false))
				{
					callback(value, oldValue);
				}
			}, true);
			scope.$on('$destroy', function ()
			{
				deregistrationFunc();
			});
		};

		$('body').on('keydown', keyDown).on('keyup', keyUp);
	}

	/**
	 * @ngdoc directive
	 * @id RbsChange.directive:rbsKbSwitch
	 * @name Alt-Ctrl-Shift-Meta keys manager
	 * @restrict EA
	 *
	 * @description
	 * This Directive helps you display different widgets depending on the state of special keys. This is very useful
	 * to display an alternative button when the user holds the Alt-key down for example.
	 *
	 * Use rbs-kb-when="" and rbs-kb-default to build the different combinations.
	 *
	 * @example
	 *

	 * <rbs-kb-switch>
	 *
	 *
	 *
	 * </rbs-kb-switch>
	 *

	 */
	function rbsKbSwitch(Keyboard)
	{
		return {
			restrict : 'EA',
			link : function (scope, elm)
			{
				var when, whenCounter, def;

				// shortcut rbs-kb-alt="" instead of rbs-kb-when="alt"
				elm.find('[rbs-kb-alt]').each(function () {
					$(this).removeAttr('rbs-kb-alt').attr('rbs-kb-when', 'alt');
				});

				when = elm.find('[rbs-kb-when]');
				whenCounter = 0;
				def = elm.find('[rbs-kb-default]');

				when.each(function ()
				{
					var $el = $(this);
					Keyboard.watch(scope, $el.attr('rbs-kb-when'), function (value, oldValue)
					{
						if (value)
						{
							def.hide();
							$el.show();
							whenCounter++;
						}
						else
						{
							$el.hide();
							if (oldValue === true)
							{
								whenCounter--;
							}
							if (whenCounter === 0)
							{
								def.show();
							}
						}
					});
				});
			}
		};
	}

	var app = angular.module('RbsChange');
	app.service('RbsChange.Keyboard', ['$rootScope', KeyboardService]);
	app.directive('rbsKbSwitch', ['RbsChange.Keyboard', rbsKbSwitch]);

})(window.jQuery);<commit_msg>Handle data-prefixed attributes on rbs-kb-switch.<commit_after>/**
 * Copyright (C) 2014 Ready Business System
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
(function($) {
	"use strict";

	/**
	 * @ngdoc service
	 * @name RbsChange.service:Keyboard
	 * @description Service to help special keys detection.
	 *
	 * This Service creates the following object in the `$rootScope`, and updates it in real time
	 * to reflect the keyboard status:
	 *

	 *   rbsChangeKeyboardStatus = {
	 *     'shift': false,
	 *     'ctrl': false,
	 *     'alt': false,
	 *     'meta': false
	 *   };
	 *

	 */
	function KeyboardService($rootScope) {
		$rootScope.rbsChangeKeyboardStatus = {
			'shift': false,
			'ctrl': false,
			'alt': false,
			'meta': false
		};

		function keyDown(event) {
			if (event.shiftKey) {
				$rootScope.rbsChangeKeyboardStatus.shift = true;
			}
			if (event.ctrlKey) {
				$rootScope.rbsChangeKeyboardStatus.ctrl = true;
			}
			if (event.altKey) {
				$rootScope.rbsChangeKeyboardStatus.alt = true;
			}
			if (event.metaKey) {
				$rootScope.rbsChangeKeyboardStatus.meta = true;
			}
			$rootScope.$digest();
		}

		function keyUp(event) {
			if (!event.shiftKey) {
				$rootScope.rbsChangeKeyboardStatus.shift = false;
			}
			if (!event.ctrlKey) {
				$rootScope.rbsChangeKeyboardStatus.ctrl = false;
			}
			if (!event.altKey) {
				$rootScope.rbsChangeKeyboardStatus.alt = false;
			}
			if (!event.metaKey) {
				$rootScope.rbsChangeKeyboardStatus.meta = false;
			}
			$rootScope.$digest();
		}

		this.watch = function(scope, key, callback) {
			var expr = 'rbsChangeKeyboardStatus.' +
				key.replace(/\+/g, ' && rbsChangeKeyboardStatus.').replace(/\-/g, ' && !rbsChangeKeyboardStatus.');
			var deregistrationFunc = $rootScope.$watch(expr, function(value, oldValue) {
				if (value === true || (value === false)) {
					callback(value, oldValue);
				}
			}, true);
			scope.$on('$destroy', function() {
				deregistrationFunc();
			});
		};

		$('body').on('keydown', keyDown).on('keyup', keyUp);
	}

	/**
	 * @ngdoc directive
	 * @id RbsChange.directive:rbsKbSwitch
	 * @name Alt-Ctrl-Shift-Meta keys manager
	 * @restrict EA
	 *
	 * @description
	 * This Directive helps you display different widgets depending on the state of special keys. This is very useful
	 * to display an alternative button when the user holds the Alt-key down for example.
	 *
	 * Use rbs-kb-when="" and rbs-kb-default to build the different combinations.
	 *
	 * @example
	 *

	 * <rbs-kb-switch>
	 *
	 *
	 *
	 * </rbs-kb-switch>
	 *

	 */
	function rbsKbSwitch(Keyboard) {
		return {
			restrict: 'EA',
			link: function(scope, elm) {
				var when, whenCounter, def;

				// Shortcut rbs-kb-alt="" instead of rbs-kb-when="alt".
				elm.find('[rbs-kb-alt]').each(function() {
					$(this).removeAttr('rbs-kb-alt').attr('data-rbs-kb-when', 'alt');
				});
				elm.find('[data-rbs-kb-alt]').each(function() {
					$(this).removeAttr('data-rbs-kb-alt').attr('data-rbs-kb-when', 'alt');
				});

				whenCounter = 0;
				def = elm.find('[rbs-kb-default], [data-rbs-kb-default]');
				elm.find('[rbs-kb-when], [data-rbs-kb-when]').each(function() {
					var $el = $(this);
					var key = $el.attr('rbs-kb-when') || $el.attr('data-rbs-kb-when');
					Keyboard.watch(scope, key, function(value, oldValue) {
						if (value) {
							def.hide();
							$el.show();
							whenCounter++;
						}
						else {
							$el.hide();
							if (oldValue === true) {
								whenCounter--;
							}
							if (whenCounter === 0) {
								def.show();
							}
						}
					});
				});
			}
		};
	}

	var app = angular.module('RbsChange');
	app.service('RbsChange.Keyboard', ['$rootScope', KeyboardService]);
	app.directive('rbsKbSwitch', ['RbsChange.Keyboard', rbsKbSwitch]);

})(window.jQuery);<|endoftext|>


<commit_before>const taskReducer = (state=[], action) => {
  switch (action.type) {
    case 'ADD_TASK':
      return [
        ...state,
        action.task
      ];
    case 'DO_TASK':
      return [
        ...state.slice(0, action.index),
        {
          ...state[action.index],
          done: true,
        },
        ...state.slice(action.index + 1),
      ];
    case 'EDIT_TASK':
      return [
        ...state.slice(0, action.index),
        action.newTask,
        ...state.slice(action.index + 1),
      ];
    case 'DELETE_TASK':
      return [
        ...state.slice(0, action.index),
        ...state.slice(action.index + 1),
      ];
    default:
      return state;
  }
};

export default taskReducer;
<commit_msg>Update task reducer<commit_after>const taskReducer = (state=[], action) => {
  switch (action.type) {
    case 'ADD_TASK':
      return [
        ...state,
        action.task
      ];
    case 'DO_TASK':
      return [
        ...state.slice(0, action.index),
        {
          ...state[action.index],
          done: true,
        },
        ...state.slice(action.index + 1),
      ];
    case 'EDIT_TASK':
      return [
        ...state.slice(0, action.index),
        {
          ...state[action.index],
          task: action.newTask.task
        },
        ...state.slice(action.index + 1),
      ];
    case 'DELETE_TASK':
      return [
        ...state.slice(0, action.index),
        ...state.slice(action.index + 1),
      ];
    default:
      return state;
  }
};

export default taskReducer;
<|endoftext|>


<commit_before>var progress = 0
var pps = 1
var goldpertick = 1
var goldcount = 2

var increasegoldproductionrateprice = 1
var increasegoldamountrateprice = 10
var pbar = document.getElementById("progressbar");
var golddisplay = document.getElementById("gold");
var clickcollectgold = document.getElementById("collectgold");

golddisplay.innerHTML = "Gold: " + goldcount;

function updateprogress()	{
    pbar.value = progress;
}
document.getElementById('collectgold').onclick = function()	{
	if (progress > 999) {
		progress = 0
		goldcount += goldpertick
		golddisplay.innerHTML = "Gold: " + goldcount;
		updateprogress()
	}
}
document.getElementById('speed').onclick = function()	{
	if (goldcount > increasegoldproductionrateprice - 1)	{
		goldcount -= increasegoldproductionrateprice
		golddisplay.innerHTML = "Gold: " + goldcount;
		increasegoldproductionrateprice = Math.ceil(increasegoldproductionrateprice = Math.pow(pps,2) * 0.4)

		document.getElementById('speed').innerHTML = "Increase Production Rate for " + increasegoldproductionrateprice + " gold"
		pps += 1;
	}

}
document.getElementById('amount').onclick = function()	{
	if (goldcount > increasegoldamountrateprice - 1)	{
		goldcount -= increasegoldamountrateprice
		golddisplay.innerHTML = "Gold: " + goldcount;
		increasegoldamountrateprice += increasegoldamountrateprice * 2
		goldpertick = goldpertick * 2
		document.getElementById('amount').innerHTML = "Increase Amount Found for " + increasegoldamountrateprice + " gold";
	}
}
setInterval(function() {
    progress += pps;
	updateprogress()

},10);

	<commit_msg>fix start gold<commit_after>var progress = 0
var pps = 1
var goldpertick = 1
var goldcount = 0

var increasegoldproductionrateprice = 1
var increasegoldamountrateprice = 10
var pbar = document.getElementById("progressbar");
var golddisplay = document.getElementById("gold");
var clickcollectgold = document.getElementById("collectgold");

golddisplay.innerHTML = "Gold: " + goldcount;

function updateprogress()	{
    pbar.value = progress;
}
document.getElementById('collectgold').onclick = function()	{
	if (progress > 999) {
		progress = 0
		goldcount += goldpertick
		golddisplay.innerHTML = "Gold: " + goldcount;
		updateprogress()
	}
}
document.getElementById('speed').onclick = function()	{
	if (goldcount > increasegoldproductionrateprice - 1)	{
		goldcount -= increasegoldproductionrateprice
		golddisplay.innerHTML = "Gold: " + goldcount;
		increasegoldproductionrateprice = Math.ceil(increasegoldproductionrateprice = Math.pow(pps,2) * 0.4)

		document.getElementById('speed').innerHTML = "Increase Production Rate for " + increasegoldproductionrateprice + " gold"
		pps += 1;
	}

}
document.getElementById('amount').onclick = function()	{
	if (goldcount > increasegoldamountrateprice - 1)	{
		goldcount -= increasegoldamountrateprice
		golddisplay.innerHTML = "Gold: " + goldcount;
		increasegoldamountrateprice += increasegoldamountrateprice * 2
		goldpertick = goldpertick * 2
		document.getElementById('amount').innerHTML = "Increase Amount Found for " + increasegoldamountrateprice + " gold";
	}
}
setInterval(function() {
    progress += pps;
	updateprogress()

},10);

	<|endoftext|>


<commit_before>import React from 'react';
import { Link } from 'react-router-dom';

const Book = (props) => {
  const { book } = props;
  return (

                    <Link to= { `/books/${book.id}`} className="btn-floating halfway-fab waves-effect waves-light small red">
                        chevron_right
                    </Link>

                     { book.title }

 Author|  { book.author}

 Genre|  {book.subject}

 Quantity|  { book.quantity}

thumb_up{book.upvotes}

favorite_border{book.favCount}

comment{book.bookReviews.length}

  );
};

export default Book;
<commit_msg>Change button styles to flat button<commit_after>import React from 'react';
import { Link } from 'react-router-dom';

const Book = (props) => {
  const { book } = props;
  return (

                    <Link to= { `/books/${book.id}`} className="btn-floating halfway-fab waves-effect waves-light small red">
                        chevron_right
                    </Link>

                     { book.title }

 Author|  { book.author}

 Genre|  {book.subject}

 Quantity|  { book.quantity}

thumb_up{book.upvotes}

favorite_border{book.favCount}

comment{book.bookReviews.length}

  );
};

export default Book;
<|endoftext|>


<commit_before>var ace = AceEditor.instance();

angular.module('domegis')

.directive('domegisStyles', [
  function() {
    return {
      restrict: 'E',
      templateUrl: 'client/contents/styles.html',
      scope: {
        content: '='
      },
      controller: [
        '$scope',
        '$reactive',
        '$compile',
        function($scope, $reactive, $compile) {

          $scope.aceOption = {
            mode: 'css',
            useWrapMode: false,
            showGutter: false,
            theme: 'github'
          };

          $scope.table = {
            title: 'table'
          };

          $scope.styles = {
            polygon: {
              composite: '',
              fill: {
                color: '#f00',
                opacity: .8,
              },
              stroke: {
                color: '#0f0',
                width: 1,
                opacity: .8
              }
            },
            marker: {
              composite: '',
              fill: {
                width: 10,
                color: '#00f',
                opacity: 1
              },
              stroke: {
                color: '#0f0',
                width: .5,
                opacity: .8
              }
            }
          };

          var mapCarto = {
            'polygon': {
              'polygon-fill': 'fill.color',
              'polygon-opacity': 'fill.opacity',
              'polygon-comp-op': 'composite',
              'line-color': 'stroke.color',
              'line-width': 'stroke.width',
              'line-opacity': 'stroke.opacity'
            },
            'marker': {
              'marker-width': 'fill.width',
              'marker-fill': 'fill.color',
              'marker-fill-opacity': 'fill.opacity',
              'marker-comp-op': 'composite',
              'marker-line-color': 'stroke.color',
              'marker-line-width': 'stroke.width',
              'marker-line-opacity': 'stroke.opacity'
            }
          };

          var getProp = function(type, name) {
            var val = '';
            if(mapCarto[type][name]) {
              return eval('$scope.styles.' + type + '.' + mapCarto[type][name]);
            }
            return val;
          }

          function regexEscape(str) {
            return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
          }

          $scope.cartocss = '';

          var tableRegex = new RegExp(regexEscape('#' + $scope.table.title + ' {') + '([\\s\\S]*?)}');

          // Update styles object from raw CartoCSS
          $scope.$watch('cartocss', function(cartocss) {
            var tableMatch = cartocss.match(tableRegex);
            if(tableMatch != null && tableMatch[1]) {
              for(var type in mapCarto) {
                if($scope.isType(type)) {
                  for(var prop in mapCarto[type]) {
                    var propRegex = new RegExp(regexEscape(prop) + ':(.*?);');
                    var propMatch = cartocss.match(propRegex);
                    if(propMatch != null) {
                      eval('$scope.styles.' + type + '.' + mapCarto[type][prop] + ' = propMatch[1].trim().toLowerCase()');
                    }
                  }
                }
              }
            }
          });

          // Update CartoCSS output from styles object
          $scope.$watch('styles', function(styles, prevStyles) {

            var tableMatch = $scope.cartocss.match(tableRegex);

            var cartocss = '';

            if(tableMatch != null && tableMatch[1]) {
              cartocss = tableMatch[1];
            }

            for(var type in mapCarto) {
              if($scope.isType(type)) {
                for(var prop in mapCarto[type]) {
                  var propRegex = new RegExp(regexEscape(prop) + ':(.*?);');
                  var propMatch = cartocss.match(propRegex);
                  var val = getProp(type, prop);
                  if(propMatch != null) {
                    if(propMatch[1].trim().toLowerCase() != val) {
                      cartocss = cartocss.replace(propRegex, prop + ': ' + val + ';');
                    }
                  } else {
                    cartocss += '\t' + prop + ': ' + val + ';\n';
                  }
                }
              }
            }

            if(tableMatch != null && tableMatch[1]) {
              $scope.cartocss = $scope.cartocss.replace(tableRegex, '#' + $scope.table.title + ' {' + cartocss + '}');
            } else {
              $scope.cartocss = '#' + $scope.table.title + ' {\n' + cartocss + '}';
            }

          }, true);

          $scope.composites = {
            '': 'None',
            'multiply': 'Multiply',
            'screen': 'Screen',
            'overlay': 'Overlay',
            'darken': 'Darken',
            'lighten': 'Lighten',
            'color-dodge': 'Color dodge',
            'color-burn': 'Color burn'
          };

          $scope.types = ['polygon', 'marker'];

          $scope.isType = function(type) {
            return $scope.types.indexOf(type) !== -1;
          };

          $scope.properties = [
            {
              key: 'amount',
              type: 'number',
              values: [1,2,3,4,5,6,7,8,9,10]
            },
            {
              key: 'category',
              type: 'string',
              values: ['category 1', 'category 2', 'category 3']
            }
          ];
        }
      ]
    }
  }
])
<commit_msg>fix add/rm lines and check empty val<commit_after>var ace = AceEditor.instance();

angular.module('domegis')

.directive('domegisStyles', [
  function() {
    return {
      restrict: 'E',
      templateUrl: 'client/contents/styles.html',
      scope: {
        content: '='
      },
      controller: [
        '$scope',
        '$reactive',
        '$compile',
        function($scope, $reactive, $compile) {

          $scope.aceOption = {
            mode: 'css',
            useWrapMode: false,
            showGutter: false,
            theme: 'github'
          };

          $scope.table = {
            title: 'table'
          };

          $scope.styles = {
            polygon: {
              composite: '',
              fill: {
                color: '#f00',
                opacity: .8,
              },
              stroke: {
                color: '#0f0',
                width: 1,
                opacity: .8
              }
            },
            marker: {
              composite: '',
              fill: {
                width: 10,
                color: '#00f',
                opacity: 1
              },
              stroke: {
                color: '#0f0',
                width: .5,
                opacity: .8
              }
            }
          };

          var mapCarto = {
            'polygon': {
              'polygon-fill': 'fill.color',
              'polygon-opacity': 'fill.opacity',
              'polygon-comp-op': 'composite',
              'line-color': 'stroke.color',
              'line-width': 'stroke.width',
              'line-opacity': 'stroke.opacity'
            },
            'marker': {
              'marker-width': 'fill.width',
              'marker-fill': 'fill.color',
              'marker-fill-opacity': 'fill.opacity',
              'marker-comp-op': 'composite',
              'marker-line-color': 'stroke.color',
              'marker-line-width': 'stroke.width',
              'marker-line-opacity': 'stroke.opacity'
            }
          };

          var getProp = function(type, name) {
            var val = '';
            if(mapCarto[type][name]) {
              return eval('$scope.styles.' + type + '.' + mapCarto[type][name]);
            }
            return val;
          }

          function regexEscape(str) {
            return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
          }

          $scope.cartocss = '';

          var tableRegex = new RegExp(regexEscape('#' + $scope.table.title + ' {') + '([\\s\\S]*?)}');

          // Update styles object from raw CartoCSS
          $scope.$watch('cartocss', function(cartocss) {
            var tableMatch = cartocss.match(tableRegex);
            if(tableMatch != null && tableMatch[1]) {
              for(var type in mapCarto) {
                if($scope.isType(type)) {
                  for(var prop in mapCarto[type]) {
                    var propRegex = new RegExp(regexEscape(prop) + ':(.*?);');
                    var propMatch = cartocss.match(propRegex);
                    if(propMatch != null) {
                      eval('$scope.styles.' + type + '.' + mapCarto[type][prop] + ' = propMatch[1].trim().toLowerCase()');
                    }
                  }
                }
              }
            }
          });

          // Update CartoCSS output from styles object
          $scope.$watch('styles', function(styles, prevStyles) {

            var tableMatch = $scope.cartocss.match(tableRegex);

            var cartocss = '';

            if(tableMatch != null && tableMatch[1]) {
              cartocss = tableMatch[1];
            }

            for(var type in mapCarto) {
              if($scope.isType(type)) {
                for(var prop in mapCarto[type]) {
                  var propRegex = new RegExp('\t' + regexEscape(prop) + ':(.*?);\n');
                  var propMatch = cartocss.match(propRegex);
                  var val = getProp(type, prop);
                  if(propMatch != null) {
                    var rep = '';
                    if(val !== '')
                      rep = '\t' + prop + ': ' + val + ';\n';
                    if(propMatch[1].trim().toLowerCase() != val) {
                      cartocss = cartocss.replace(propRegex, rep);
                    }
                  } else {
                    if(val !== '')
                      cartocss += '\t' + prop + ': ' + val + ';\n';
                  }
                }
              }
            }

            if(tableMatch != null && tableMatch[1]) {
              $scope.cartocss = $scope.cartocss.replace(tableRegex, '#' + $scope.table.title + ' {' + cartocss + '}');
            } else {
              $scope.cartocss = '#' + $scope.table.title + ' {\n' + cartocss + '}';
            }

          }, true);

          $scope.composites = {
            '': 'None',
            'multiply': 'Multiply',
            'screen': 'Screen',
            'overlay': 'Overlay',
            'darken': 'Darken',
            'lighten': 'Lighten',
            'color-dodge': 'Color dodge',
            'color-burn': 'Color burn'
          };

          $scope.types = ['polygon', 'marker'];

          $scope.isType = function(type) {
            return $scope.types.indexOf(type) !== -1;
          };

          $scope.properties = [
            {
              key: 'amount',
              type: 'number',
              values: [1,2,3,4,5,6,7,8,9,10]
            },
            {
              key: 'category',
              type: 'string',
              values: ['category 1', 'category 2', 'category 3']
            }
          ];
        }
      ]
    }
  }
])
<|endoftext|>


<commit_before>Template.layout.events({
    'click .updates': function(){
        var obj = getOffset($('.updates')[0]),
            updatesDiv = $('.updates-div');

        if(updatesDiv.is(":visible")){
            updatesDiv.hide();
        } else {
            updatesDiv.offset({ top: obj.top, left: obj.left});
            updatesDiv.show();
            updatesDiv.offset({ top: obj.top, left: obj.left});
        }
    },
    "click #login-buttons-logout": function(event){
        Session.set('updates', 'none');
    }
});

function getOffset(el){
    el = el.getBoundingClientRect();
    return {
        top: el.bottom + window.scrollY + 19,
        left: el.left + window.scrollX - 290
    }
}

Template.trueHeader.helpers({
    updates: function(){
        var sessionUpdates = Session.get('updates');
        return ReactiveMethod.call("getFiveUpdates", sessionUpdates);
    },
    usernameFromId: function(){
        return Meteor.users.findOne(this.userId, {fields: {username: 1}}).username;
    },
    ideologyNameFromId: function(){
        return Ideologies.findOne(this.ideologyId, {fields: {name: 1}}).name;
    },
    workFromId: function(){
        return Works.findOne(this.worksId, {fields: {_id: 1}});
    }
});

Template.trueHeader.events({
    "click .update-link": function(event){
        if(event.target.id){
            Session.set("updates", !Session.get("updates"));
            Meteor.call('addCheckedRatingToUser', event.target.id, function(err, res){
            });
            $('.updates-div').hide();
        }
    }
});

Template.layout.rendered = function(){
    $('body').on('keydown', function(e){
        if(e.which === 27){
            $('.updates-div').hide();
        }
    });

    $('body').on('click', function(e){
        if(e.target.className !== "updates-div" && e.target.className !== "updates"
            && e.target.className !== "updates-cog fa fa-cog"){
            $('.updates-div').hide();
        }
    });
}<commit_msg>Towards making Updates look better - fit window when resizing<commit_after>Template.layout.events({
    'click .updates': function(){
        var obj = getUpdatesOffset($('.updates')[0]),
            updatesDiv = $('.updates-div');

        if(updatesDiv.is(":visible")){
            updatesDiv.hide();
        } else {
            updatesDiv.offset(obj);
            updatesDiv.show();
            updatesDiv.offset(obj);
        }
    },
    "click #login-buttons-logout": function(event){
        Session.set('updates', 'none');
    }
});

function getUpdatesOffset(el){
    el = el.getBoundingClientRect();
    return {
        top: el.bottom + window.scrollY + 19,
        left: el.right + window.scrollX - 290
    }
}

Template.trueHeader.helpers({
    updates: function(){
        var sessionUpdates = Session.get('updates');
        return ReactiveMethod.call("getFiveUpdates", sessionUpdates);
    },
    usernameFromId: function(){
        return Meteor.users.findOne(this.userId, {fields: {username: 1}}).username;
    },
    ideologyNameFromId: function(){
        return Ideologies.findOne(this.ideologyId, {fields: {name: 1}}).name;
    },
    workFromId: function(){
        return Works.findOne(this.worksId, {fields: {_id: 1}});
    }
});

Template.trueHeader.events({
    "click .update-link": function(event){
        if(event.target.id){
            Session.set("updates", !Session.get("updates"));
            Meteor.call('addCheckedRatingToUser', event.target.id, function(err, res){
            });
            $('.updates-div').hide();
        }
    }
});

Template.layout.rendered = function(){
    $('body').on('keydown', function(e){
        if(e.which === 27){
            $('.updates-div').hide();
        }
    });

    $('body').on('click', function(e){
        if(e.target.className !== "updates-div" && e.target.className !== "updates"
            && e.target.className !== "updates-cog fa fa-cog"){
            $('.updates-div').hide();
        }
    });

    $(window).resize(function(){
        if(Meteor.userId()){
            var obj = getUpdatesOffset($('.updates')[0]),
                updatesDiv = $('.updates-div');

                updatesDiv.offset(obj);
                updatesDiv.show();
                updatesDiv.offset(obj);
        }
    });
}<|endoftext|>


<commit_before>var SQ = SQ || {};

SQ.TazioGame = function TazioGame (screenCanvas, settings) {
	this.lastUpdate = Date.now();
	this.settings = this.normalizeSettings(settings, this.defaultSettings);

	this.assetManager = new SQ.AssetManager({
		assetsToLoad: this.assetsToLoad,
		step: this.assetStep.bind(this),
		error: this.assetError.bind(this),
		success: this.assetSuccess.bind(this)
	});
	this.maxToLoad = this.assetManager.maxToLoad;

	this.loadingScreen = new SQ.LoadingScreen("blue");
	this.loadingScreen.addToDom();
};

/* Loop Management */

SQ.TazioGame.prototype.update = function update () {

};

SQ.TazioGame.prototype.draw = function draw () {

};

SQ.TazioGame.prototype.loop = function loop () {
	var deltaTime = Date.now() - this.lastUpdate;
	while (deltaTime > this.settings.loopTime) {
		deltaTime -= this.settings.loopTime;
		this.lastUpdate += this.settings.loopTime;
		this.update();
		this.draw();
	}
	requestAnimationFrame(this.loop.bind(this));
};

/* Asset Management */

SQ.TazioGame.prototype.assetStep = function assetStep (toLoad, event) {
	this.loadingScreen.setBar((this.maxToLoad - toLoad) / this.maxToLoad);
	this.loadingScreen.setMessage((this.maxToLoad - toLoad) + "/" + this.maxToLoad + " images loaded");
};

SQ.TazioGame.prototype.assetError = function assetError (toLoad, event) {
	this.loadingScreen.setBar((this.maxToLoad - toLoad) / this.maxToLoad);
	this.loadingScreen.setMessage("Error while loading image! (" + (this.maxToLoad - toLoad) + "/" + this.maxToLoad + ")");
};

SQ.TazioGame.prototype.assetSuccess = function assetError () {
	console.log("Images loaded, removing loadingScreen");
	setTimeout(function () {
		this.loadingScreen.removeFromDom();
		delete this.loadingScreen;
		this.loop();
	}.bind(this), 200);
};

/* Settings */

SQ.TazioGame.prototype.normalizeSettings = function normalizeSettings (settings, defaultSettings) {
	settings = settings || {};
	for (var setting in defaultSettings) {
		if (defaultSettings[setting] === "object") {
			settings[setting] = {};
			settings[setting] = this.normalizeSettings(settings[setting], defaultSettings[setting]);
		} else {
			settings[setting] = (typeof settings[setting] === "undefined") ? defaultSettings[setting] : settings[setting];
		}
	}
	return settings;
};

/* DATA */

SQ.TazioGame.prototype.defaultSettings = {
	loopTime: 1000 / 60
};

SQ.TazioGame.prototype.assetsToLoad = {
	images: {
		tiles: {
			grass: "images/terrain_atlas.png"
		}
	},
	jsondata: {
		mapFile: "js/mapFile.json"
	}
};

SQ.tazioGame = new SQ.TazioGame(document.getElementById("taziosscreen"));<commit_msg>Changed text "images" to "resources"<commit_after>var SQ = SQ || {};

SQ.TazioGame = function TazioGame (screenCanvas, settings) {
	this.lastUpdate = Date.now();
	this.settings = this.normalizeSettings(settings, this.defaultSettings);

	this.assetManager = new SQ.AssetManager({
		assetsToLoad: this.assetsToLoad,
		step: this.assetStep.bind(this),
		error: this.assetError.bind(this),
		success: this.assetSuccess.bind(this)
	});
	this.maxToLoad = this.assetManager.maxToLoad;

	this.loadingScreen = new SQ.LoadingScreen("blue");
	this.loadingScreen.addToDom();
};

/* Loop Management */

SQ.TazioGame.prototype.update = function update () {

};

SQ.TazioGame.prototype.draw = function draw () {

};

SQ.TazioGame.prototype.loop = function loop () {
	var deltaTime = Date.now() - this.lastUpdate;
	while (deltaTime > this.settings.loopTime) {
		deltaTime -= this.settings.loopTime;
		this.lastUpdate += this.settings.loopTime;
		this.update();
		this.draw();
	}
	requestAnimationFrame(this.loop.bind(this));
};

/* Asset Management */

SQ.TazioGame.prototype.assetStep = function assetStep (toLoad, event) {
	this.loadingScreen.setBar((this.maxToLoad - toLoad) / this.maxToLoad);
	this.loadingScreen.setMessage((this.maxToLoad - toLoad) + "/" + this.maxToLoad + " resources loaded");
};

SQ.TazioGame.prototype.assetError = function assetError (toLoad, event) {
	this.loadingScreen.setBar((this.maxToLoad - toLoad) / this.maxToLoad);
	this.loadingScreen.setMessage("Error while loading resource! (" + (this.maxToLoad - toLoad) + "/" + this.maxToLoad + ")");
};

SQ.TazioGame.prototype.assetSuccess = function assetError () {
	console.log("Resources loaded, removing loadingScreen");
	setTimeout(function () {
		this.loadingScreen.removeFromDom();
		delete this.loadingScreen;
		this.loop();
	}.bind(this), 200);
};

/* Settings */

SQ.TazioGame.prototype.normalizeSettings = function normalizeSettings (settings, defaultSettings) {
	settings = settings || {};
	for (var setting in defaultSettings) {
		if (defaultSettings[setting] === "object") {
			settings[setting] = {};
			settings[setting] = this.normalizeSettings(settings[setting], defaultSettings[setting]);
		} else {
			settings[setting] = (typeof settings[setting] === "undefined") ? defaultSettings[setting] : settings[setting];
		}
	}
	return settings;
};

/* DATA */

SQ.TazioGame.prototype.defaultSettings = {
	loopTime: 1000 / 60
};

SQ.TazioGame.prototype.assetsToLoad = {
	images: {
		tiles: {
			grass: "images/terrain_atlas.png"
		}
	},
	jsondata: {
		mapFile: "js/mapFile.json"
	}
};

SQ.tazioGame = new SQ.TazioGame(document.getElementById("taziosscreen"));<|endoftext|>


<commit_before>function Clock(conn) {
	var self = this;

	var curTime = 0;
	self.time = function () {
		return curTime;
	};

	var offset = 0;
	var appliedOffset = 0;
	var prevNow = now();
	var prevTime = 0;
	self.update = function () {
		var curNow = now();
		var dt = curNow - prevNow;
		var doff = offset - appliedOffset;
		appliedOffset += min(abs(dt*0.5), abs(doff)) * signum(doff);

		curTime = appliedOffset + curNow;
		if (curTime < prevTime) {
			debugger;
		}
		prevNow = curNow;
		prevTime = curTime;
	};

	function signum(n) {
		if (n > 0) return 1;
		else if (n < 0) return -1;
		else return 0;
	}

	self.init = function (serverTime) {
		offset = calcOffset(clientTime, serverTime, serverTime, now());
		appliedOffset = offset;
		conn.on('ntp-sync', proccessSync);
		startSync();
	}

	var clientTime = now();
	function startSync() {
		clientTime = now();
		conn.queue('ntp-sync', {});
	}

	// http://en.wikipedia.org/wiki/Network_Time_Protocol
	function calcOffset(t0, t1, t2, t3) {
		var newOffset = ((t1 - t0) + (t2 - t3)) / 2;
		console.log("Syncronized time with server. We were off by ", offset - newOffset, "ms.");
		console.log("Round trip connection based ping is", t3 - t0, "ms");
		return newOffset;
	}

	function proccessSync(payload) {
		var serverTime = payload.ServerTime;
		offset = calcOffset(clientTime, serverTime, serverTime, now());

		// Re-sync in 5 seconds
		setTimeout(startSync, 5000);
	}

	function now() {
		return window.performance.now();
	}
}
<commit_msg>Cleanup partial time sync application. Should fix #67.<commit_after>function Clock(conn) {
	var self = this;

	var curTime = 0;
	// Only updated after you call .update(). This way, all
	// things querying the time in a frame will get the
	// same time.
	self.time = function () {
		return curTime;
	};

	// Actual client <-> server offset, according to most
	// recent sync.
	var offset = 0;
	// How much of the offset we've actually applied. We
	// don't want to apply it all at once, because that will
	// cause lots of jerk.
	var appliedOffset = 0;
	var prevNow = now();
	self.update = function () {
		var curNow = now();
		var dt = curNow - prevNow;
		var doff = offset - appliedOffset;
		appliedOffset += min(abs(dt*0.5), abs(doff)) * signum(doff);

		curTime = appliedOffset + curNow;
		prevNow = curNow;
	};

	function signum(n) {
		if (n > 0) return 1;
		else if (n < 0) return -1;
		else return 0;
	}

	self.init = function (serverTime) {
		offset = calcOffset(clientTime, serverTime, serverTime, now());
		appliedOffset = offset;
		conn.on('ntp-sync', proccessSync);
		startSync();
	}

	var clientTime = now();
	function startSync() {
		clientTime = now();
		conn.queue('ntp-sync', {});
	}

	// http://en.wikipedia.org/wiki/Network_Time_Protocol
	function calcOffset(t0, t1, t2, t3) {
		var newOffset = ((t1 - t0) + (t2 - t3)) / 2;
		console.log("Syncronized time with server. We were off by ", offset - newOffset, "ms.");
		console.log("Round trip connection based ping is", t3 - t0, "ms");
		return newOffset;
	}

	function proccessSync(payload) {
		var serverTime = payload.ServerTime;
		offset = calcOffset(clientTime, serverTime, serverTime, now());

		// Re-sync in 5 seconds
		setTimeout(startSync, 5000);
	}

	function now() {
		return window.performance.now();
	}
}
<|endoftext|>


<commit_before>function workcalendar(){
  var c = $('#work-calendar');
  var events = [];

  function addToList(date){
    console.log(date);
    $.get('/work/'+date+'/events', function(data) {
      if(data){
        if(data.constructor === Array){
          data.forEach(function(event) {
            events.push(event);
          });
        }else{
          events.push(data);
        }

        c.fullCalendar('removeEvents');
        c.fullCalendar('addEventSource', events);
      }
    });
  }

  var updateEvents = function(view, element){
    events = [];
    var start = view.start;
    var end = view.end;

    var current = start;
    while(current.add(1, 'days').diff(end, 'days') < 0){
      if(currentUser.scheduleObject.scheduleDays[current.format("MM/DD/YY")] !== undefined){
        addToList(current.format("YYYY-MM-DD"));
      }
    }
  }

  c.fullCalendar({
    weekends: false,
    header: {
			left: 'prev,next today',
			center: 'title',
			right: 'month,basicWeek,basicDay'
		},
    dayRender: function(date, cell) {
      var dateString = date.format("MM/DD/YY");
      var sd = currentUser.scheduleObject.scheduleDays[dateString];
      if(sd !== undefined){
        cell.append(''+sd+'-Day');
      }
    },
    viewRender: updateEvents,
    eventRender: function(event, element) {
      element.html(event.title);
    },
    eventMouseover: function(event, jsEvent, view) {
      //$(this).html(event.description);
    },
    eventMouseout: function function_name(event, jsEvent, view) {
      //$(this).html(event.title);
    }
  });

  updateEvents(c.fullCalendar('getView'), null);

}
<commit_msg>Improved calendar<commit_after>function workcalendar(){
  var c = $('#work-calendar');
  var events = [];

  function addToList(date, viewtype){
    console.log(viewtype);

    if(viewtype !== "month"){
      var sd = currentUser.scheduleObject.scheduleDays[date.format("MM/DD/YY")];
      if(sd){
        var periods = currentUser.scheduleObject.dayClasses[sd];
        periods.forEach(function(p) {
          if(p.className.indexOf(" Advisement") == -1){
            var start = moment(date.format("YYYY-MM-DD")+" "+p.startTime, "YYYY-MM-DD hh:mm A");
            var end = moment(date.format("YYYY-MM-DD")+" "+p.endTime, "YYYY-MM-DD hh:mm A");

            var color = 'rgb(204, 200, 203)';
            if(p.className !== "Lunch" && p.className !== "Unstructured Time"){
              color = "#2780E3";
            }

            events.push({
              title: p.className.split("(")[0],
              room: p.room,
              start: start,
              end: end,
              color: color,
              itemType: 'period'
            });
          }
        });
      }
    }
    var date = date.format("YYYY-MM-DD");
    $.get('/work/'+date+'/events', function(data) {
      if(data){
        if(data.constructor === Array){
          data.forEach(function(event) {
            events.push(event);
          });
        }else{
          events.push(data);
        }
        c.fullCalendar('removeEvents');
        c.fullCalendar('addEventSource', events);
      }
    });
  }

  var updateEvents = function(view, element){
    events = [];
    var start = view.start;
    var end = view.end;

    var current = start;
    while(current.add(1, 'days').diff(end, 'days') < 0){
      if(currentUser.scheduleObject.scheduleDays[current.format("MM/DD/YY")] !== undefined){
        addToList(current, view.name);
      }
    }
  }

  c.fullCalendar({
    theme: true,
    weekends: false,
    header: {
			left: 'prev,next today',
			center: 'title',
			right: 'month,agendaWeek,agendaDay'
		},
    dayRender: function(date, cell) {
      var dateString = date.format("MM/DD/YY");
      var sd = currentUser.scheduleObject.scheduleDays[dateString];
      if(sd !== undefined){
        cell.append(''+sd+'-Day');
      }
    },
    viewRender: updateEvents,
    defaultView: 'agendaWeek',
    eventRender: function(event, element) {
      element.html(event.title);
    },
    eventMouseover: function(event, jsEvent, view) {
      console.log(event);
      if(event.itemType == "period")
        $(this).html(""+event.room+"");
    },
    eventMouseout: function function_name(event, jsEvent, view) {
      $(this).html(event.title);
    },
    minTime: "08:40:00",
    maxTime: "16:00:00",
    slotDuration: "00:20:00"
  });

  updateEvents(c.fullCalendar('getView'), null);
}
<|endoftext|>


<commit_before>AudioPlayer = {
    audioElement: new Audio(),

    canPlay: function(song) {
        var self = this;
        return self.audioElement.canPlayType(song.mime);
    },
    load: function(song, successCallback, errorCallback, options) {
        var self = this;
        if(self.audioElement.currentSrc) {
            self.audioElement.pause();
            Session.set('currentSong', undefined);
        }
        var successCallback2 = function() {
            Session.set('currentSong', song);
            if(successCallback) {
                successCallback();
            }
        };
        var errorCallback2 = function(error) {
            if(!(error instanceof Error)) {
                error = new Error(error);
            }
            if(errorCallback) {
                errorCallback(error);
            }
        };
        if(song.owner == Meteo.userId()) {
            self.loadFromUrl(MusicManager.localCollection.findOne({ _id: song._id }).url, successCallback2, errorCallback2);
        } else if(song.url) {
            self.loadFromUrl(song.url, successCallback2, errorCallback2);
        } else {
            MusicManager.requestSong(song.owner, song._id, function(url) {
                self.loadFromUrl(url, successCallback2, errorCallback2);
            }, errorCallback2, options);
        }
    },
    loadFromUrl: function(url, successCallback, errorCallback) {
        var self = this;
        var loadCallback = function(url) {
            self.audioElement.src = url;
            self.audioElement.load();
            if(successCallback) {
                successCallback();
            }
        }
        if(url.indexOf('indexeddb:') != 0) {
            loadCallback(url);
        } else {
            MusicManager.localStorage.readFileFromUrl(url, function(fileEntry) {
                loadCallback(URL.createObjectURL(fileEntry));
            }, errorCallback);
        }
    }
}
<commit_msg>Fix typo<commit_after>AudioPlayer = {
    audioElement: new Audio(),

    canPlay: function(song) {
        var self = this;
        return self.audioElement.canPlayType(song.mime);
    },
    load: function(song, successCallback, errorCallback, options) {
        var self = this;
        if(self.audioElement.currentSrc) {
            self.audioElement.pause();
            Session.set('currentSong', undefined);
        }
        var successCallback2 = function() {
            Session.set('currentSong', song);
            if(successCallback) {
                successCallback();
            }
        };
        var errorCallback2 = function(error) {
            if(!(error instanceof Error)) {
                error = new Error(error);
            }
            if(errorCallback) {
                errorCallback(error);
            }
        };
        if(song.owner == Meteor.userId()) {
            self.loadFromUrl(MusicManager.localCollection.findOne({ _id: song._id }).url, successCallback2, errorCallback2);
        } else if(song.url) {
            self.loadFromUrl(song.url, successCallback2, errorCallback2);
        } else {
            MusicManager.requestSong(song.owner, song._id, function(url) {
                self.loadFromUrl(url, successCallback2, errorCallback2);
            }, errorCallback2, options);
        }
    },
    loadFromUrl: function(url, successCallback, errorCallback) {
        var self = this;
        var loadCallback = function(url) {
            self.audioElement.src = url;
            self.audioElement.load();
            if(successCallback) {
                successCallback();
            }
        }
        if(url.indexOf('indexeddb:') != 0) {
            loadCallback(url);
        } else {
            MusicManager.localStorage.readFileFromUrl(url, function(fileEntry) {
                loadCallback(URL.createObjectURL(fileEntry));
            }, errorCallback);
        }
    }
}
<|endoftext|>


<commit_before>Template.pokerTab.helpers({
	setSelected: function() {
		var gameSelected, rankingSelected, winnersSelected;
		switch (this.selected) {
			case 'game':
				gameSelected = 'selected';
				break;
			case 'ranking':
				rankingSelected = 'selected';
				break;
			case 'winners':
				winnersSelected = 'selected';
				break;
		}
		return {
			gameSelected: gameSelected,
			rankingSelected: rankingSelected,
			winnersSelected: winnersSelected
		};
	}
});

Template.pokerCounters.onCreated(function() {
	// Init
	var instance = this;
	// Ranking
	instance.weekPosition = new ReactiveVar(null);
});

Template.pokerCounters.helpers({
	weekPosition: function() {
		var instance = Template.instance();
		var weekTotal = Counts.get('weekTotal');
		Meteor.call('getRankingPosition', weekTotal, function(e, weekPosition) {
			instance.weekPosition.set(weekPosition);
		});
		return instance.weekPosition.get();
	}
})

Template.bisPoker.onCreated(function() {
	// Init
	var instance = this;
	// Cards
	instance.card0value = new ReactiveVar(null);
	instance.card0status = new ReactiveVar(false);
	instance.card1value = new ReactiveVar(null);
	instance.card1status = new ReactiveVar(false);
	instance.card2value = new ReactiveVar(null);
	instance.card2status = new ReactiveVar(false);
	instance.card3value = new ReactiveVar(null);
	instance.card3status = new ReactiveVar(false);
	instance.card4value = new ReactiveVar(null);
	instance.card4status = new ReactiveVar(false);
	// Messages
	instance.winMessage = new ReactiveVar(null);
	instance.statusMessage = new ReactiveVar(null);
	// Status
	instance.statusPlay = new ReactiveVar();

	// populate initial data from controller
	instance.populateInitialData = function(data) {
		instance.card0value.set(data.deck[0]);
		instance.card1value.set(data.deck[1]);
		instance.card2value.set(data.deck[2]);
		instance.card3value.set(data.deck[3]);
		instance.card4value.set(data.deck[4]);
		instance.winMessage.set(data.winMessage);
		instance.statusMessage.set(data.statusMessage);
		instance.statusPlay.set(data.statusPlay);
		if (data.statusPlay == 'cambia' && data.bet && data.handId) {
			Bisia.Poker.handId = data.handId;
			Bisia.Poker.currentHandBet = data.bet;
			Bisia.Poker.firstHand = data.firstHand;
			$('#value'+ data.bet).prop('checked', true);
			Bisia.Poker.buildChangeDeck(data.deck, instance);
		}
	};

});

Template.bisPoker.onRendered(function() {
	// Init
	var instance = this;

	instance.autorun(function() {

		for (i = 0; i < 5; i++) {
			instance['$card' + i] = $('#card' + i);
			instance['$card' + i].prop('checked', instance['card' + i + 'status'].get());
			instance['$card' + i].val(instance['card' + i + 'value'].get());
		}

	});

	// Init data from controller (status of play)
	// console.log(instance.data);
	instance.populateInitialData(instance.data);

});

Template.bisPoker.helpers({
	deckValues: function() {
		var instance = Template.instance();
		instance.dailyCredit = Counts.get('countDailyCredit');
		return {
			card0: instance.card0value.get(),
			card1: instance.card1value.get(),
			card2: instance.card2value.get(),
			card3: instance.card3value.get(),
			card4: instance.card4value.get(),
			winMessage: instance.winMessage.get(),
			statusMessage: instance.statusMessage.get(),
			statusPlay: instance.statusPlay.get()
		}
	},
	allowCredits: function(credit) {
		var instance = Template.instance();
		var dailyCredit = instance.dailyCredit;
		var status = instance.statusPlay.get();
		if (parseInt(credit) > dailyCredit) {
			return 'disabled';
		}
	},
	outOfCredit: function() {
		var instance = Template.instance();
		var status = instance.statusPlay.get();
		var credit = instance.dailyCredit;
		return credit == 0 && status == 'apri';
	},
	isDisabled: function() {
		var instance = Template.instance();
		var status = instance.statusPlay.get();
		if (status == 'apri') return 'disabled';
	},
	printNextCredits: function() {
		var credit = Bisia.Poker.credit;
		var midDay = moment().set('hour', 12).set('minute', 0).set('second', 0);
		if (moment().isBefore(midDay)) {
			return 'Ne riceverai ulteriori '+credit+' alle ore 12:00';
		} else {
			return 'Riceverai nuovi '+credit+' crediti a mezzanotte.';
		}
	}
});

Template.bisPoker.events({
	'click .card[data-value]': function(e, instance) {
		e.preventDefault();
		// get the card
		var $card = $(e.currentTarget);
		// toggle the class
		$card.toggleClass('open');
		// get parameters
		var cardId = $card.data('control');
		var cardChecked = $card.hasClass('open');
		// set status
		instance[cardId + 'status'].set(cardChecked);
	},
	'click [name=bet]': function(e, instance) {
		$('#play').removeAttr('disabled');
	},
	'submit #poker-form': function(e, instance) {
		e.preventDefault();
		var $target = $(e.target);

		var formObject = Bisia.Form.getFields($target, null, {
			'card0': 'cards.card0',
			'card1': 'cards.card1',
			'card2': 'cards.card2',
			'card3': 'cards.card3',
			'card4': 'cards.card4',
		});

		if (formObject.play.length > 0) {

			switch (formObject.play) {
				case 'apri':
					Bisia.Poker.actionPlayGame(formObject, instance);
					break;
				case 'cambia':
					Bisia.Poker.actionChangeGame(formObject, instance);
					break;
				case 'gioca':
					Bisia.Poker.actionResetGame(instance);
					break;
				default:
					alert('game not valid');
			}

		} else {
			alert('game not valid');
		}
	}
});

Template.playerItem.onRendered(function() {
	var rankingInstance = this.parentTemplate();
	if (rankingInstance.$('.ranking[data-value='+this.data.ranking+']').length > 1) {
		rankingInstance.$('.ranking[data-value='+this.data.ranking+']').not().eq(1).hide();
	}
	return this;
});

Template.playerItem.events({
	'click [data-view=hands]': function(e, t) {
		Bisia.Ui.toggleModal(e, 'playerHandsModal', this);
	}
});

Template.bisPokerRanking.helpers({
	generateRankings: function() {
		var ranking = {};
		var counter = 1;
		_.each(this.items.fetch(), function(player) {
			if (!ranking[player.points]) {
				ranking[player.points] = counter;
				counter ++;
			}
		});
		this.ranking = ranking;
		return this;
	},
	getPlayer: function(obj, ranking) {
		var instance = Template.instance();
		var user = Users.findOne({ '_id': obj.playerId }, { 'fields': {
			'username': 1,
			'profile.city': 1,
			'profile.gender': 1,
			'profile.status': 1,
			'profile.avatar': 1,
			'profile.online': 1,
			'profile.birthday': 1
		}});

		// add ranking to the first of ranking position
		// if (!Bisia.Poker.ranking[this.points]) {
			user.ranking = ranking[this.points];
			// Bisia.Poker.ranking[this.points] = ranking[this.points];
		// }

		return _.extend(this, user);
	},
	detectFirstPage: function() {
		var increment = Bisia.getController('increment');
		var limit = Bisia.getController('params')['pageLimit'];
		// Don't show spinner by default
		var pageDisplay = true;
		// If we are on the first page...
		if (!limit || limit == increment) {
			// pageDisplay becomes reactive
			pageDisplay = this.pageReady;
		}
		// Add pageDisplay to this
		return _.extend(this, {
			pageDisplay: pageDisplay
		});
	},
	weekNumber: function() {
		return moment().format('w');
	},
	weekStart: function() {
		return Bisia.Poker.weekStart('dddd DD');
	},
	weekStop: function() {
		return Bisia.Poker.weekStop('dddd DD MMMM YYYY');
	}
});

Template.bisPokerRanking.events({
	'scroll .content': function(e, t) {
		Bisia.Ui.toggleAtBottom(e, '#helpbars', 'bottom-show');
	}
});

Template.winnerItem.helpers({
	getPlayer: function(obj) {
		var user = Users.findOne({ '_id': obj.winnerId }, { 'fields': {
			'username': 1,
			'profile.city': 1,
			'profile.gender': 1,
			'profile.status': 1,
			'profile.avatar': 1,
			'profile.online': 1,
			'profile.birthday': 1
		}});
		return _.extend(this, user);
	},
});

Template.playerHandsModal.onCreated(function() {
	var instance = this;
	// run paginator
	Bisia.Paginator.init(instance, {
		subsTo: 'playerHands',
		collection: 'pokerhands',
		query: {
			'playerId': '_id',
			'status': 'finish'
		}
	});
});

Template.playerHandsModal.helpers({
	getTitle: function() {
		return {
			title: "Le mani di " + this.username
		}
	},
	formatDeck: function() {
		return {
			createdAt: this.createdAt,
			bet: this.bet,
			win: this.win,
			winning: this.winMessage.replace('Hai', 'Ha').replace('hai', 'ha'),
			card0: this.changeDeck[0],
			card1: this.changeDeck[1],
			card2: this.changeDeck[2],
			card3: this.changeDeck[3],
			card4: this.changeDeck[4]
		};
	},
	playerHands: function() {
		return Template.instance().getData();
	},
	hasMoreData: function() {
		return Template.instance().hasMoreData.get();
	},
	pageReady: function() {
		return Template.instance().ready.get();
	}
});

Template.playerHandsModal.events({
	'scroll .content': function(e, t) {
		Bisia.Paginator.triggerBottom(e);
	}
});

Template.cardItem.helpers({
	newTime: function() {
		return '?' + new Date().getTime();
	}
});<commit_msg>forcing poker images redraw time cache killer<commit_after>Template.pokerTab.helpers({
	setSelected: function() {
		var gameSelected, rankingSelected, winnersSelected;
		switch (this.selected) {
			case 'game':
				gameSelected = 'selected';
				break;
			case 'ranking':
				rankingSelected = 'selected';
				break;
			case 'winners':
				winnersSelected = 'selected';
				break;
		}
		return {
			gameSelected: gameSelected,
			rankingSelected: rankingSelected,
			winnersSelected: winnersSelected
		};
	}
});

Template.pokerCounters.onCreated(function() {
	// Init
	var instance = this;
	// Ranking
	instance.weekPosition = new ReactiveVar(null);
});

Template.pokerCounters.helpers({
	weekPosition: function() {
		var instance = Template.instance();
		var weekTotal = Counts.get('weekTotal');
		Meteor.call('getRankingPosition', weekTotal, function(e, weekPosition) {
			instance.weekPosition.set(weekPosition);
		});
		return instance.weekPosition.get();
	}
})

Template.bisPoker.onCreated(function() {
	// Init
	var instance = this;
	// Cards
	instance.card0value = new ReactiveVar(null);
	instance.card0status = new ReactiveVar(false);
	instance.card1value = new ReactiveVar(null);
	instance.card1status = new ReactiveVar(false);
	instance.card2value = new ReactiveVar(null);
	instance.card2status = new ReactiveVar(false);
	instance.card3value = new ReactiveVar(null);
	instance.card3status = new ReactiveVar(false);
	instance.card4value = new ReactiveVar(null);
	instance.card4status = new ReactiveVar(false);
	// Messages
	instance.winMessage = new ReactiveVar(null);
	instance.statusMessage = new ReactiveVar(null);
	// Status
	instance.statusPlay = new ReactiveVar();

	// populate initial data from controller
	instance.populateInitialData = function(data) {
		instance.card0value.set(data.deck[0]);
		instance.card1value.set(data.deck[1]);
		instance.card2value.set(data.deck[2]);
		instance.card3value.set(data.deck[3]);
		instance.card4value.set(data.deck[4]);
		instance.winMessage.set(data.winMessage);
		instance.statusMessage.set(data.statusMessage);
		instance.statusPlay.set(data.statusPlay);
		if (data.statusPlay == 'cambia' && data.bet && data.handId) {
			Bisia.Poker.handId = data.handId;
			Bisia.Poker.currentHandBet = data.bet;
			Bisia.Poker.firstHand = data.firstHand;
			$('#value'+ data.bet).prop('checked', true);
			Bisia.Poker.buildChangeDeck(data.deck, instance);
		}
	};

});

Template.bisPoker.onRendered(function() {
	// Init
	var instance = this;

	instance.autorun(function() {

		for (i = 0; i < 5; i++) {
			instance['$card' + i] = $('#card' + i);
			instance['$card' + i].prop('checked', instance['card' + i + 'status'].get());
			instance['$card' + i].val(instance['card' + i + 'value'].get());
		}

	});

	// Init data from controller (status of play)
	// console.log(instance.data);
	instance.populateInitialData(instance.data);

});

Template.bisPoker.helpers({
	deckValues: function() {
		var instance = Template.instance();
		instance.dailyCredit = Counts.get('countDailyCredit');
		return {
			card0: instance.card0value.get(),
			card1: instance.card1value.get(),
			card2: instance.card2value.get(),
			card3: instance.card3value.get(),
			card4: instance.card4value.get(),
			winMessage: instance.winMessage.get(),
			statusMessage: instance.statusMessage.get(),
			statusPlay: instance.statusPlay.get()
		}
	},
	allowCredits: function(credit) {
		var instance = Template.instance();
		var dailyCredit = instance.dailyCredit;
		var status = instance.statusPlay.get();
		if (parseInt(credit) > dailyCredit) {
			return 'disabled';
		}
	},
	outOfCredit: function() {
		var instance = Template.instance();
		var status = instance.statusPlay.get();
		var credit = instance.dailyCredit;
		return credit == 0 && status == 'apri';
	},
	isDisabled: function() {
		var instance = Template.instance();
		var status = instance.statusPlay.get();
		if (status == 'apri') return 'disabled';
	},
	printNextCredits: function() {
		var credit = Bisia.Poker.credit;
		var midDay = moment().set('hour', 12).set('minute', 0).set('second', 0);
		if (moment().isBefore(midDay)) {
			return 'Ne riceverai ulteriori '+credit+' alle ore 12:00';
		} else {
			return 'Riceverai nuovi '+credit+' crediti a mezzanotte.';
		}
	}
});

Template.bisPoker.events({
	'click .card[data-value]': function(e, instance) {
		e.preventDefault();
		// get the card
		var $card = $(e.currentTarget);
		// toggle the class
		$card.toggleClass('open');
		// get parameters
		var cardId = $card.data('control');
		var cardChecked = $card.hasClass('open');
		// set status
		instance[cardId + 'status'].set(cardChecked);
	},
	'click [name=bet]': function(e, instance) {
		$('#play').removeAttr('disabled');
	},
	'submit #poker-form': function(e, instance) {
		e.preventDefault();
		var $target = $(e.target);

		var formObject = Bisia.Form.getFields($target, null, {
			'card0': 'cards.card0',
			'card1': 'cards.card1',
			'card2': 'cards.card2',
			'card3': 'cards.card3',
			'card4': 'cards.card4',
		});

		if (formObject.play.length > 0) {

			switch (formObject.play) {
				case 'apri':
					Bisia.Poker.actionPlayGame(formObject, instance);
					break;
				case 'cambia':
					Bisia.Poker.actionChangeGame(formObject, instance);
					break;
				case 'gioca':
					Bisia.Poker.actionResetGame(instance);
					break;
				default:
					alert('game not valid');
			}

		} else {
			alert('game not valid');
		}
	}
});

Template.playerItem.onRendered(function() {
	var rankingInstance = this.parentTemplate();
	if (rankingInstance.$('.ranking[data-value='+this.data.ranking+']').length > 1) {
		rankingInstance.$('.ranking[data-value='+this.data.ranking+']').not().eq(1).hide();
	}
	return this;
});

Template.playerItem.events({
	'click [data-view=hands]': function(e, t) {
		Bisia.Ui.toggleModal(e, 'playerHandsModal', this);
	}
});

Template.bisPokerRanking.helpers({
	generateRankings: function() {
		var ranking = {};
		var counter = 1;
		_.each(this.items.fetch(), function(player) {
			if (!ranking[player.points]) {
				ranking[player.points] = counter;
				counter ++;
			}
		});
		this.ranking = ranking;
		return this;
	},
	getPlayer: function(obj, ranking) {
		var instance = Template.instance();
		var user = Users.findOne({ '_id': obj.playerId }, { 'fields': {
			'username': 1,
			'profile.city': 1,
			'profile.gender': 1,
			'profile.status': 1,
			'profile.avatar': 1,
			'profile.online': 1,
			'profile.birthday': 1
		}});

		// add ranking to the first of ranking position
		// if (!Bisia.Poker.ranking[this.points]) {
			user.ranking = ranking[this.points];
			// Bisia.Poker.ranking[this.points] = ranking[this.points];
		// }

		return _.extend(this, user);
	},
	detectFirstPage: function() {
		var increment = Bisia.getController('increment');
		var limit = Bisia.getController('params')['pageLimit'];
		// Don't show spinner by default
		var pageDisplay = true;
		// If we are on the first page...
		if (!limit || limit == increment) {
			// pageDisplay becomes reactive
			pageDisplay = this.pageReady;
		}
		// Add pageDisplay to this
		return _.extend(this, {
			pageDisplay: pageDisplay
		});
	},
	weekNumber: function() {
		return moment().format('w');
	},
	weekStart: function() {
		return Bisia.Poker.weekStart('dddd DD');
	},
	weekStop: function() {
		return Bisia.Poker.weekStop('dddd DD MMMM YYYY');
	}
});

Template.bisPokerRanking.events({
	'scroll .content': function(e, t) {
		Bisia.Ui.toggleAtBottom(e, '#helpbars', 'bottom-show');
	}
});

Template.winnerItem.helpers({
	getPlayer: function(obj) {
		var user = Users.findOne({ '_id': obj.winnerId }, { 'fields': {
			'username': 1,
			'profile.city': 1,
			'profile.gender': 1,
			'profile.status': 1,
			'profile.avatar': 1,
			'profile.online': 1,
			'profile.birthday': 1
		}});
		return _.extend(this, user);
	},
});

Template.playerHandsModal.onCreated(function() {
	var instance = this;
	// run paginator
	Bisia.Paginator.init(instance, {
		subsTo: 'playerHands',
		collection: 'pokerhands',
		query: {
			'playerId': '_id',
			'status': 'finish'
		}
	});
});

Template.playerHandsModal.helpers({
	getTitle: function() {
		return {
			title: "Le mani di " + this.username
		}
	},
	formatDeck: function() {
		return {
			createdAt: this.createdAt,
			bet: this.bet,
			win: this.win,
			winning: this.winMessage.replace('Hai', 'Ha').replace('hai', 'ha'),
			card0: this.changeDeck[0],
			card1: this.changeDeck[1],
			card2: this.changeDeck[2],
			card3: this.changeDeck[3],
			card4: this.changeDeck[4]
		};
	},
	playerHands: function() {
		return Template.instance().getData();
	},
	hasMoreData: function() {
		return Template.instance().hasMoreData.get();
	},
	pageReady: function() {
		return Template.instance().ready.get();
	}
});

Template.playerHandsModal.events({
	'scroll .content': function(e, t) {
		Bisia.Paginator.triggerBottom(e);
	}
});

Template.cardItem.helpers({
	newTime: function() {
		return '?t=' + new Date().getTime();
	}
});<|endoftext|>


<commit_before>import React from 'react'
import { compose, withHandlers, withProps } from 'recompact'

import styled from 'styled-components'
import { withCard } from '../data/card'
import { withCampaignId } from '../data/campaign'
import withLoading from '../control/loading'
import { Form, withFormData } from '../control/form'
import { iAmOwner } from '../data/owner'
import TypeSelect from '../collection/type-select'
import preventingDefault from '../utils/preventing-default'
import { Card } from '../../shared/methods'
import { LabelledInput } from '../visual/primitives'
import { Input, Textarea, BonelessInput } from '../visual/form'
import AccessForm from '../control/privacy'
import Icon from '../visual/icon'
import schema from '../../shared/schema'
import { go } from '../utils/router'
import { ImageSelectModal } from '../control/image-select'
import { Main } from '../visual/grid'
import {
	SplashBleed,
	Hero,
	HeroTitle,
	SplashAccessory,
	HeroBlurb
} from '../visual/splash'
import withImage from '../data/image'
import {
	SplashToolbar,
	Center,
	Space,
	Divider,
	MenuButton,
	MenuItem
} from '../visual/menu'

const connectFormSplash = compose(
	withFormData,
	withProps({ small: true }),
	withImage(({ fields }) => fields.cover)
)

const FormCardSplash = connectFormSplash(SplashBleed)

const SchemaFields = withFormData(({ fields }) =>
	fields.type ? (
		<>
			{_.map(schema[fields.type].fields, ({ label, format, ...field }, key) => (
				<MenuItem key={key} flush>
					<LabelledInput>

{label}

						<Input {...field} key={key} name={key} />
					</LabelledInput>
				</MenuItem>
			))}
			<Divider />
		</>
	) : null
)

const ContentsForm = withProps({
	tag: styled.form`
		display: contents;
	`
})(Form)

const FloatMenuItem = styled.div`
	display: flex;
	padding: 0 1rem;
	align-items: center;
	font-size: 0.9em;
`

const EditCard = ({ card = {}, saveCard, back, deleteCard, isOwner }) => (
	<ContentsForm initialData={card} onSubmit={saveCard}>
		<FormCardSplash>
			<SplashAccessory right>
				<ImageSelectModal name='cover' />
			</SplashAccessory>

			<Hero>
				<HeroTitle>
					<BonelessInput required name='title' placeholder='Title' />
				</HeroTitle>
				<HeroBlurb>
					<BonelessInput name='subtitle' placeholder='Subtitle' />
				</HeroBlurb>
			</Hero>
		</FormCardSplash>

		<SplashToolbar>

				<TypeSelect name='type' placeholder='Type...' />
				<Divider />
				<SchemaFields />

				{(isOwner || !card._id) && (
					<>
						<AccessForm {...card} flush tag={FloatMenuItem} />
						<Divider />
					</>
				)}

				<Space />
				<MenuButton>
					{card._id ? <Icon icon='check' /> : <Icon icon='plus' />}
					{card._id ? 'Save' : 'Create'}
				</MenuButton>
				{back && (
					<MenuButton onClick={preventingDefault(back)}>
						<Icon icon='times' /> Cancel
					</MenuButton>
				)}
				{deleteCard && card._id && (
					<MenuButton colour='scarlet' onClick={deleteCard}>
						<Icon icon='trash' /> Delete
					</MenuButton>
				)}

		</SplashToolbar>

			<Textarea fullWidth name='text' />

	</ContentsForm>
)

const editCardActions = withHandlers({
	saveCard: ({ card, campaignId }) => async data => {
		let _id

		if (card) {
			_id = card._id
			Card.update(card, data)
		} else {
			_id = (await Card.create({
				...data,
				campaignId
			}))._id
		}

		go(`/${campaignId}/${_id}`)
	},

	deleteCard: ({ card }) => ev => {
		ev.preventDefault()

		if (confirm(`Are you sure you want to delete ${card.title}?`)) {
			Card.delete(card)
			go(`/${card.campaignId}`)
		}
	},

	back: ({ card, campaignId }) => () => {
		go(`/${campaignId}/${card ? card._id : ''}`)
	}
})

const withCardData = compose(
	withCampaignId,
	withCard,
	withLoading,
	editCardActions,
	iAmOwner('card')
)

export default withCardData(EditCard)
<commit_msg>too many dividers?<commit_after>import React from 'react'
import { compose, withHandlers, withProps } from 'recompact'

import styled from 'styled-components'
import { withCard } from '../data/card'
import { withCampaignId } from '../data/campaign'
import withLoading from '../control/loading'
import { Form, withFormData } from '../control/form'
import { iAmOwner } from '../data/owner'
import TypeSelect from '../collection/type-select'
import preventingDefault from '../utils/preventing-default'
import { Card } from '../../shared/methods'
import { LabelledInput } from '../visual/primitives'
import { Input, Textarea, BonelessInput } from '../visual/form'
import AccessForm from '../control/privacy'
import Icon from '../visual/icon'
import schema from '../../shared/schema'
import { go } from '../utils/router'
import { ImageSelectModal } from '../control/image-select'
import { Main } from '../visual/grid'
import {
	SplashBleed,
	Hero,
	HeroTitle,
	SplashAccessory,
	HeroBlurb
} from '../visual/splash'
import withImage from '../data/image'
import {
	SplashToolbar,
	Center,
	Space,
	Divider,
	MenuButton,
	MenuItem
} from '../visual/menu'

const connectFormSplash = compose(
	withFormData,
	withProps({ small: true }),
	withImage(({ fields }) => fields.cover)
)

const FormCardSplash = connectFormSplash(SplashBleed)

const SchemaFields = withFormData(({ fields }) =>
	fields.type ? (
		<>
			{_.map(schema[fields.type].fields, ({ label, format, ...field }, key) => (
				<MenuItem key={key} flush>
					<LabelledInput>

{label}

						<Input {...field} key={key} name={key} />
					</LabelledInput>
				</MenuItem>
			))}
			<Divider />
		</>
	) : null
)

const ContentsForm = withProps({
	tag: styled.form`
		display: contents;
	`
})(Form)

const FloatMenuItem = styled.div`
	display: flex;
	padding: 0 1rem;
	align-items: center;
	font-size: 0.9em;
`

const EditCard = ({ card = {}, saveCard, back, deleteCard, isOwner }) => (
	<ContentsForm initialData={card} onSubmit={saveCard}>
		<FormCardSplash>
			<SplashAccessory right>
				<ImageSelectModal name='cover' />
			</SplashAccessory>

			<Hero>
				<HeroTitle>
					<BonelessInput required name='title' placeholder='Title' />
				</HeroTitle>
				<HeroBlurb>
					<BonelessInput name='subtitle' placeholder='Subtitle' />
				</HeroBlurb>
			</Hero>
		</FormCardSplash>

		<SplashToolbar>

				<TypeSelect name='type' placeholder='Type...' />
				<Divider />
				<SchemaFields />

				{(isOwner || !card._id) && (
					<AccessForm {...card} flush tag={FloatMenuItem} />
				)}

				<Space />
				<MenuButton>
					{card._id ? <Icon icon='check' /> : <Icon icon='plus' />}
					{card._id ? 'Save' : 'Create'}
				</MenuButton>
				{back && (
					<MenuButton onClick={preventingDefault(back)}>
						<Icon icon='times' /> Cancel
					</MenuButton>
				)}
				{deleteCard && card._id && (
					<MenuButton colour='scarlet' onClick={deleteCard}>
						<Icon icon='trash' /> Delete
					</MenuButton>
				)}

		</SplashToolbar>

			<Textarea fullWidth name='text' />

	</ContentsForm>
)

const editCardActions = withHandlers({
	saveCard: ({ card, campaignId }) => async data => {
		let _id

		if (card) {
			_id = card._id
			Card.update(card, data)
		} else {
			_id = (await Card.create({
				...data,
				campaignId
			}))._id
		}

		go(`/${campaignId}/${_id}`)
	},

	deleteCard: ({ card }) => ev => {
		ev.preventDefault()

		if (confirm(`Are you sure you want to delete ${card.title}?`)) {
			Card.delete(card)
			go(`/${card.campaignId}`)
		}
	},

	back: ({ card, campaignId }) => () => {
		go(`/${campaignId}/${card ? card._id : ''}`)
	}
})

const withCardData = compose(
	withCampaignId,
	withCard,
	withLoading,
	editCardActions,
	iAmOwner('card')
)

export default withCardData(EditCard)
<|endoftext|>