<commit_before>/*  ==========================================================================
	Grunt configuration
	==========================================================================  */

'use strict';

function getIP() {

	var os = require('os');
	var interfaces = os.networkInterfaces();
	var addresses = [];
	for (var k in interfaces) {
		for (var k2 in interfaces[k]) {
			var address = interfaces[k][k2];
			if (address.family === 'IPv4' && !address.internal) {
				addresses.push(address.address);
			}
		}
	}
	return addresses[0];

}

module.exports = function(grunt) {

	// Load all grunt task in package.json

	require('jit-grunt')(grunt, {
		browser_sync : 'grunt-browser-sync'
	});

	grunt.initConfig({

		// Reads dependencies from package.json

		pkg: grunt.file.readJSON('package.json'),

		// noxie config

		noxie: {
			dev: 'app',					// Development folder
			deploy: 'deploy',			// Deploy folder
			hostname: getIP(),			// Set '*' or '0.0.0.0' to access the server from outside
			serverPort: 8000,			// Server port
			livereloadPort: 35729,		// Port number or boolean
			weinrePort: 8080,			// Weinre port
			banner: '/*! <%= pkg.title %> v<%= pkg.version %> | (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %> <%= pkg.author.url %> */\n'
		},

		// [ grunt autoprefixer ] Prefixes css3 propreties (https://github.com/nDmitry/grunt-autoprefixer)

		autoprefixer: {
			options: {
				browsers: [
					'last 3 version',
					'> 1%',
					'ie 8',
					'ie 7'
				]
			},
			dev: {
				files: {
					'<%= noxie.dev %>/css/main.css': ['<%= noxie.dev %>/css/main.css']
				}
			},
			deploy: {
				files: {
					'<%= noxie.deploy %>/css/main.css': ['<%= noxie.deploy %>/css/main.css']
				}
			}
		},

		// [ browser sync ] Keeps multiple devices ( https://github.com/shakyShane/grunt-browser-sync )

		browser_sync: {
			options: {
				debugInfo: true,
				ghostMode: {
					clicks: true,
					scroll: true,
					links: true,
					forms: true
				},
				host: '<%= noxie.hostname %>',
				server: {
					baseDir: '<%= noxie.dev %>'
				}
			},
			bsFiles: {
				src : [
					'<%= noxie.dev %>/css/{,*/}*.css',
					'<%= noxie.dev %>/**/*.html',
					'<%= noxie.dev %>/js/{,*/}*.js',
					'<%= noxie.dev %>/img/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
				]
			}
		},

		// [ grunt clean ] Cleans deploy direcory (https://github.com/gruntjs/grunt-contrib-clean)

		clean: {
			deploy: {
				src: [ '<%= noxie.deploy %>']
			}
		},

		// [ grunt concat ] Concatenate javascript files (https://github.com/gruntjs/grunt-contrib-concat)

		concat: {
			options: {
				separator: ';'
			},
			dev: {
				src: ['<%= noxie.dev %>/js/plugins/*.js'],
				dest: '<%= noxie.dev %>/js/plugins.js'
			},
			deploy: {
				src: ['<%= noxie.dev %>/js/plugins/*.js'],
				dest: '<%= noxie.deploy %>/js/plugins.js'
			}
		},

		// [ grunt cssmin:deploy ] Combines and minifies css (https://github.com/gruntjs/grunt-contrib-cssmin)

		cssmin: {
			deploy: {
				expand: true,
				cwd: '<%= noxie.deploy %>/css/',
				src: ['main.css'],
				dest: '<%= noxie.deploy %>/css/'
			}
		},

		// [ grunt copy ] Copies files for deployment (https://github.com/gruntjs/grunt-contrib-copy)

		copy: {
			deploy: {
				files: [{
					expand: true,
					dot: true,
					cwd: '<%= noxie.dev %>',
					src: ['**', '!scss/**', '!js/plugins/**'],
					dest: '<%= noxie.deploy %>/'
				}]
			}
		},

		// [ grunt concurrent ] Runs multiple tasks (https://github.com/sindresorhus/grunt-concurrent)

		concurrent: {
			dev: {
				tasks: [
					'jshint',
					'sass:dev',
					'autoprefixer:dev',
					'concat:dev',
					'weinre',
					'notify:server',
					'open',
					'watch',
					'browser_sync'
				],
				options: {
					logConcurrentOutput: true
				}
			}
		},

		// [ grunt htmlmin ] Compresses html ( https://github.com/gruntjs/grunt-contrib-htmlmin )

		htmlmin: {
			deploy: {
				options: {
					removeComments: true,
					collapseWhitespace: true
				},
				files: [{
					expand: true,        // Enable dynamic expansion.
					cwd: '<%= noxie.deploy %>',  // Src matches are relative to this path.
					src: ['*.html'],     // Actual pattern(s) to match.
					dest: '<%= noxie.deploy %>'  // Destination path prefix.
			}]
			}
		},

		// [ grunt imagemin ] Images optimization (https://github.com/gruntjs/grunt-contrib-imagemin)

		imagemin: {
			options: {
				optimizationLevel: 3,
				progressive: true
			},
			deploy: {
				files: [{
					expand: true,
					cwd: '<%= noxie.deploy %>/img/',
					src: ['**/*.{png,jpg,gif}'],
					dest: '<%= noxie.deploy %>/img/'
				}]
			}
		},

		// [ grunt jshint ] Validate files with JSHint (https://github.com/gruntjs/grunt-contrib-jshint)

		jshint: {
			options: {
				jshintrc: '.jshintrc',
				errorsOnly: true, // only display errors
				failOnError: false, // defaults to true
				reporter: require('jshint-stylish')
			},
			all: ['<%= noxie.dev %>/js/main.js']
		},

		// [ grunt notify ] Desktop notifications for Grunt errors and warnings using Growl for OS X or Windows, Mountain Lion Notification Center, Snarl, and Notify-Send (https://github.com/dylang/grunt-notify)

		notify: {
			bower: {
				options: {
					title: 'Bower',
					message: 'New package added in bower_components/',
				}
			},
			weinre: {
				options: {
					title: 'Browser',
					message: 'Weinre server launched on http://<%= noxie.hostname %>:<%= noxie.weinrePort %>/',
				}
			},
			server: {
				options:{
					title: 'Browser',
					message:'Server started on http://<%= noxie.hostname %>:<%= noxie.serverPort %>/'
				}
			},
			imagemin: {
				options: {
					title: 'Minification',
					message: 'Image minification done successfully',
				}
			},
			jshint: {
				options: {
					title: 'JSHint',
					message: 'Js validation done successfully',
					max_jshint_notifications: 5
				}
			},
			sass: {
				options: {
					title: 'Sass',
					message: 'SASS Compilation done successfully',
				}
			}
		},

		// [grunt open:weinre ] Opens weinre url in default web browser (https://github.com/jsoverson/grunt-open)

		open: {
			weinre: {
				path: 'http://<%= noxie.hostname %>:<%= noxie.weinrePort %>/client/#anonymous'
			}
		},

		// [ grunt sass:dev ] Compiles main.scss in development mode (https://github.com/gruntjs/grunt-contrib-sass)
		// [ grunt sass:deploy ] Compiles main.scss in distribution mode

		sass: {
			dev: {
				files: {
					'<%= noxie.dev %>/css/main.css': '<%= noxie.dev %>/scss/main.scss'
				},
				options: {
					banner: '<%= noxie.banner %>',
					debugInfo: true,		// enable if you want to use FireSass
					lineNumbers: true,
					sourcemap: false,		// Requires Sass 3.3.0, which can be installed with gem install sass --pre
					style: 'expanded'
				}
			},
			deploy: {
				files: {
					'<%= noxie.deploy %>/css/main.css': '<%= noxie.dev %>/scss/main.scss'
				},
				options: {
					banner: '<%= noxie.banner %>',
					style: 'compressed'
				}
			}
		},

		// [ grunt uglify ] Javascript plugins compressor (https://github.com/gruntjs/grunt-contrib-uglify)

		uglify: {
			options: {
				banner: '<%= noxie.banner %>'
			},
			deploy: {
				files: {
					'<%= noxie.deploy %>/js/plugins.js': ['<%= noxie.deploy %>/js/plugins.js'],
					'<%= noxie.deploy %>/js/main.js': ['<%= noxie.deploy %>/js/main.js']
				}
			}
		},

		// [ grunt svgmin ] Svg compressor (https://github.com/sindresorhus/grunt-svgmin)

		svgmin: {
			deploy: {
				files: [{
					expand: true,
					cwd: '<%= noxie.deploy %>/img',
					src: ['**/*.svg'],
					dest: '<%= noxie.deploy %>/img/',
				}]
			}
		},

		// [ grunt watch ] Watches for file changes and optimizes images, concats and minifies scripts in plugins and also starts a livereload server (https://github.com/gruntjs/grunt-contrib-watch)

		watch: {
			css: {
				files: '<%= noxie.dev %>/scss/{,*/}*.{scss,sass}',
				tasks: [
					'sass:dev',
					'autoprefixer:dev',
					'notify:sass'
				]
			},
			bower: {
				files: 'bower_components/{,*/}*.*',
				tasks: [
					'notify:bower'
				]
			},
			plugins: {
				files: '<%= noxie.dev %>/js/plugins/*.js',
				tasks: ['concat:dev']
			},
			jshint: {
				files: '<%= noxie.dev %>/js/main.js',
				tasks: ['jshint']
			}
		},

		// [grunt weinre ]

		weinre: {
			dev: {
				options: {
					httpPort: '<%= noxie.weinrePort %>',
					boundHost: '-all-',
					verbose: false,
					debug: false,
					readTimeout: 5,
					deathTimeout: 15
				}
			}
		}

	});

	// Register tasks

	grunt.registerTask('default', [
		'concurrent:dev'
	]);

	grunt.registerTask('deploy', [
		'jshint',
		'clean:deploy',
		'copy:deploy',
		'htmlmin:deploy',
		'sass:deploy',
		'autoprefixer:deploy',
		'cssmin:deploy',
		'imagemin:deploy',
		'concat:deploy',
		'svgmin:deploy',
		'uglify:deploy'
	]);

};
<commit_msg>Open server on deploy<commit_after>/*  ==========================================================================
	Grunt configuration
	==========================================================================  */

'use strict';

function getIP() {

	var os = require('os');
	var interfaces = os.networkInterfaces();
	var addresses = [];
	for (var k in interfaces) {
		for (var k2 in interfaces[k]) {
			var address = interfaces[k][k2];
			if (address.family === 'IPv4' && !address.internal) {
				addresses.push(address.address);
			}
		}
	}
	return addresses[0];

}

module.exports = function(grunt) {

	// Load all grunt task in package.json

	require('jit-grunt')(grunt, {
		browser_sync : 'grunt-browser-sync'
	});

	grunt.initConfig({

		// Reads dependencies from package.json

		pkg: grunt.file.readJSON('package.json'),

		// noxie config

		noxie: {
			dev: 'app',					// Development folder
			deploy: 'deploy',			// Deploy folder
			hostname: getIP(),			// Set '*' or '0.0.0.0' to access the server from outside
			serverPort: 8000,			// Server port
			livereloadPort: 35729,		// Port number or boolean
			weinrePort: 8080,			// Weinre port
			banner: '/*! <%= pkg.title %> v<%= pkg.version %> | (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %> <%= pkg.author.url %> */\n'
		},

		// [ grunt autoprefixer ] Prefixes css3 propreties (https://github.com/nDmitry/grunt-autoprefixer)

		autoprefixer: {
			options: {
				browsers: [
					'last 3 version',
					'> 1%',
					'ie 8',
					'ie 7'
				]
			},
			dev: {
				files: {
					'<%= noxie.dev %>/css/main.css': ['<%= noxie.dev %>/css/main.css']
				}
			},
			deploy: {
				files: {
					'<%= noxie.deploy %>/css/main.css': ['<%= noxie.deploy %>/css/main.css']
				}
			}
		},

		// [ browser sync ] Keeps multiple devices ( https://github.com/shakyShane/grunt-browser-sync )

		browser_sync: {
			dev: {
				options: {
					debugInfo: true,
					ghostMode: {
						clicks: true,
						scroll: true,
						links: true,
						forms: true
					},
					host: '<%= noxie.hostname %>',
					server: {
						baseDir: '<%= noxie.dev %>'
					}
				},
				bsFiles: {
					src : [
						'<%= noxie.dev %>/css/{,*/}*.css',
						'<%= noxie.dev %>/**/*.html',
						'<%= noxie.dev %>/js/{,*/}*.js',
						'<%= noxie.dev %>/img/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
					]
				}
			},
			deploy: {
				options: {
					debugInfo: false,
					ghostMode: {
						clicks: true,
						scroll: true,
						links: true,
						forms: true
					},
					host: '<%= noxie.hostname %>',
					server: {
						baseDir: '<%= noxie.deploy %>'
					}
				},
			}
		},

		// [ grunt clean ] Cleans deploy direcory (https://github.com/gruntjs/grunt-contrib-clean)

		clean: {
			deploy: {
				src: [ '<%= noxie.deploy %>']
			}
		},

		// [ grunt concat ] Concatenate javascript files (https://github.com/gruntjs/grunt-contrib-concat)

		concat: {
			options: {
				separator: ';'
			},
			dev: {
				src: ['<%= noxie.dev %>/js/plugins/*.js'],
				dest: '<%= noxie.dev %>/js/plugins.js'
			},
			deploy: {
				src: ['<%= noxie.dev %>/js/plugins/*.js'],
				dest: '<%= noxie.deploy %>/js/plugins.js'
			}
		},

		// [ grunt cssmin:deploy ] Combines and minifies css (https://github.com/gruntjs/grunt-contrib-cssmin)

		cssmin: {
			deploy: {
				expand: true,
				cwd: '<%= noxie.deploy %>/css/',
				src: ['main.css'],
				dest: '<%= noxie.deploy %>/css/'
			}
		},

		// [ grunt copy ] Copies files for deployment (https://github.com/gruntjs/grunt-contrib-copy)

		copy: {
			deploy: {
				files: [{
					expand: true,
					dot: true,
					cwd: '<%= noxie.dev %>',
					src: ['**', '!scss/**', '!js/plugins/**'],
					dest: '<%= noxie.deploy %>/'
				}]
			}
		},

		// [ grunt concurrent ] Runs multiple tasks (https://github.com/sindresorhus/grunt-concurrent)

		concurrent: {
			dev: {
				tasks: [
					'jshint',
					'sass:dev',
					'autoprefixer:dev',
					'concat:dev',
					'weinre',
					'notify:server',
					'open',
					'watch',
					'browser_sync'
				],
				options: {
					logConcurrentOutput: true
				}
			}
		},

		// [ grunt htmlmin ] Compresses html ( https://github.com/gruntjs/grunt-contrib-htmlmin )

		htmlmin: {
			deploy: {
				options: {
					removeComments: true,
					collapseWhitespace: true
				},
				files: [{
					expand: true,        // Enable dynamic expansion.
					cwd: '<%= noxie.deploy %>',  // Src matches are relative to this path.
					src: ['*.html'],     // Actual pattern(s) to match.
					dest: '<%= noxie.deploy %>'  // Destination path prefix.
			}]
			}
		},

		// [ grunt imagemin ] Images optimization (https://github.com/gruntjs/grunt-contrib-imagemin)

		imagemin: {
			options: {
				optimizationLevel: 3,
				progressive: true
			},
			deploy: {
				files: [{
					expand: true,
					cwd: '<%= noxie.deploy %>/img/',
					src: ['**/*.{png,jpg,gif}'],
					dest: '<%= noxie.deploy %>/img/'
				}]
			}
		},

		// [ grunt jshint ] Validate files with JSHint (https://github.com/gruntjs/grunt-contrib-jshint)

		jshint: {
			options: {
				jshintrc: '.jshintrc',
				errorsOnly: true, // only display errors
				failOnError: false, // defaults to true
				reporter: require('jshint-stylish')
			},
			all: ['<%= noxie.dev %>/js/main.js']
		},

		// [ grunt notify ] Desktop notifications for Grunt errors and warnings using Growl for OS X or Windows, Mountain Lion Notification Center, Snarl, and Notify-Send (https://github.com/dylang/grunt-notify)

		notify: {
			bower: {
				options: {
					title: 'Bower',
					message: 'New package added in bower_components/',
				}
			},
			weinre: {
				options: {
					title: 'Browser',
					message: 'Weinre server launched on http://<%= noxie.hostname %>:<%= noxie.weinrePort %>/',
				}
			},
			server: {
				options:{
					title: 'Browser',
					message:'Server started on http://<%= noxie.hostname %>:<%= noxie.serverPort %>/'
				}
			},
			imagemin: {
				options: {
					title: 'Minification',
					message: 'Image minification done successfully',
				}
			},
			jshint: {
				options: {
					title: 'JSHint',
					message: 'Js validation done successfully',
					max_jshint_notifications: 5
				}
			},
			sass: {
				options: {
					title: 'Sass',
					message: 'SASS Compilation done successfully',
				}
			}
		},

		// [grunt open:weinre ] Opens weinre url in default web browser (https://github.com/jsoverson/grunt-open)

		open: {
			weinre: {
				path: 'http://<%= noxie.hostname %>:<%= noxie.weinrePort %>/client/#anonymous'
			}
		},

		// [ grunt sass:dev ] Compiles main.scss in development mode (https://github.com/gruntjs/grunt-contrib-sass)
		// [ grunt sass:deploy ] Compiles main.scss in distribution mode

		sass: {
			dev: {
				files: {
					'<%= noxie.dev %>/css/main.css': '<%= noxie.dev %>/scss/main.scss'
				},
				options: {
					banner: '<%= noxie.banner %>',
					debugInfo: true,		// enable if you want to use FireSass
					lineNumbers: true,
					sourcemap: false,		// Requires Sass 3.3.0, which can be installed with gem install sass --pre
					style: 'expanded'
				}
			},
			deploy: {
				files: {
					'<%= noxie.deploy %>/css/main.css': '<%= noxie.dev %>/scss/main.scss'
				},
				options: {
					banner: '<%= noxie.banner %>',
					style: 'compressed'
				}
			}
		},

		// [ grunt uglify ] Javascript plugins compressor (https://github.com/gruntjs/grunt-contrib-uglify)

		uglify: {
			options: {
				banner: '<%= noxie.banner %>'
			},
			deploy: {
				files: {
					'<%= noxie.deploy %>/js/plugins.js': ['<%= noxie.deploy %>/js/plugins.js'],
					'<%= noxie.deploy %>/js/main.js': ['<%= noxie.deploy %>/js/main.js']
				}
			}
		},

		// [ grunt svgmin ] Svg compressor (https://github.com/sindresorhus/grunt-svgmin)

		svgmin: {
			deploy: {
				files: [{
					expand: true,
					cwd: '<%= noxie.deploy %>/img',
					src: ['**/*.svg'],
					dest: '<%= noxie.deploy %>/img/',
				}]
			}
		},

		// [ grunt watch ] Watches for file changes and optimizes images, concats and minifies scripts in plugins and also starts a livereload server (https://github.com/gruntjs/grunt-contrib-watch)

		watch: {
			css: {
				files: '<%= noxie.dev %>/scss/{,*/}*.{scss,sass}',
				tasks: [
					'sass:dev',
					'autoprefixer:dev',
					'notify:sass'
				]
			},
			bower: {
				files: 'bower_components/{,*/}*.*',
				tasks: [
					'notify:bower'
				]
			},
			plugins: {
				files: '<%= noxie.dev %>/js/plugins/*.js',
				tasks: ['concat:dev']
			},
			jshint: {
				files: '<%= noxie.dev %>/js/main.js',
				tasks: ['jshint']
			}
		},

		// [grunt weinre ]

		weinre: {
			dev: {
				options: {
					httpPort: '<%= noxie.weinrePort %>',
					boundHost: '-all-',
					verbose: false,
					debug: false,
					readTimeout: 5,
					deathTimeout: 15
				}
			}
		}

	});

	// Register tasks

	grunt.registerTask('default', [
		'concurrent:dev'
	]);

	grunt.registerTask('deploy', [
		'jshint',
		'clean:deploy',
		'copy:deploy',
		'htmlmin:deploy',
		'sass:deploy',
		'autoprefixer:deploy',
		'cssmin:deploy',
		'imagemin:deploy',
		'concat:deploy',
		'svgmin:deploy',
		'uglify:deploy',
		'browser_sync:deploy'
	]);

};
<|endoftext|>


<commit_before>module.exports = function(Weatherreport) {
	Weatherreport.handleChangeError = function(err) {
		console.warn("Cannot update change records for WeatherReport: ", err);
	};
};
<commit_msg>Add with-position WeatherReport endpoint that matches groupId through MobileUser relation.<commit_after>module.exports = function(Weatherreport) {
	Weatherreport.handleChangeError = function(err) {
		console.warn("Cannot update change records for WeatherReport: ", err);
	};

	Weatherreport.withPositions = function(groupId, startDate, endDate, cb) {
		Weatherreport.find({
			include: [{
				relation: 'Position',
				scope: {
					where: {
						timestamp: {
							gte: new Date(startDate),
							lte: new Date(endDate)
						}
					}
				}
			},
			{
				relation: 'MobileUser',
				scope: {
					where: {
						groupId: groupId
					}
				}
			}]
		}, function(err, results) {
			if (err) return cb(err);
			var filteredResults = results.filter(function (result) {
				return result.Position() && result.MobileUser();
			});
			cb(null, filteredResults);
		});
	};

	Weatherreport.remoteMethod('withPositions', {
		http: {path: '/with-positions', verb: 'get'},
		accepts: [
			{arg: 'groupId', type: 'string', 'http': {source: 'query'}, required: true},
			{arg: 'startdate', type: 'string', 'http': {source: 'query'}, required: true},
			{arg: 'enddate', type: 'string', 'http': {source: 'query'}, required: true}
		],
		returns: {arg: 'WeatherReports', type: 'string'}
	});
};
<|endoftext|>


<commit_before>'use strict';

var nodemon;
var browserSync;
var jshint;

var gulp = require('gulp');
var sass = require('gulp-sass');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var clean = require('gulp-clean');
var cssmin = require('gulp-cssmin');
var htmlreplace = require('gulp-html-replace');

gulp.task('default', ['browser-sync'], function () {
    gulp.watch('public/assets/styles/scss/**/*.scss', ['sass']);
});

gulp.task('browser-sync', ['nodemon'], function () {
    return browserSync.init(null, {
        proxy: 'localhost:9000',
        files: ['public/**/*.*']
    });
});

gulp.task('nodemon', ['sass-dev'], function () {
    nodemon = require('gulp-nodemon');
    return nodemon({
        script: 'server.js',
        ignore: ['public/', 'node_modules/']
    });
});

gulp.task('sass-dev', function () {
    browserSync = require('browser-sync');
    return gulp.src('public/assets/styles/scss/**/*.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest('public/assets/styles/css/build'))
        .pipe(browserSync.reload({
            stream: true
        }));
});

gulp.task('production', ['bundle'], function () {
    return gulp.src('public/index.html')
        .pipe(htmlreplace({
            'css': 'assets/styles/css/bundle.css',
            'js': 'assets/js/bundle.js'
        }))
        .pipe(gulp.dest('public'));
});

gulp.task('bundle', ['bundle-js', 'bundle-css'], function () {
    return gulp.src([
        'public/assets/js/build',
        'public/assets/styles/css/build'
    ], { read: false })
        .pipe(clean());
});

gulp.task('bundle-css', ['sass'], function () {
    return gulp.src([
        'public/assets/vendors/angular-material/angular-material.css',
        'public/assets/styles/css/build/main.css'
    ])
        .pipe(cssmin())
        .pipe(concat('bundle.css'))
        .pipe(gulp.dest('public/assets/styles/css'));
});

gulp.task('sass', function () {
    return gulp.src('public/assets/styles/scss/**/*.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest('public/assets/styles/css/build'));
});

gulp.task('bundle-js', ['bundle-js-modules', 'bundle-js-logic', 'bundle-js-vendors'], function () {
    return gulp.src([
        'public/assets/js/build/vendors.js',
        'public/assets/js/build/modules.js',
        'public/assets/js/build/logic.js'
    ])
        .pipe(concat('bundle.js'))
        .pipe(gulp.dest('public/assets/js'));
});

gulp.task('bundle-js-vendors', function () {
    return gulp.src([
        'public/assets/vendors/angular/angular.min.js',
        'public/assets/vendors/angular-animate/angular-animate.min.js',
        'public/assets/vendors/angular-sanitize/angular-sanitize.min.js',
        'public/assets/vendors/angular-aria/angular-aria.min.js',
        'public/assets/vendors/angular-messages/angular-messages.min.js',
        'public/assets/vendors/angular-material/angular-material.min.js',
        'public/assets/vendors/angular-ui-router/release/angular-ui-router.min.js'
    ])
        .pipe(concat('vendors.js'))
        .pipe(gulp.dest('public/assets/js/build'));
});

gulp.task('bundle-js-logic', function () {
    return gulp.src(['public/app/**/*.js', '!public/app/**/*.module.js'])
        .pipe(concat('logic.js'))
        .pipe(uglify())
        .pipe(gulp.dest('public/assets/js/build'));
});

gulp.task('bundle-js-modules', function () {
    return gulp.src('public/app/**/*.module.js')
        .pipe(concat('modules.js'))
        .pipe(uglify())
        .pipe(gulp.dest('public/assets/js/build'));
});

gulp.task('lint', function () {
    jshint = require('gulp-jshint');
    return gulp.src(['public/app/**/*.js', 'backend/**/*.js', 'gulpfile.js'])
        .pipe(jshint('.jshintrc'))
        .pipe(jshint.reporter('jshint-stylish'));
});<commit_msg>Added server.js to lint config<commit_after>'use strict';

var nodemon;
var browserSync;
var jshint;

var gulp = require('gulp');
var sass = require('gulp-sass');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var clean = require('gulp-clean');
var cssmin = require('gulp-cssmin');
var htmlreplace = require('gulp-html-replace');

gulp.task('default', ['browser-sync'], function () {
    gulp.watch('public/assets/styles/scss/**/*.scss', ['sass']);
});

gulp.task('browser-sync', ['nodemon'], function () {
    return browserSync.init(null, {
        proxy: 'localhost:9000',
        files: ['public/**/*.*']
    });
});

gulp.task('nodemon', ['sass-dev'], function () {
    nodemon = require('gulp-nodemon');
    return nodemon({
        script: 'server.js',
        ignore: ['public/', 'node_modules/']
    });
});

gulp.task('sass-dev', function () {
    browserSync = require('browser-sync');
    return gulp.src('public/assets/styles/scss/**/*.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest('public/assets/styles/css/build'))
        .pipe(browserSync.reload({
            stream: true
        }));
});

gulp.task('production', ['bundle'], function () {
    return gulp.src('public/index.html')
        .pipe(htmlreplace({
            'css': 'assets/styles/css/bundle.css',
            'js': 'assets/js/bundle.js'
        }))
        .pipe(gulp.dest('public'));
});

gulp.task('bundle', ['bundle-js', 'bundle-css'], function () {
    return gulp.src([
        'public/assets/js/build',
        'public/assets/styles/css/build'
    ], { read: false })
        .pipe(clean());
});

gulp.task('bundle-css', ['sass'], function () {
    return gulp.src([
        'public/assets/vendors/angular-material/angular-material.css',
        'public/assets/styles/css/build/main.css'
    ])
        .pipe(cssmin())
        .pipe(concat('bundle.css'))
        .pipe(gulp.dest('public/assets/styles/css'));
});

gulp.task('sass', function () {
    return gulp.src('public/assets/styles/scss/**/*.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest('public/assets/styles/css/build'));
});

gulp.task('bundle-js', ['bundle-js-modules', 'bundle-js-logic', 'bundle-js-vendors'], function () {
    return gulp.src([
        'public/assets/js/build/vendors.js',
        'public/assets/js/build/modules.js',
        'public/assets/js/build/logic.js'
    ])
        .pipe(concat('bundle.js'))
        .pipe(gulp.dest('public/assets/js'));
});

gulp.task('bundle-js-vendors', function () {
    return gulp.src([
        'public/assets/vendors/angular/angular.min.js',
        'public/assets/vendors/angular-animate/angular-animate.min.js',
        'public/assets/vendors/angular-sanitize/angular-sanitize.min.js',
        'public/assets/vendors/angular-aria/angular-aria.min.js',
        'public/assets/vendors/angular-messages/angular-messages.min.js',
        'public/assets/vendors/angular-material/angular-material.min.js',
        'public/assets/vendors/angular-ui-router/release/angular-ui-router.min.js'
    ])
        .pipe(concat('vendors.js'))
        .pipe(gulp.dest('public/assets/js/build'));
});

gulp.task('bundle-js-logic', function () {
    return gulp.src(['public/app/**/*.js', '!public/app/**/*.module.js'])
        .pipe(concat('logic.js'))
        .pipe(uglify())
        .pipe(gulp.dest('public/assets/js/build'));
});

gulp.task('bundle-js-modules', function () {
    return gulp.src('public/app/**/*.module.js')
        .pipe(concat('modules.js'))
        .pipe(uglify())
        .pipe(gulp.dest('public/assets/js/build'));
});

gulp.task('lint', function () {
    jshint = require('gulp-jshint');
    return gulp.src(['server.js', 'public/app/**/*.js', 'backend/**/*.js', 'gulpfile.js'])
        .pipe(jshint('.jshintrc'))
        .pipe(jshint.reporter('jshint-stylish'));
});<|endoftext|>


<commit_before>/*
* AUI Base
*/
AUI.add('aui-base', function(A) {

	A.mix(A.Array, {
		remove: function(a, from, to) {
		  var rest = a.slice((to || from) + 1 || a.length);
		  a.length = (from < 0) ? (a.length + from) : from;

		  return a.push.apply(a, rest);
		},

		removeItem: function(a, item) {
			var index = A.Array.indexOf(a, item);

			return A.Array.remove(a, index);
		}
	});

}, '@VERSION', { requires: [ 'yui-base' ] });

/*
* AUI Delayed Task
*/

AUI.add('delayed-task', function(A) {

	var DelayedTask = function(fn, scope, args) {
		var instance = this;

		instance._args = args;
		instance._delay = 0;
		instance._fn = fn;
		instance._id = null;
		instance._scope = scope || instance;
		instance._time = 0;

		instance._base = function() {
			var now = instance._getTime();

			if (now - instance._time >= instance._delay) {
				clearInterval(instance._id);

				instance._id = null;

				instance._fn.apply(instance._scope, instance._args || []);
			}
		};
	};

	DelayedTask.prototype = {
		delay: function(delay, newFn, newScope, newArgs) {
			var instance = this;

			if (instance._id && instance._delay != delay) {
				instance.cancel();
			}

			instance._delay = delay || instance._delay;
			instance._time = instance._getTime();

			instance._fn = newFn || instance._fn;
			instance._scope = newScope || instance._scope;
			instance._args = newArgs || instance._args;

			if (!A.Lang.isArray(instance._args)) {
				instance._args = [instance._args];
			}

			if (!instance._id) {
				if (instance._delay > 0) {
					instance._id = setInterval(instance._base, instance._delay);
				}
				else {
					instance._base();
				}
			}
		},

		cancel: function() {
			var instance = this;

			if (instance._id) {
				clearInterval(instance._id);

				instance._id = null;
			}
		},

		_getTime: function() {
			var instance = this;

			return (+new Date());
		}
	};

	A.DelayedTask = DelayedTask;

}, '@VERSION', { requires: [ 'yui-base' ] });

/*
* AUI Node
*/

AUI.add('aui-node', function(A) {

	var Lang = A.Lang,
		isArray = Lang.isArray,
		isString = Lang.isString,
		isUndefined = Lang.isUndefined,

		INNER_HTML = 'innerHTML',
		NEXT_SIBLING = 'nextSibling',
		NONE = 'none',
		PARENT_NODE = 'parentNode',
		SCRIPT = 'script',
		VALUE = 'value';

	A.mix(A.Node.prototype, {
		appendTo: function(selector) {
			var instance = this;

			A.get(selector).append(instance);
		},

		attr: function(name, value) {
			var instance = this;

			if (!isUndefined(value)) {
				return instance.set(name, value);
			}
			else {
				return instance.get(name) || instance.getAttribute(name);
			}
		},

		empty: function() {
			var instance = this;

			instance.queryAll('>*').remove();

			var el = A.Node.getDOMNode(instance);

			while (el.firstChild) {
				el.removeChild(el.firstChild);
			}

			return instance;
		},

		getDOM: function() {
			var instance = this;

			return A.Node.getDOMNode(instance);
		},

		guid: function(prefix) {
			var instance = this;
			var currentId = instance.get('id');

			if (!currentId) {
				currentId = A.stamp(instance);

				instance.set('id', currentId);
			}

			return currentId;
		},

		hide: function(cssClass) {
			var instance = this;

			instance.addClass(cssClass || instance._hideClass || 'aui-helper-hidden');
		},

		html: function() {
			var args = arguments, length = args.length;

			if (length) {
				this.set(INNER_HTML, args[0]);
			}
			else {
				return this.get(INNER_HTML);
			}

			return this;
		},

		placeAfter: function(content) {
			var instance = this;

			instance.get(PARENT_NODE).insertBefore(content, instance.get(NEXT_SIBLING));
		},

		placeBefore: function(content) {
			var instance = this;

			instance.get(PARENT_NODE).insertBefore(content, instance);
		},

		prependTo: function(selector) {
			var instance = this;

			A.get(selector).prepend(instance);
		},

		text: function(text) {
			var instance = this;
			var el = instance.getDOM();

			if (!isUndefined(text)) {
				text = A.DOM._getDoc(el).createTextNode(text);

				return instance.empty().append(text);
			}

			return instance._getText(el.childNodes);
		},

		selectable: function() {
			var instance = this;

			instance.getDOM().unselectable = 'off';
			instance.detach('selectstart');

			instance.setStyles(
				{
					'MozUserSelect': '',
					'KhtmlUserSelect': ''
				}
			);

			instance.removeClass('aui-helper-unselectable');

			return instance;
		},

		show: function(cssClass) {
			var instance = this;

			instance.removeClass(cssClass || instance._hideClass || 'aui-helper-hidden');
		},

		swallowEvent: function(eventName, preventDefault) {
			var instance = this;

			var fn = function(event) {
				event.stopPropagation();

				if (preventDefault) {
					event.preventDefault();

					event.halt();
				}

				return false;
			};

			if(isArray(eventName)) {
				A.Array.each(
					eventName,
					function(name) {
						instance.on(name, fn);
					}
				);

				return this;
			}
			else {
				instance.on(eventName, fn);
			}

			return instance;
		},

		unselectable: function() {
			var instance = this;

			instance.getDOM().unselectable = 'on';

			instance.swallowEvent('selectstart', true);

			instance.setStyles(
				{
					'MozUserSelect': NONE,
					'KhtmlUserSelect': NONE
				}
			);

			instance.addClass('aui-helper-unselectable');

			return instance;
		},

		val: function(value) {
			var instance = this;

			return instance.attr(VALUE, value);
		},

		_getText: function(childNodes) {
			var instance = this;

			var length = childNodes.length;
			var childNode;

			var str = [];

			for (var i = 0; i < length; i++) {
				childNode = childNodes[i];

				if (childNode && childNode.nodeType != 8) {
					if (childNode.nodeType != 1) {
						str.push(childNode.nodeValue);
					}

					if (childNode.childNodes) {
						str.push(instance._getText(childNode.childNodes));
					}
				}
			}

			return str.join('');
		}
	}, true);

	A.mix(A.Node, {
		globalEval: function(data) {
			if ( data && /\S/.test(data) ) {
				var head = document.getElementsByTagName('head')[0] || document.documentElement;
				var script = document.createElement('script');

				script.type = 'text/javascript';

				if (AUI.support.scriptEval) {
					script.appendChild(document.createTextNode(data));
				}
				else {
					script.text = data;
				}

				head.insertBefore(script, head.firstChild);
				head.removeChild(script);
			}
		},

		evalScript: function(elem) {
			if (elem.src) {
				A.io(elem.src, {
					async: false,
					on: {
						complete: function(i, o) {
							A.Node.globalEval(o.responseText);
						}
					}
				});
			}
			else {
				A.Node.globalEval(elem.text || elem.textContent || elem.innerHTML || '');
			}
		},

		clean: function(html) {
			var TPL_NODE = '

',
				IE_FIX_PADDING_NODE = '
_
';

			// instead of fix all tags to "XHTML"-style, make the firstChild be a valid non-empty tag
			html = IE_FIX_PADDING_NODE + A.Lang.trim(html);

			delete A.DOM._cloneCache[html];

			// wrap in a nodeType == 1, nodeType 11 (document fragment) does not support getElementsByTagName
			var temp = A.Node.create(TPL_NODE).append(
				A.Node.create(html)
			);

			var scripts = temp.getElementsByTagName(SCRIPT);

			scripts.each(function(elem) {
				elem.remove();
			});

			temp.removeChild(A.Node.getDOMNode(temp).firstChild);

			var html = temp.html();

			// avoid IE6 memory leak
			temp = null;

			return [ html, scripts ];
		},

		domManip: function(html, callback) {
			var clean = A.Node.clean(html);
			var content = clean[0];
			var scripts = clean[1];

			if (callback) {
				callback.apply(this, [ content ]);
			}

			scripts.each(function(elem) {
				A.Node.evalScript( A.Node.getDOMNode(elem) );
			});
		}
	});

	A.Node.ATTRS.innerHTML = {
		setter: function(v) {
			var instance = this;

			var defaultSetter = function(value) {
				A.Node.DEFAULT_SETTER.apply(instance, [ INNER_HTML, value ]);
			};

			if (isString(v)) {
				// eval scripts
				v = A.Node.domManip(v, defaultSetter);
			}
			else {
				defaultSetter(v);
			}
		}
	};

	A.NodeList.importMethod(
		A.Node.prototype,
		[
			'after',

			'appendTo',

			'attr',

			'before',

			'empty',

			'hide',

			'html',

			'prepend',

			'prependTo',

			'selectable',

			'show',

			'text',

			'unselectable'
		]
	);

	A.NodeList.prototype.getDOM = function() {
		return A.NodeList.getDOMNodes(this);
	};

}, '@VERSION', { requires: [ 'node' ] });<commit_msg>base.js return instance for chaining on appentTo/show/hide methods;<commit_after>/*
* AUI Base
*/
AUI.add('aui-base', function(A) {

	A.mix(A.Array, {
		remove: function(a, from, to) {
		  var rest = a.slice((to || from) + 1 || a.length);
		  a.length = (from < 0) ? (a.length + from) : from;

		  return a.push.apply(a, rest);
		},

		removeItem: function(a, item) {
			var index = A.Array.indexOf(a, item);

			return A.Array.remove(a, index);
		}
	});

}, '@VERSION', { requires: [ 'yui-base' ] });

/*
* AUI Delayed Task
*/

AUI.add('delayed-task', function(A) {

	var DelayedTask = function(fn, scope, args) {
		var instance = this;

		instance._args = args;
		instance._delay = 0;
		instance._fn = fn;
		instance._id = null;
		instance._scope = scope || instance;
		instance._time = 0;

		instance._base = function() {
			var now = instance._getTime();

			if (now - instance._time >= instance._delay) {
				clearInterval(instance._id);

				instance._id = null;

				instance._fn.apply(instance._scope, instance._args || []);
			}
		};
	};

	DelayedTask.prototype = {
		delay: function(delay, newFn, newScope, newArgs) {
			var instance = this;

			if (instance._id && instance._delay != delay) {
				instance.cancel();
			}

			instance._delay = delay || instance._delay;
			instance._time = instance._getTime();

			instance._fn = newFn || instance._fn;
			instance._scope = newScope || instance._scope;
			instance._args = newArgs || instance._args;

			if (!A.Lang.isArray(instance._args)) {
				instance._args = [instance._args];
			}

			if (!instance._id) {
				if (instance._delay > 0) {
					instance._id = setInterval(instance._base, instance._delay);
				}
				else {
					instance._base();
				}
			}
		},

		cancel: function() {
			var instance = this;

			if (instance._id) {
				clearInterval(instance._id);

				instance._id = null;
			}
		},

		_getTime: function() {
			var instance = this;

			return (+new Date());
		}
	};

	A.DelayedTask = DelayedTask;

}, '@VERSION', { requires: [ 'yui-base' ] });

/*
* AUI Node
*/

AUI.add('aui-node', function(A) {

	var Lang = A.Lang,
		isArray = Lang.isArray,
		isString = Lang.isString,
		isUndefined = Lang.isUndefined,

		INNER_HTML = 'innerHTML',
		NEXT_SIBLING = 'nextSibling',
		NONE = 'none',
		PARENT_NODE = 'parentNode',
		SCRIPT = 'script',
		VALUE = 'value';

	A.mix(A.Node.prototype, {
		appendTo: function(selector) {
			var instance = this;

			A.get(selector).append(instance);

			return instance;
		},

		attr: function(name, value) {
			var instance = this;

			if (!isUndefined(value)) {
				return instance.set(name, value);
			}
			else {
				return instance.get(name) || instance.getAttribute(name);
			}
		},

		empty: function() {
			var instance = this;

			instance.queryAll('>*').remove();

			var el = A.Node.getDOMNode(instance);

			while (el.firstChild) {
				el.removeChild(el.firstChild);
			}

			return instance;
		},

		getDOM: function() {
			var instance = this;

			return A.Node.getDOMNode(instance);
		},

		guid: function(prefix) {
			var instance = this;
			var currentId = instance.get('id');

			if (!currentId) {
				currentId = A.stamp(instance);

				instance.set('id', currentId);
			}

			return currentId;
		},

		hide: function(cssClass) {
			var instance = this;

			instance.addClass(cssClass || instance._hideClass || 'aui-helper-hidden');

			return instance;
		},

		html: function() {
			var args = arguments, length = args.length;

			if (length) {
				this.set(INNER_HTML, args[0]);
			}
			else {
				return this.get(INNER_HTML);
			}

			return this;
		},

		placeAfter: function(content) {
			var instance = this;

			instance.get(PARENT_NODE).insertBefore(content, instance.get(NEXT_SIBLING));
		},

		placeBefore: function(content) {
			var instance = this;

			instance.get(PARENT_NODE).insertBefore(content, instance);
		},

		prependTo: function(selector) {
			var instance = this;

			A.get(selector).prepend(instance);
		},

		text: function(text) {
			var instance = this;
			var el = instance.getDOM();

			if (!isUndefined(text)) {
				text = A.DOM._getDoc(el).createTextNode(text);

				return instance.empty().append(text);
			}

			return instance._getText(el.childNodes);
		},

		selectable: function() {
			var instance = this;

			instance.getDOM().unselectable = 'off';
			instance.detach('selectstart');

			instance.setStyles(
				{
					'MozUserSelect': '',
					'KhtmlUserSelect': ''
				}
			);

			instance.removeClass('aui-helper-unselectable');

			return instance;
		},

		show: function(cssClass) {
			var instance = this;

			instance.removeClass(cssClass || instance._hideClass || 'aui-helper-hidden')

			return instance;
		},

		swallowEvent: function(eventName, preventDefault) {
			var instance = this;

			var fn = function(event) {
				event.stopPropagation();

				if (preventDefault) {
					event.preventDefault();

					event.halt();
				}

				return false;
			};

			if(isArray(eventName)) {
				A.Array.each(
					eventName,
					function(name) {
						instance.on(name, fn);
					}
				);

				return this;
			}
			else {
				instance.on(eventName, fn);
			}

			return instance;
		},

		unselectable: function() {
			var instance = this;

			instance.getDOM().unselectable = 'on';

			instance.swallowEvent('selectstart', true);

			instance.setStyles(
				{
					'MozUserSelect': NONE,
					'KhtmlUserSelect': NONE
				}
			);

			instance.addClass('aui-helper-unselectable');

			return instance;
		},

		val: function(value) {
			var instance = this;

			return instance.attr(VALUE, value);
		},

		_getText: function(childNodes) {
			var instance = this;

			var length = childNodes.length;
			var childNode;

			var str = [];

			for (var i = 0; i < length; i++) {
				childNode = childNodes[i];

				if (childNode && childNode.nodeType != 8) {
					if (childNode.nodeType != 1) {
						str.push(childNode.nodeValue);
					}

					if (childNode.childNodes) {
						str.push(instance._getText(childNode.childNodes));
					}
				}
			}

			return str.join('');
		}
	}, true);

	A.mix(A.Node, {
		globalEval: function(data) {
			if ( data && /\S/.test(data) ) {
				var head = document.getElementsByTagName('head')[0] || document.documentElement;
				var script = document.createElement('script');

				script.type = 'text/javascript';

				if (AUI.support.scriptEval) {
					script.appendChild(document.createTextNode(data));
				}
				else {
					script.text = data;
				}

				head.insertBefore(script, head.firstChild);
				head.removeChild(script);
			}
		},

		evalScript: function(elem) {
			if (elem.src) {
				A.io(elem.src, {
					async: false,
					on: {
						complete: function(i, o) {
							A.Node.globalEval(o.responseText);
						}
					}
				});
			}
			else {
				A.Node.globalEval(elem.text || elem.textContent || elem.innerHTML || '');
			}
		},

		clean: function(html) {
			var TPL_NODE = '

',
				IE_FIX_PADDING_NODE = '
_
';

			// instead of fix all tags to "XHTML"-style, make the firstChild be a valid non-empty tag
			html = IE_FIX_PADDING_NODE + A.Lang.trim(html);

			delete A.DOM._cloneCache[html];

			// wrap in a nodeType == 1, nodeType 11 (document fragment) does not support getElementsByTagName
			var temp = A.Node.create(TPL_NODE).append(
				A.Node.create(html)
			);

			var scripts = temp.getElementsByTagName(SCRIPT);

			scripts.each(function(elem) {
				elem.remove();
			});

			temp.removeChild(A.Node.getDOMNode(temp).firstChild);

			var html = temp.html();

			// avoid IE6 memory leak
			temp = null;

			return [ html, scripts ];
		},

		domManip: function(html, callback) {
			var clean = A.Node.clean(html);
			var content = clean[0];
			var scripts = clean[1];

			if (callback) {
				callback.apply(this, [ content ]);
			}

			scripts.each(function(elem) {
				A.Node.evalScript( A.Node.getDOMNode(elem) );
			});
		}
	});

	A.Node.ATTRS.innerHTML = {
		setter: function(v) {
			var instance = this;

			var defaultSetter = function(value) {
				A.Node.DEFAULT_SETTER.apply(instance, [ INNER_HTML, value ]);
			};

			if (isString(v)) {
				// eval scripts
				v = A.Node.domManip(v, defaultSetter);
			}
			else {
				defaultSetter(v);
			}
		}
	};

	A.NodeList.importMethod(
		A.Node.prototype,
		[
			'after',

			'appendTo',

			'attr',

			'before',

			'empty',

			'hide',

			'html',

			'prepend',

			'prependTo',

			'selectable',

			'show',

			'text',

			'unselectable'
		]
	);

	A.NodeList.prototype.getDOM = function() {
		return A.NodeList.getDOMNodes(this);
	};

}, '@VERSION', { requires: [ 'node' ] });<|endoftext|>


<commit_before>/**
 * Created by bko on 29/5/14.
 */

/**
 * Provides the homepage map functionality only.
 * Requires JQuery, Moment, and leaflet.
 *
 * Because .noconflict() is called by drupal.js use the alternate
 * syntax while preserving $; see http://api.jquery.com/ready
 */
(function ($) {
  var env = Drupal.settings.environment_settings;
  var data_portal_base_url = env.data_portal_base_url;
  var api_base_url = env.gbif_api_base_url + "/v" + env.gbif_api_version;

    Drupal.behaviors.loadMapTiles = {
      attach: function (context, settings) {
        var maxVisible = 300; // at any time
        var delayMsecs = 1000;

        // increment a seed to force randomization and avoid per client caches
        var seed = 0;

        // randomize the initial view port location a little, but not too much
        var startLat = Math.floor(Math.random()*30);
        var startLng = Math.floor(Math.random()*90) - 45;

        var map = L.map('homepageMap', {
          center: [startLng, startLat],
          zoom: 2,
          minZoom: 1,
          touchZoom: false,
          scrollWheelZoom: false,
          doubleClickZoom: false
        });

        var tileURL = data_portal_base_url + '/img/tiles/{z}/{x}/{y}.png';

        L.tileLayer(tileURL, {
          maxZoom: 4,
          minZoom: 0
        }).addTo(map);

        var points = [];
        var visible = []; // at any time

        function initData() {
          for (var i = 0; i < maxVisible; i++) {
            points.push(
              new L.CircleMarker([0, 0], {
                fillColor: '#223E1D',
                weight: 2,
                color: '#FFF',
                fillOpacity: 1,
                opacity: 0.8,
                radius: 4
              })
            );
          }
        }

        /**
         * Gets a page of occurrences from the server
         */
        function getOccurrences() {
          var occurrences = [];
          $.ajax({
            url: api_base_url + '/occurrence/featured?seed=' + seed++,
            success: function(data) {
              $.each(data, function(index, o) {
                occurrences.push(o);
              });
            }, async:false});
          occurrences.reverse; // so we can just pop off the end
          return occurrences;
        }

        var currentPointIdx=0;
        var occurrences = getOccurrences();

        /**
         * Gets a batch from the server and pages through it plotting the points
         */
        function runMap() {
          // get a batch from the server
          if (occurrences.length==0) {
            occurrences = getOccurrences();
          }

          var point = points[currentPointIdx];
          if (point._map && point._map.hasLayer(point._popup)) {
            // popup is open, can't remove this point
          }
          else {
            var occurrence = occurrences.pop();
            if (occurrence!==undefined) {
              point.setLatLng([occurrence.latitude,occurrence.longitude]);
              point.unbindPopup(); // avoid memory leak
              point.bindPopup(
                "
Occurrence of " + occurrence.scientificName +"
" +
                  "Published by " + occurrence.publisher +"" +
                  "
Last indexed " + moment(occurrence.lastInterpreted).fromNow() +"
");
              point.addTo(map); // it should already be
            }
          }

          // move to next one
          currentPointIdx = currentPointIdx + 1;
          // reuse the points
          if (currentPointIdx >= points.length) {
            currentPointIdx = 0;
          }
          setTimeout(runMap, delayMsecs);
        }
        initData();
        runMap();
      }
    }

    function numberWithCommas(x) {
      return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    Drupal.behaviors.loadStats = {
      attach: function (context, settings) {
        $.getJSON(api_base_url + '/occurrence/count?callback=?', function (data)
          { $("#countOccurrences").html(numberWithCommas(data)); }
        );
        $.getJSON(api_base_url + '/species/search?dataset_key=7ddf754f-d193-4cc9-b351-99906754a03b&limit=1&rank=species&status=accepted&status=DOUBTFUL&callback=?', function (data)
          { $("#countSpecies").html(numberWithCommas(data.count)); }
        );
        $.getJSON(api_base_url + '/dataset/search?limit=1&callback=?', function (data)
          { $("#countDatasets").html(numberWithCommas(data.count)); }
        );
        $.getJSON(api_base_url + '/organization/count?callback=?', function (data)
          { $("#countPublishers").html(numberWithCommas(data)); }
        );
      }
    }

}(jQuery));<commit_msg>POR-2680 Use dataset metrics of CoL for species count on the front page.<commit_after>/**
 * Created by bko on 29/5/14.
 */

/**
 * Provides the homepage map functionality only.
 * Requires JQuery, Moment, and leaflet.
 *
 * Because .noconflict() is called by drupal.js use the alternate
 * syntax while preserving $; see http://api.jquery.com/ready
 */
(function ($) {
  var env = Drupal.settings.environment_settings;
  var data_portal_base_url = env.data_portal_base_url;
  var api_base_url = env.gbif_api_base_url + "/v" + env.gbif_api_version;

    Drupal.behaviors.loadMapTiles = {
      attach: function (context, settings) {
        var maxVisible = 300; // at any time
        var delayMsecs = 1000;

        // increment a seed to force randomization and avoid per client caches
        var seed = 0;

        // randomize the initial view port location a little, but not too much
        var startLat = Math.floor(Math.random()*30);
        var startLng = Math.floor(Math.random()*90) - 45;

        var map = L.map('homepageMap', {
          center: [startLng, startLat],
          zoom: 2,
          minZoom: 1,
          touchZoom: false,
          scrollWheelZoom: false,
          doubleClickZoom: false
        });

        var tileURL = data_portal_base_url + '/img/tiles/{z}/{x}/{y}.png';

        L.tileLayer(tileURL, {
          maxZoom: 4,
          minZoom: 0
        }).addTo(map);

        var points = [];
        var visible = []; // at any time

        function initData() {
          for (var i = 0; i < maxVisible; i++) {
            points.push(
              new L.CircleMarker([0, 0], {
                fillColor: '#223E1D',
                weight: 2,
                color: '#FFF',
                fillOpacity: 1,
                opacity: 0.8,
                radius: 4
              })
            );
          }
        }

        /**
         * Gets a page of occurrences from the server
         */
        function getOccurrences() {
          var occurrences = [];
          $.ajax({
            url: api_base_url + '/occurrence/featured?seed=' + seed++,
            success: function(data) {
              $.each(data, function(index, o) {
                occurrences.push(o);
              });
            }, async:false});
          occurrences.reverse; // so we can just pop off the end
          return occurrences;
        }

        var currentPointIdx=0;
        var occurrences = getOccurrences();

        /**
         * Gets a batch from the server and pages through it plotting the points
         */
        function runMap() {
          // get a batch from the server
          if (occurrences.length==0) {
            occurrences = getOccurrences();
          }

          var point = points[currentPointIdx];
          if (point._map && point._map.hasLayer(point._popup)) {
            // popup is open, can't remove this point
          }
          else {
            var occurrence = occurrences.pop();
            if (occurrence!==undefined) {
              point.setLatLng([occurrence.latitude,occurrence.longitude]);
              point.unbindPopup(); // avoid memory leak
              point.bindPopup(
                "
Occurrence of " + occurrence.scientificName +"
" +
                  "Published by " + occurrence.publisher +"" +
                  "
Last indexed " + moment(occurrence.lastInterpreted).fromNow() +"
");
              point.addTo(map); // it should already be
            }
          }

          // move to next one
          currentPointIdx = currentPointIdx + 1;
          // reuse the points
          if (currentPointIdx >= points.length) {
            currentPointIdx = 0;
          }
          setTimeout(runMap, delayMsecs);
        }
        initData();
        runMap();
      }
    }

    function numberWithCommas(x) {
      return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    Drupal.behaviors.loadStats = {
      attach: function (context, settings) {
        $.getJSON(api_base_url + '/occurrence/count?callback=?', function (data)
          { $("#countOccurrences").html(numberWithCommas(data)); }
        );
        $.getJSON(api_base_url + '/dataset/7ddf754f-d193-4cc9-b351-99906754a03b/metrics', function (data)
          { $("#countSpecies").html(numberWithCommas(data.countByRank.SPECIES)); }
        );
        $.getJSON(api_base_url + '/dataset/search?limit=1&callback=?', function (data)
          { $("#countDatasets").html(numberWithCommas(data.count)); }
        );
        $.getJSON(api_base_url + '/organization/count?callback=?', function (data)
          { $("#countPublishers").html(numberWithCommas(data)); }
        );
      }
    }

}(jQuery));<|endoftext|>


<commit_before>function import_upload(e,r,t,o){var a=$(e.target),n=a.next(".feedback"),s=a.data("name"),l=$("#"+s);n.text("Loading... Large uploads can take some time to process"),$.post(t,{upload_id:r.upload_id,argument_name:s}).fail(function(e){n.addClass("error").html(e.responseJSON[s])}).success(function(e){n.removeClass("error").text(""),l.html(e),$("[name="+s+"]").val(r.upload_id),o&&o(n,l)})}!function(){IR.users||$(".btn-file").enable();var e=$("form.result");if(e.length){var r=$("#run-tool-options"),t=r.find(".btn-run"),o=$("div.result");e.submit(function(e){e.preventDefault()}),t.click(function(){var o=t.prop("disabled",!0),a=e.trigger("updated.cc"),n=o.text();o.text("Running..."),$(".control-label").removeClass("error").find(".feedback").remove();var s=get_form_dictionary(r);s.x=get_form_json(a),$.ajax({type:"post",url:CC.tool_json_url,data:s,error:function(e){var r=e.responseJSON;for(k in r){var t=$("[name="+k+"]");t.length&&t.parents(".form-group").find(".control-label").first().addClass("error").append('[ '+r[k].toUpperCase()+" ]")}a.trigger("failed.cc",e),o.prop("disabled",!1).text(n)},success:function(e){a.trigger("succeeded.cc",e),location.href=e.result_url}})}),o.length&&setTimeout(function(){var e=o.offset();scrollTo(e.left,e.top)},1)}$('[data-toggle="popover"]').popover({trigger:"click hover focus"})}();
<commit_msg>Save changes<commit_after>function import_upload(e,r,t,o){var a=$(e.target),n=a.next(".feedback"),s=a.data("name"),l=$("#"+s);n.text("Loading... Large uploads can take some time to process"),$.post(t,{upload_id:r.upload_id,argument_name:s}).fail(function(e){n.addClass("error").html(e.responseJSON[s])}).success(function(e){n.removeClass("error").text(""),l.html(e),$("[name="+s+"]").val(r.upload_id),o&&o(n,l)})}!function(){IR.users||$(".btn-file").enable();var r=$("form.result");if(r.length){var t=$("#run-tool-options"),s=t.find(".btn-run"),o=$("div.result");r.submit(function(e){e.preventDefault()}),s.click(function(){var o=s.prop("disabled",!0),a=r.trigger("updated.cc"),n=o.text();o.text("Running..."),$(".control-label").removeClass("error").find(".feedback").remove();var e=get_form_dictionary(t);e.x=get_form_json(a),$.ajax({type:"post",url:CC.tool_json_url,data:e,error:function(e){var r=e.responseJSON;for(k in r){var t=$("[name="+k+"]");t.length&&t.parents(".form-group").find(".control-label").first().addClass("error").append('[ '+r[k].toUpperCase()+" ]")}a.trigger("failed.cc",e),o.prop("disabled",!1).text(n)},success:function(e){a.trigger("succeeded.cc",e),location.href=e.result_url}})}),o.length&&setTimeout(function(){var e=o.offset();scrollTo(e.left,e.top)},1)}$('[data-toggle="popover"]').popover({trigger:"click hover focus"})}();
<|endoftext|>


<commit_before>var compact = require('lodash-node/modern/arrays/compact');
var utils = require('../utils');
var xhr = require('../xhr');
var settings = require('../settings');
var iScroll = require('iscroll');
var session = require('../session');
var i18n = require('../i18n');
var formWidgets = require('./_formWidgets');
var session = require('../session');
var moment = window.moment;

// iScroll instance
var scroller = null;

var gamesMenu = {};

var isOpen = false;
var newGameCardSwapped = false;

gamesMenu.open = function() {
  isOpen = true;
  if (utils.hasNetwork() && session.isConnected()) session.refresh();
};

gamesMenu.openNewGame = function() {
  gamesMenu.open();
  newGameCardSwapped = true;
};

gamesMenu.openCurrentGames = function() {
  gamesMenu.open();
  scroller.goToPage(1, 0);
};

gamesMenu.isOpen = function() {
  return isOpen;
};

gamesMenu.close = function() {
  isOpen = false;
};

gamesMenu.lastJoined = null;

gamesMenu.joinGame = function(g) {
  gamesMenu.lastJoined = g;
  gamesMenu.close();
  m.route('/play/' + g.fullId);
  m.redraw();
};

function iconFromVariant(variant, perf) {
  var lookup = variant === 'standard' ? perf : variant;
  return utils.variantIconsMap[lookup];
}

function startAIGame() {
  return xhr.newAiGame().then(function(data) {
    m.route('/play' + data.url.round);
  }, function(error) {
    utils.handleXhrError(error);
    throw error;
  });
}

function seekHumanGame() {
  m.route('/seek');
}

function swapCard() {
  newGameCardSwapped = !newGameCardSwapped;
}

function tupleOf(x) {
  return [x, x];
}

function renderForm(action, settingsObj, variants, timeModes) {
  var timeMode = settingsObj.timeMode();
  var hasClock = timeMode === '1';
  // var hasCorresp = timeMode === '2';
  var allowWhite = !settingsObj.mode ||
    settingsObj.mode() === '0' ||
    ['5', '6', '7'].indexOf(settingsObj.variant()) === -1 ||
    settings.game.selected() !== 'human';
  var colors = compact([
    ['randomColor', 'random'],
    allowWhite ? ['white', 'white'] : null,
    ['black', 'black']
  ]);
  var generalFieldset = [
    m('div.select_input', [
      formWidgets.renderSelect('color', 'color', colors, settingsObj.color),
    ]),
    m('div.select_input', [
      formWidgets.renderSelect('variant', 'variant', variants, settingsObj.variant),
    ])
  ];
  if (settingsObj.level) {
    generalFieldset.push(m('div.select_input', [
      formWidgets.renderSelect('level', 'ailevel', [
        '1', '2', '3', '4', '5', '6', '7', '8'
      ].map(tupleOf), settingsObj.level)
    ]));
  }
  if (settingsObj.mode) {
    generalFieldset.push(m('div.select_input', [
      formWidgets.renderSelect('mode', 'mode', [
        ['casual', '0'],
        ['rated', '1']
      ], settingsObj.mode)
    ]));
  }

  var timeFieldset = [
    m('div.select_input', [
      formWidgets.renderSelect('clock', 'timeMode', timeModes, settingsObj.timeMode)
    ])
  ];
  if (hasClock) {
    timeFieldset.push(
      m('div.select_input.inline', [
        formWidgets.renderSelect('time', 'time',
          settings.game.availableTimes.map(tupleOf), settingsObj.time, false)
      ]),
      m('div.select_input.inline', [
        formWidgets.renderSelect('increment', 'increment',
          settings.game.availableIncrements.map(tupleOf), settingsObj.increment, false)
      ])
    );
  }
  // if (hasCorresp) {
  //   timeFieldset.push(m('div.select_input', [
  //     formWidgets.renderSelect('Days per turn:', 'days', [
  //       '1', '2', '3', '5', '7', '10', '14'
  //       ].map(tupleOf), settingsObj.days, false)
  //   ]));
  // }

  return m('form#new_game_form.form', {
    onsubmit: function(e) {
      e.preventDefault();
      gamesMenu.close();
      swapCard();
      action();
    }
  }, [
    m('fieldset', [
      m('div.nice-radio', formWidgets.renderRadio('human', 'selected', 'human', settings.game.selected)),
      m('div.nice-radio', formWidgets.renderRadio('computer', 'selected', 'computer', settings.game.selected))
    ]),
    m('fieldset', generalFieldset),
    m('fieldset#clock', timeFieldset),
    m('button', i18n('createAGame'))
  ]);
}

function renderAllGames() {

  function cardDims() {
    var vp = utils.getViewportDims();
    var width = vp.vw * 85 / 100;
    var padding = vp.vw * 2.5 / 100;
    return {
      w: width + padding * 2,
      h: width + 144,
      innerW: width,
      padding: padding
    };
  }

  function renderViewOnlyBoard(fen, lastMove, color, variant) {
    return m('div', {
      style: {
        height: cDim.innerW + 'px'
      }
    }, [
      utils.viewOnlyBoard(fen, lastMove, color, variant)
    ]);
  }

  var nowPlaying = session.nowPlaying();
  var cDim = cardDims();
  var cardStyle = {
    width: cDim.w + 'px',
    height: cDim.h + 'px',
    paddingLeft: cDim.padding + 'px',
    paddingRight: cDim.padding + 'px'
  };
  var nbCards = nowPlaying.length + 1;
  // scroller wrapper width
  // calcul is:
  // ((cardWidth + visible part of adjacent card) * nb of cards) +
  //   wrapper's marginLeft
  var wrapperWidth = ((cDim.w + cDim.padding * 2) * nbCards) +
    (cDim.padding * 2);

  var timeLeft = function(g) {
    if (!g.isMyTurn) return i18n('waitingForOpponent');
    if (!g.secondsLeft) return i18n('yourTurn');
    var time = moment().add(g.secondsLeft, 'seconds');
    return m('time', {
      datetime: time.format()
    }, time.fromNow());
  };

  var allGames = nowPlaying.map(function(g) {
    var icon = iconFromVariant(g.variant.key, g.perf);
    return m('div.card.standard.' + g.color, {
      key: 'game.' + g.gameId,
      style: cardStyle,
      config: utils.ontouchendScroll(function() {
        gamesMenu.joinGame(g);
      })
    }, [
      renderViewOnlyBoard(g.fen, g.lastMove, g.color, g.variant),
      m('div.infos', [
        m('div.icon-game', {
          'data-icon': icon ? icon : ''
        }),
        m('div.description', [
          m('h2.title', utils.playerName(g.opponent, true)),
          m('p', [
            g.variant.name,
            m('span.time-indication', timeLeft(g))
          ])
        ])
      ])
    ]);
  });

  var game = m('div.card.new-game', {
    key: 'new-game',
    class: newGameCardSwapped ? 'back_visible' : '',
    style: cardStyle
  }, [
    m('div.container_flip', [
      m('div.front', {
        config: utils.ontouchendScroll(swapCard)
      }, [
        renderViewOnlyBoard(),
        m('div.infos', [
          m('div.description', [
            m('h2.title', i18n('createAGame')),
            m('p', i18n('newOpponent')),
          ])
        ])
      ]),
      m('div.back', [
        settings.game.selected() === 'human' ?
        renderForm(
          seekHumanGame,
          settings.game.human,
          settings.game.human.availableVariants,
          settings.game.human.availableTimeModes
        ) :
        renderForm(
          startAIGame,
          settings.game.ai,
          settings.game.ai.availableVariants,
          settings.game.ai.availableTimeModes
        )
      ])
    ])
  ]);

  allGames.unshift(game);

  return m('div#all_games', {
    style: {
      width: wrapperWidth + 'px',
      marginLeft: (cDim.padding * 2) + 'px'
    }
  }, allGames);
}

gamesMenu.view = function() {
  if (!isOpen) return;
  var children = [
    m('button.overlay_close.fa.fa-close', {
      config: utils.ontouchend(gamesMenu.close)
    }),
    m('div#wrapper_games', {
      config: function(el, isUpdate, context) {
        if (!isUpdate) {
          scroller = new iScroll(el, {
            scrollX: true,
            scrollY: false,
            momentum: false,
            snap: '.card',
            snapSpeed: 400,
            preventDefaultException: {
              tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT|LABEL)$/
            }
          });

          context.onunload = function() {
            if (scroller) {
              scroller.destroy();
              scroller = null;
            }
          };
        }
        // see https://github.com/cubiq/iscroll/issues/412
        scroller.options.snap = el.querySelectorAll('.card');
        scroller.refresh();
      }
    }, renderAllGames())
  ];

  return m('div#games_menu.overlay', children);
};

module.exports = gamesMenu;
<commit_msg>fix weird bug<commit_after>var compact = require('lodash-node/modern/arrays/compact');
var utils = require('../utils');
var xhr = require('../xhr');
var settings = require('../settings');
var iScroll = require('iscroll');
var session = require('../session');
var i18n = require('../i18n');
var formWidgets = require('./_formWidgets');
var session = require('../session');
var moment = window.moment;

// iScroll instance
var scroller = null;

var gamesMenu = {};

var isOpen = false;
var newGameCardSwapped = false;

gamesMenu.open = function() {
  isOpen = true;
  if (utils.hasNetwork() && session.isConnected()) session.refresh();
};

gamesMenu.openNewGame = function() {
  gamesMenu.open();
  newGameCardSwapped = true;
};

gamesMenu.openCurrentGames = function() {
  gamesMenu.open();
  if (scroller) scroller.goToPage(1, 0);
};

gamesMenu.isOpen = function() {
  return isOpen;
};

gamesMenu.close = function() {
  isOpen = false;
};

gamesMenu.lastJoined = null;

gamesMenu.joinGame = function(g) {
  gamesMenu.lastJoined = g;
  gamesMenu.close();
  m.route('/play/' + g.fullId);
  m.redraw();
};

function iconFromVariant(variant, perf) {
  var lookup = variant === 'standard' ? perf : variant;
  return utils.variantIconsMap[lookup];
}

function startAIGame() {
  return xhr.newAiGame().then(function(data) {
    m.route('/play' + data.url.round);
  }, function(error) {
    utils.handleXhrError(error);
    throw error;
  });
}

function seekHumanGame() {
  m.route('/seek');
}

function swapCard() {
  newGameCardSwapped = !newGameCardSwapped;
}

function tupleOf(x) {
  return [x, x];
}

function renderForm(action, settingsObj, variants, timeModes) {
  var timeMode = settingsObj.timeMode();
  var hasClock = timeMode === '1';
  // var hasCorresp = timeMode === '2';
  var allowWhite = !settingsObj.mode ||
    settingsObj.mode() === '0' ||
    ['5', '6', '7'].indexOf(settingsObj.variant()) === -1 ||
    settings.game.selected() !== 'human';
  var colors = compact([
    ['randomColor', 'random'],
    allowWhite ? ['white', 'white'] : null,
    ['black', 'black']
  ]);
  var generalFieldset = [
    m('div.select_input', [
      formWidgets.renderSelect('color', 'color', colors, settingsObj.color),
    ]),
    m('div.select_input', [
      formWidgets.renderSelect('variant', 'variant', variants, settingsObj.variant),
    ])
  ];
  if (settingsObj.level) {
    generalFieldset.push(m('div.select_input', [
      formWidgets.renderSelect('level', 'ailevel', [
        '1', '2', '3', '4', '5', '6', '7', '8'
      ].map(tupleOf), settingsObj.level)
    ]));
  }
  if (settingsObj.mode) {
    generalFieldset.push(m('div.select_input', [
      formWidgets.renderSelect('mode', 'mode', [
        ['casual', '0'],
        ['rated', '1']
      ], settingsObj.mode)
    ]));
  }

  var timeFieldset = [
    m('div.select_input', [
      formWidgets.renderSelect('clock', 'timeMode', timeModes, settingsObj.timeMode)
    ])
  ];
  if (hasClock) {
    timeFieldset.push(
      m('div.select_input.inline', [
        formWidgets.renderSelect('time', 'time',
          settings.game.availableTimes.map(tupleOf), settingsObj.time, false)
      ]),
      m('div.select_input.inline', [
        formWidgets.renderSelect('increment', 'increment',
          settings.game.availableIncrements.map(tupleOf), settingsObj.increment, false)
      ])
    );
  }
  // if (hasCorresp) {
  //   timeFieldset.push(m('div.select_input', [
  //     formWidgets.renderSelect('Days per turn:', 'days', [
  //       '1', '2', '3', '5', '7', '10', '14'
  //       ].map(tupleOf), settingsObj.days, false)
  //   ]));
  // }

  return m('form#new_game_form.form', {
    onsubmit: function(e) {
      e.preventDefault();
      gamesMenu.close();
      swapCard();
      action();
    }
  }, [
    m('fieldset', [
      m('div.nice-radio', formWidgets.renderRadio('human', 'selected', 'human', settings.game.selected)),
      m('div.nice-radio', formWidgets.renderRadio('computer', 'selected', 'computer', settings.game.selected))
    ]),
    m('fieldset', generalFieldset),
    m('fieldset#clock', timeFieldset),
    m('button', i18n('createAGame'))
  ]);
}

function renderAllGames() {

  function cardDims() {
    var vp = utils.getViewportDims();
    var width = vp.vw * 85 / 100;
    var padding = vp.vw * 2.5 / 100;
    return {
      w: width + padding * 2,
      h: width + 144,
      innerW: width,
      padding: padding
    };
  }

  function renderViewOnlyBoard(fen, lastMove, color, variant) {
    return m('div', {
      style: {
        height: cDim.innerW + 'px'
      }
    }, [
      utils.viewOnlyBoard(fen, lastMove, color, variant)
    ]);
  }

  var nowPlaying = session.nowPlaying();
  var cDim = cardDims();
  var cardStyle = {
    width: cDim.w + 'px',
    height: cDim.h + 'px',
    paddingLeft: cDim.padding + 'px',
    paddingRight: cDim.padding + 'px'
  };
  var nbCards = nowPlaying.length + 1;
  // scroller wrapper width
  // calcul is:
  // ((cardWidth + visible part of adjacent card) * nb of cards) +
  //   wrapper's marginLeft
  var wrapperWidth = ((cDim.w + cDim.padding * 2) * nbCards) +
    (cDim.padding * 2);

  var timeLeft = function(g) {
    if (!g.isMyTurn) return i18n('waitingForOpponent');
    if (!g.secondsLeft) return i18n('yourTurn');
    var time = moment().add(g.secondsLeft, 'seconds');
    return m('time', {
      datetime: time.format()
    }, time.fromNow());
  };

  var allGames = nowPlaying.map(function(g) {
    var icon = iconFromVariant(g.variant.key, g.perf);
    return m('div.card.standard.' + g.color, {
      key: 'game.' + g.gameId,
      style: cardStyle,
      config: utils.ontouchendScroll(function() {
        gamesMenu.joinGame(g);
      })
    }, [
      renderViewOnlyBoard(g.fen, g.lastMove, g.color, g.variant),
      m('div.infos', [
        m('div.icon-game', {
          'data-icon': icon ? icon : ''
        }),
        m('div.description', [
          m('h2.title', utils.playerName(g.opponent, true)),
          m('p', [
            g.variant.name,
            m('span.time-indication', timeLeft(g))
          ])
        ])
      ])
    ]);
  });

  var game = m('div.card.new-game', {
    key: 'new-game',
    class: newGameCardSwapped ? 'back_visible' : '',
    style: cardStyle
  }, [
    m('div.container_flip', [
      m('div.front', {
        config: utils.ontouchendScroll(swapCard)
      }, [
        renderViewOnlyBoard(),
        m('div.infos', [
          m('div.description', [
            m('h2.title', i18n('createAGame')),
            m('p', i18n('newOpponent')),
          ])
        ])
      ]),
      m('div.back', [
        settings.game.selected() === 'human' ?
        renderForm(
          seekHumanGame,
          settings.game.human,
          settings.game.human.availableVariants,
          settings.game.human.availableTimeModes
        ) :
        renderForm(
          startAIGame,
          settings.game.ai,
          settings.game.ai.availableVariants,
          settings.game.ai.availableTimeModes
        )
      ])
    ])
  ]);

  allGames.unshift(game);

  return m('div#all_games', {
    style: {
      width: wrapperWidth + 'px',
      marginLeft: (cDim.padding * 2) + 'px'
    }
  }, allGames);
}

gamesMenu.view = function() {
  if (!isOpen) return;
  var children = [
    m('button.overlay_close.fa.fa-close', {
      config: utils.ontouchend(gamesMenu.close)
    }),
    m('div#wrapper_games', {
      config: function(el, isUpdate, context) {
        if (!isUpdate) {
          scroller = new iScroll(el, {
            scrollX: true,
            scrollY: false,
            momentum: false,
            snap: '.card',
            snapSpeed: 400,
            preventDefaultException: {
              tagName: /^(INPUT|TEXTAREA|BUTTON|SELECT|LABEL)$/
            }
          });

          context.onunload = function() {
            if (scroller) {
              scroller.destroy();
              scroller = null;
            }
          };
        }
        // see https://github.com/cubiq/iscroll/issues/412
        scroller.options.snap = el.querySelectorAll('.card');
        scroller.refresh();
      }
    }, renderAllGames())
  ];

  return m('div#games_menu.overlay', children);
};

module.exports = gamesMenu;
<|endoftext|>


<commit_before>/// <reference path='../../dist/Excalibur.d.ts' />
var logger = ex.Logger.getInstance();
logger.defaultLevel = 0 /* Debug */;

// Create an the game container
var game = new ex.Engine(800, 600, 'game');
game.setAntialiasing(false);

var imageRun = new ex.Texture('../images/PlayerRun.png');
var imageJump = new ex.Texture('../images/PlayerJump.png');
var imageBlocks = new ex.Texture('../images/BlockA0.png');
var spriteFontImage = new ex.Texture('../images/SpriteFont.png');
var jump = new ex.Sound('../sounds/jump.wav', '../sounds/jump.mp3');
jump.setVolume(.3);

var loader = new ex.Loader();
loader.addResource(imageRun);
loader.addResource(imageJump);
loader.addResource(imageBlocks);
loader.addResource(spriteFontImage);
loader.addResource(jump);

// Set background color
game.backgroundColor = new ex.Color(114, 213, 224);

// Turn on debug diagnostics
game.isDebug = false;

// Create spritesheet
var spriteSheetRun = new ex.SpriteSheet(imageRun, 21, 1, 96, 96);
var spriteSheetJump = new ex.SpriteSheet(imageJump, 21, 1, 96, 96);
var tileBlockWidth = 64, tileBlockHeight = 48, spriteTiles = new ex.SpriteSheet(imageBlocks, 1, 1, tileBlockWidth, tileBlockHeight);

// Create spriteFont
var spriteFont = new ex.SpriteFont(spriteFontImage, '0123456789abcdefghijklmnopqrstuvwxyz,!\'&."?- ', true, 16, 3, 16, 16);
var label = new ex.Label('Hello World', 100, 100, null, spriteFont);
label.scaleTo(2, .5).scaleTo(1, .5).repeatForever();
game.addChild(label);

// Retrieve animations for blocks from sprite sheet
var blockAnimation = spriteTiles.getSprite(0);
blockAnimation.addEffect(new ex.Effects.Grayscale());

// Animation 'enum' to prevent 'stringly' typed misspelling errors
var Animations;
(function (Animations) {
    Animations[Animations["Block"] = 0] = "Block";
    Animations[Animations["Idle"] = 1] = "Idle";
    Animations[Animations["Left"] = 2] = "Left";
    Animations[Animations["Right"] = 3] = "Right";
    Animations[Animations["JumpRight"] = 4] = "JumpRight";
    Animations[Animations["JumpLeft"] = 5] = "JumpLeft";
})(Animations || (Animations = {}));

var currentX = 0;

for (var i = 0; i < 36; i++) {
    currentX = tileBlockWidth * i + 10;
    var color = new ex.Color(Math.random() * 255, Math.random() * 255, Math.random() * 255);
    var block = new ex.Actor(currentX, 350 + Math.random() * 100, tileBlockWidth, tileBlockHeight, color);

    block.addCollisionGroup('ground');
    block.addDrawing(0 /* Block */, blockAnimation);

    game.addChild(block);
}

var platform = new ex.Actor(400, 300, 200, 50, new ex.Color(0, 200, 0));
platform.moveTo(200, 300, 100).moveTo(600, 300, 100).moveTo(400, 300, 100).repeatForever();
game.addChild(platform);

var platform2 = new ex.Actor(800, 300, 200, 20, new ex.Color(0, 0, 140));
platform2.moveTo(2000, 300, 100).moveTo(2000, 100, 100).moveTo(800, 100, 100).moveTo(800, 300, 100).repeatForever();
game.addChild(platform2);

var platform3 = new ex.Actor(-200, 400, 200, 20, new ex.Color(50, 0, 100));
platform3.moveTo(-200, 800, 300).moveTo(-200, 400, 50).delay(3000).moveTo(-200, 300, 800).moveTo(-200, 400, 800).repeatForever();
game.addChild(platform3);

var platform4 = new ex.Actor(200, 200, 100, 50, ex.Color.Azure);
platform4.moveBy(75, 300, .20);
game.addChild(platform4);

// Test follow api
var follower = new ex.Actor(50, 100, 20, 20, ex.Color.Black);
follower.preventCollisions = true;
game.addChild(follower);

// Create the player
var player = new ex.Actor(100, 100, 32, 96);
follower.meet(player, 60);

// follow player
player.scale = 1;
player.rotation = 0;
player.fixed = false;

// Health bar example
player.addChild(new ex.Actor(-48, -20, 140, 5, new ex.Color(0, 255, 0)));

// Add Title above player
var playerLabel = new ex.Label('My Player', -48, -39, null, spriteFont);

player.addChild(playerLabel);

// Retrieve animations for player from sprite sheet
var left = spriteSheetRun.getAnimationBetween(game, 1, 11, 50);
var right = spriteSheetRun.getAnimationBetween(game, 1, 11, 50);
right.flipHorizontal = true;
var idle = spriteSheetRun.getAnimationByIndices(game, [0], 200);
var jumpLeft = spriteSheetJump.getAnimationBetween(game, 0, 11, 100);
var jumpRight = spriteSheetJump.getAnimationBetween(game, 11, 22, 100);
left.loop = true;
right.loop = true;
idle.loop = true;

jumpRight.freezeFrame = 0;
jumpLeft.freezeFrame = 11;

// Add animations to player
player.addDrawing(2 /* Left */, left);
player.addDrawing(3 /* Right */, right);
player.addDrawing(1 /* Idle */, idle);
player.addDrawing(4 /* JumpRight */, jumpRight);
player.addDrawing(5 /* JumpLeft */, jumpLeft);

// Set default animation
player.setDrawing(1 /* Idle */);
player.setCenterDrawing(true);

var jumpSound = jump.sound;

var inAir = true;
var groundSpeed = 150;
var airSpeed = 130;
var jumpSpeed = 500;
var direction = 1;
player.addEventListener('left', function () {
    direction = -1;
    if (!inAir) {
        player.setDrawing(2 /* Left */);
    }
    if (inAir) {
        player.dx = -airSpeed;
        return;
    }
    player.dx = -groundSpeed;
    // TODO: When platform is moving in same direction, add its dx
});

player.addEventListener('right', function () {
    direction = 1;
    if (!inAir) {
        player.setDrawing(3 /* Right */);
    }
    if (inAir) {
        player.dx = airSpeed;
        return;
    }
    player.dx = groundSpeed;
    // TODO: When platform is moving in same direction, add its dx
});

player.addEventListener('up', function () {
    if (!inAir) {
        player.dy -= jumpSpeed;
        inAir = true;
        if (direction === 1) {
            player.setDrawing(4 /* JumpRight */);
        } else {
            player.setDrawing(5 /* JumpLeft */);
        }
        jumpSound.play();
    }
});

player.addEventListener('mousedown', function (e) {
    var button = "";
    if (e.mouseEvent.button == 0 /* Left */) {
        button = "Left";
    } else if (e.mouseEvent.button == 1 /* Middle */) {
        button = "Middle";
    } else if (e.mouseEvent.button == 2 /* Right */) {
        button = "Right";
    }
    alert("Player clicked with " + button + " button!");
});

player.addEventListener('keyup', function (e) {
    if (inAir)
        return;

    if (e.key === 37 /* Left */ || e.key === 39 /* Right */) {
        player.setDrawing(1 /* Idle */);
    }
});

player.addEventListener('touchstart', function () {
    alert("player touched!");
});

var newScene = new ex.Scene();
newScene.addChild(new ex.Label("MAH LABEL!", 200, 100));

//newScene.onActivate = function(){
//   console.log('activated newScene');
//};
//newScene.onDeactivate = function(){
//   console.log('deactivated newScene');
//};
newScene.addEventListener('activate', function (evt) {
    console.log('activate newScene');
});

newScene.addEventListener('deactivate', function (evt) {
    console.log('deactivate newScene');
});

game.addScene('label', newScene);

game.addEventListener('keydown', function (keyDown) {
    if (keyDown.key === 70 /* F */) {
        var a = new ex.Actor(player.x + 10, player.y - 50, 10, 10, new ex.Color(222, 222, 222));
        a.dx = 200 * direction;
        a.dy = 0;
        a.preventCollisions = true;
        a.fixed = false;
        var inAir = true;
        a.addEventListener('collision', function (data) {
            inAir = false;
            a.dx = data.other.dx;
            a.dy = data.other.dy;
            a.kill();
        });
        a.addEventListener('update', function (data) {
            if (inAir) {
                a.dy += 400 * data.delta / 1000;
            }
            inAir = true;
        });
        game.addChild(a);
    } else if (keyDown.key === 85 /* U */) {
        game.goToScene('label');
    } else if (keyDown.key === 73 /* I */) {
        game.goToScene('root');
    }
});

var isColliding = false;
player.addEventListener('collision', function (data) {
    if (data.side === 2 /* BOTTOM */) {
        isColliding = true;

        if (inAir) {
            //console.log("Collided on bottom with inAir", inAir);
            player.setDrawing(1 /* Idle */);
        }
        inAir = false;
        player.dx = data.other.dx;
        player.dy = data.other.dy;
    }

    if (data.side === 1 /* TOP */) {
        player.dy = data.other.dy - player.dy;
    }
});

player.addEventListener('update', function (data) {
    // apply gravity if player is in the air
    // only apply gravity when not colliding
    if (!isColliding) {
        data.target.dy += 800 * data.delta / 1000;
    }

    // Reset values because we don't know until we check the next update
    // inAir = true;
    isColliding = false;
    //console.log("Player Pos", player.x, player.y, player.getWidth(), player.getHeight());
});

player.addEventListener('initialize', function (evt) {
    console.log("Player initialized", evt.engine);
});

game.addEventListener('keydown', function (keyDown) {
    if (keyDown.key === 66 /* B */) {
        var block = new ex.Actor(currentX, 350, 44, 50, color);
        currentX += 46;
        block.addDrawing(0 /* Block */, blockAnimation);
        game.addChild(block);
    }
});

var paused = false;
game.addEventListener('p', function () {
    if (!paused) {
        game.stop();
    } else {
        game.start();
    }
    paused != paused;
});

game.addEventListener('keydown', function (keyDown) {
    if (keyDown.key === 68 /* D */) {
        game.isDebug = !game.isDebug;
    }
});

// Create a camera to track the player
var camera = new ex.SideCamera(game);
camera.setActorToFollow(player);

// camera.shake(5, 5, 1000);
// camera.zoom(0.5);
// camera.zoom(1.5, 10000);
// Add player to game is synonymous with adding a player to the current scene
game.addChild(player);

// Add particle emitter
var emitter = new ex.ParticleEmitter(100, 300, 2, 2);
emitter.minVel = 417;
emitter.maxVel = 589;
emitter.minAngle = Math.PI;
emitter.maxAngle = Math.PI * 2;
emitter.isEmitting = false;
emitter.emitRate = 494;
emitter.opacity = 0.84;
emitter.fadeFlag = true;
emitter.particleLife = 2465;
emitter.maxSize = 10;
emitter.minSize = 1;
emitter.acceleration = new ex.Vector(0, 460);
emitter.beginColor = ex.Color.Red;
emitter.endColor = ex.Color.Yellow;

//emitter.acceleration = new ex.Vector(0, -400);
//emitter.particleSprite = spriteTiles.getSprite(0);
//emitter.focus = new ex.Vector(0, -100);
//emitter.focusAccel = 800;
game.addChild(emitter);

//emitter.follow(player, 20);
var exploding = false;
var trigger = new ex.Trigger(400, 200, 100, 100, function () {
    if (!exploding) {
        exploding = true;
        emitter.isEmitting = true;
        camera.shake(10, 10, 2000);
        game.addTimer(new ex.Timer(function () {
            emitter.isEmitting = false;
            exploding = false;
        }, 2000));
    }
});

trigger.repeats = -1;
trigger.target = player;

game.addChild(trigger);

game.addEventListener('mousedown', function (evt) {
    logger.info(evt.x + ", " + evt.y);
    emitter.focus = new ex.Vector(evt.x - emitter.x, evt.y - emitter.y);
});

game.addEventListener('keyup', function (evt) {
    if (evt.key == 70 /* F */) {
        jump.play();
    }
});

game.addEventListener('keyup', function (evt) {
    if (evt.key == 83 /* S */) {
        jump.stop();
    }
});

// Add camera to game
game.camera = camera;

// Run the mainloop
game.start(loader).then(function () {
    logger.info("All Resources have finished loading");
});
//# sourceMappingURL=game.js.map
<commit_msg>Remove game.js<commit_after><|endoftext|>


<commit_before>export default class Chart {
	constructor() {
		this.offsetLeft = 50;
		this.offsetTop = 50;

		this.width = 500;
		this.height = 400;

		this.xAxis = [];
		this.yAxis = [];

		this.xAxisPath = "";
		this.yAxisPath = "";

		this.stepLength = 1;

		this.scaleType = Chart.ScaleTypes.Linear;
	}

	set data(arr) {
		this.series = arr;

		this.render();
	}

	linearScale() {
		let max = Math.max.apply(null, this.series[0].data);
		let min = Math.min.apply(null, this.series[0].data);

		let step = Math.pow(10, Math.floor(Math.log(max - min) / Math.LN10));

		this.yAxis = Array.from(Array(max - min), (v, k) => {
			return {number: step * k};
		});

		this.stepLength = this.height / this.yAxis[this.yAxis.length - 1].number;
	}

	logarithmicScale() {
		let max = Math.max.apply(null, this.series[0].data);
		let min = Math.min.apply(null, this.series[0].data);

		if (max === min) {
			if (min === 0) {
				max = 1;
			} else if (min < 0) {
				max = 0;
			} else {
				min = 0;
			}
		}

		// 不管哪种坐标轴，都需要在最大最小值的基础上找等分点
		let range = max - min;
		this.oom = Math.floor(Math.log(range) / Math.LN10);
		let step = Math.pow(10, this.oom);

		min = Math.pow(10, Math.floor(Math.log(min) / Math.LN10));
		max = Math.pow(10, Math.ceil(Math.log(max) / Math.LN10));

		for (let i = min; i <= max; i *= 10) {
			this.yAxis.push({
				number: i
			});
		}

		this.stepLength = this.height / (Math.log(this.yAxis[this.yAxis.length - 1].number) * Math.LOG10E);
	}

	/**
	 * 坐标轴缩放
	 */
	scale() {
		this.linearScale();

		// 横向的刻度线
		for (let i = 0; i < this.yAxis.length; i++) {
			let y = this.yAxis[i].number * this.stepLength;

			this.yAxis[i].y = y;
			this.yAxis[i].path = "M0," + y + " L500," + y;
		}
	}

	render() {
		this.scale();

		var that = this;

		this.series[0].data.forEach((it, i) => {
			let height = it * this.stepLength;

			that.xAxis.push({
				number: it,
				x: i * 50,
				height: it * this.stepLength
			});
			this.xAxis[i].path = "M" + x + ",0 L" + x + ", 0";
		});

		this.xAxisPath = "M" + this.offsetLeft + ",0 L" + (this.offsetLeft + this.width) + ",0";
	}
}

Chart.ScaleTypes = Object.freeze({
	Linear: 0,
	Logarithmic: 1
});
<commit_msg>丢了一个变量<commit_after>export default class Chart {
	constructor() {
		this.offsetLeft = 50;
		this.offsetTop = 50;

		this.width = 500;
		this.height = 400;

		this.xAxis = [];
		this.yAxis = [];

		this.xAxisPath = "";
		this.yAxisPath = "";

		this.stepLength = 1;

		this.scaleType = Chart.ScaleTypes.Linear;
	}

	set data(arr) {
		this.series = arr;

		this.render();
	}

	linearScale() {
		let max = Math.max.apply(null, this.series[0].data);
		let min = Math.min.apply(null, this.series[0].data);

		let step = Math.pow(10, Math.floor(Math.log(max - min) / Math.LN10));

		this.yAxis = Array.from(Array(max - min), (v, k) => {
			return {number: step * k};
		});

		this.stepLength = this.height / this.yAxis[this.yAxis.length - 1].number;
	}

	logarithmicScale() {
		let max = Math.max.apply(null, this.series[0].data);
		let min = Math.min.apply(null, this.series[0].data);

		if (max === min) {
			if (min === 0) {
				max = 1;
			} else if (min < 0) {
				max = 0;
			} else {
				min = 0;
			}
		}

		// 不管哪种坐标轴，都需要在最大最小值的基础上找等分点
		let range = max - min;
		this.oom = Math.floor(Math.log(range) / Math.LN10);
		let step = Math.pow(10, this.oom);

		min = Math.pow(10, Math.floor(Math.log(min) / Math.LN10));
		max = Math.pow(10, Math.ceil(Math.log(max) / Math.LN10));

		for (let i = min; i <= max; i *= 10) {
			this.yAxis.push({
				number: i
			});
		}

		this.stepLength = this.height / (Math.log(this.yAxis[this.yAxis.length - 1].number) * Math.LOG10E);
	}

	/**
	 * 坐标轴缩放
	 */
	scale() {
		this.linearScale();

		// 横向的刻度线
		for (let i = 0; i < this.yAxis.length; i++) {
			let y = this.yAxis[i].number * this.stepLength;

			this.yAxis[i].y = y;
			this.yAxis[i].path = "M0," + y + " L500," + y;
		}
	}

	render() {
		this.scale();

		var that = this;

		this.series[0].data.forEach((it, i) => {
			let height = it * this.stepLength;
			let x = i * 50;

			that.xAxis.push({
				number: it,
				x: x,
				height: it * this.stepLength
			});
			this.xAxis[i].path = "M" + x + ",0 L" + x + ", 0";
		});

		this.xAxisPath = "M" + this.offsetLeft + ",0 L" + (this.offsetLeft + this.width) + ",0";
	}
}

Chart.ScaleTypes = Object.freeze({
	Linear: 0,
	Logarithmic: 1
});
<|endoftext|>


<commit_before>module.exports = function() {

   // module container
   var snp = {};

   snp.analyses = [];

   snp.analyzeMatches = analyzeMatches;
   function analyzeMatches(matches) {
      var bins = { '6-0': [], '6-1': [], '6-2': [], '6-3': [], '6-4': [], '7-5': [], '7-6': [] };
      matches.forEach((m) => {
         var match = m.match;
         var tournament = m.tournament.name;
         var year = m.tournament.date.getFullYear();
         var sets = match.sets();
         var players = match.players();
         sets.forEach((s) => {
            var score = s.score() ? s.score().game_score.split('(')[0].split('-').sort().reverse().join('-') : '';
            if (score && ['6-0', '6-1', '6-2', '6-3', '6-4', '7-5', '7-6'].indexOf(score) >= 0) {
               var games = s.games().length;
               var points = s.points().length;
               var shots = s.points().map(p => p.rally.length + 1).reduce((a, b) => (a+b));
               var ppg = (points / games).toFixed(2);
               var spg = (shots / games).toFixed(2);
               var h2h = players[0] + ' v. ' + players[1];
               bins[score].push({
                     "Set Score"    :  score,
                     "Total Points" :  points,
                     "Total Shots"  :  shots,
                     "PPG"          :  ppg,
                     "SPG"          :  spg,
                     "Tournament"   :  tournament,
                     "h2h"            :  h2h
               });
            }
         });
      })
      var distribution = [];
      var scores = Object.keys(bins);
      scores.forEach(function(s) { distribution = distribution.concat(bins[s]); });

      return { bins: bins, distribution: distribution };
   }

   snp.whenComplete = whenComplete;
   function whenComplete(result) {

      if (result.matches) {
         analysis = analyzeMatches(result.matches);
         snp.analyses.push(analysis);
         console.log('Analysis Complete');
      }

   }

   snp.minMax = minMax;
   function minMax(bin) {
      var max = {};
      max.ppg = { "PPG": 0 }; // maximum points per game
      max.spg = { "SPG": 0 }; // maximum shots per game
      max.pps = { "PPS": 0 }; // maximum points per set
      max.sps = { "SPS": 0 }; // maximum points per game

      var min = {};
      min.ppg = { "PPG": undefined }; // min points per game
      min.spg = { "SPG": undefined }; // min shots per game
      min.pps = { "PPS": undefined }; // min points per set
      min.sps = { "SPS": undefined }; // min points per game

      bin.forEach((b) => {
         if (b.PPG > max.ppg.PPG) max.ppg = {
            "h2h": b.h2h, "tournament": b.Tournament, "score": b['Set Score'], "PPG": b.PPG
         };
         if (b.SPG > max.spg.SPG) max.spg = {
            "h2h": b.h2h, "tournament": b.Tournament, "score": b['Set Score'], "SPG": b.SPG
         };
         if (b['Total Points'] > max.pps.PPS) max.pps = {
            "h2h": b.h2h, "tournament": b.Tournament, "score": b['Set Score'], "PPS": b['Total Points']
         };
         if (b['Total Shots']  > max.sps.SPS) max.sps = {
            "h2h": b.h2h, "tournament": b.Tournament, "score": b['Set Score'], "SPS": b['Total Shots']
         };

         if (b.PPG < min.ppg.PPG || !min.ppg.PPG) min.ppg = {
            "h2h": b.h2h, "tournament": b.Tournament, "score": b['Set Score'], "PPG": b.PPG
         };
         if (b.SPG < min.spg.SPG || !min.spg.SPG) min.spg = {
            "h2h": b.h2h, "tournament": b.Tournament, "score": b['Set Score'], "SPG": b.SPG
         };
         if (b['Total Points'] < min.pps.PPS || !min.pps.PPS) min.pps = {
            "h2h": b.h2h, "tournament": b.Tournament, "score": b['Set Score'], "PPS": b['Total Points']
         };
         if (b['Total Shots']  < min.sps.SPS || !min.sps.SPS) min.sps = {
            "h2h": b.h2h, "tournament": b.Tournament, "score": b['Set Score'], "SPS": b['Total Shots']
         };
      });
      return { min: min, max: max };
   }

   return snp;
}
<commit_msg>add 'gid' group id to support highlighting matches in scatterplot<commit_after>module.exports = function() {

   // module container
   var snp = {};

   snp.analyses = [];
   snp.total_shots = 0;

   snp.analyzeMatches = analyzeMatches;
   function analyzeMatches(matches) {
      var bins = { '6-0': [], '6-1': [], '6-2': [], '6-3': [], '6-4': [], '7-5': [], '7-6': [] };
      matches.forEach((m) => {
         var match = m.match;
         var tournament = m.tournament.name;
         var year = m.tournament.date.getFullYear();
         var sets = match.sets();
         var players = match.players();
         var gid = (players.join('') + tournament + year).replace(/ /g,'');
         sets.forEach((s) => {
            var score = s.score() ? s.score().game_score.split('(')[0].split('-').sort().reverse().join('-') : '';
            if (score && ['6-0', '6-1', '6-2', '6-3', '6-4', '7-5', '7-6'].indexOf(score) >= 0) {
               var games = s.games().length;
               var points = s.points().length;
               var shots = s.points().map(p => p.rally.length + 1).reduce((a, b) => (a+b));
               snp.total_shots += shots;
               var ppg = (points / games).toFixed(2);
               var spg = (shots / games).toFixed(2);
               var h2h = players[0] + ' v. ' + players[1];
               bins[score].push({
                     "Set Score"    :  score,
                     "Total Points" :  points,
                     "Total Shots"  :  shots,
                     "PPG"          :  ppg,
                     "SPG"          :  spg,
                     "Tournament"   :  tournament,
                     "h2h"          :  h2h,
                     "gid"          :  gid
               });
            }
         });
      })
      var distribution = [];
      var scores = Object.keys(bins);
      scores.forEach(function(s) { distribution = distribution.concat(bins[s]); });

      return { bins: bins, distribution: distribution };
   }

   snp.whenComplete = whenComplete;
   function whenComplete(result) {

      if (result.matches) {
         analysis = analyzeMatches(result.matches);
         snp.analyses.push(analysis);
         console.log('Analysis Complete');
      }

   }

   snp.minMax = minMax;
   function minMax(bin) {
      var max = {};
      max.ppg = { "PPG": 0 }; // maximum points per game
      max.spg = { "SPG": 0 }; // maximum shots per game
      max.pps = { "PPS": 0 }; // maximum points per set
      max.sps = { "SPS": 0 }; // maximum points per game

      var min = {};
      min.ppg = { "PPG": undefined }; // min points per game
      min.spg = { "SPG": undefined }; // min shots per game
      min.pps = { "PPS": undefined }; // min points per set
      min.sps = { "SPS": undefined }; // min points per game

      bin.forEach((b) => {
         if (b.PPG > max.ppg.PPG) max.ppg = {
            "h2h": b.h2h, "tournament": b.Tournament, "score": b['Set Score'], "PPG": b.PPG
         };
         if (b.SPG > max.spg.SPG) max.spg = {
            "h2h": b.h2h, "tournament": b.Tournament, "score": b['Set Score'], "SPG": b.SPG
         };
         if (b['Total Points'] > max.pps.PPS) max.pps = {
            "h2h": b.h2h, "tournament": b.Tournament, "score": b['Set Score'], "PPS": b['Total Points']
         };
         if (b['Total Shots']  > max.sps.SPS) max.sps = {
            "h2h": b.h2h, "tournament": b.Tournament, "score": b['Set Score'], "SPS": b['Total Shots']
         };

         if (b.PPG < min.ppg.PPG || !min.ppg.PPG) min.ppg = {
            "h2h": b.h2h, "tournament": b.Tournament, "score": b['Set Score'], "PPG": b.PPG
         };
         if (b.SPG < min.spg.SPG || !min.spg.SPG) min.spg = {
            "h2h": b.h2h, "tournament": b.Tournament, "score": b['Set Score'], "SPG": b.SPG
         };
         if (b['Total Points'] < min.pps.PPS || !min.pps.PPS) min.pps = {
            "h2h": b.h2h, "tournament": b.Tournament, "score": b['Set Score'], "PPS": b['Total Points']
         };
         if (b['Total Shots']  < min.sps.SPS || !min.sps.SPS) min.sps = {
            "h2h": b.h2h, "tournament": b.Tournament, "score": b['Set Score'], "SPS": b['Total Shots']
         };
      });
      return { min: min, max: max };
   }

   return snp;
}
<|endoftext|>


<commit_before>function createWorkspace(path, collectionName, menu) {

  var currentPath = '';
  if (path) {
    currentPath = path;
  }

  localStorage.removeItem("pageurl");
  localStorage.setItem("pageurl", currentPath);

  // tentative reload of nav bar with collection name
  var mainNavHtml = templates.mainNav(Florence);
  $('.admin-nav').replaceWith(mainNavHtml);

  var workSpace = templates.workSpace(path);
  $('.section').replaceWith(workSpace);

  setupIframeHandler();
  viewWorkspace(path, collectionName, menu);
}

<commit_msg>Preventing creation of workspace replacing the container class.<commit_after>function createWorkspace(path, collectionName, menu) {

  var currentPath = '';
  if (path) {
    currentPath = path;
  }

  localStorage.removeItem("pageurl");
  localStorage.setItem("pageurl", currentPath);

  Florence.refreshAdminMenu();

  var workSpace = templates.workSpace(path);
  $('.section').html(workSpace);

  setupIframeHandler();
  viewWorkspace(path, collectionName, menu);
}

<|endoftext|>