<commit_before>// ## Globals
var argv         = require('minimist')(process.argv.slice(2));
var autoprefixer = require('gulp-autoprefixer');
var browserSync  = require('browser-sync').create();
var changed      = require('gulp-changed');
var concat       = require('gulp-concat');
var flatten      = require('gulp-flatten');
var gulp         = require('gulp');
var bless        = require('gulp-bless');
var gulpif       = require('gulp-if');
var imagemin     = require('gulp-imagemin');
var jshint       = require('gulp-jshint');
var lazypipe     = require('lazypipe');
var less         = require('gulp-less');
var merge        = require('merge-stream');
var minifyCss    = require('gulp-minify-css');
var plumber      = require('gulp-plumber');
var rev          = require('gulp-rev');
var runSequence  = require('run-sequence');
var sass         = require('gulp-sass');
var sourcemaps   = require('gulp-sourcemaps');
var uglify       = require('gulp-uglify');

// See https://github.com/austinpray/asset-builder
var manifest = require('asset-builder')('./assets/manifest.json');

// `path` - Paths to base asset directories. With trailing slashes.
// - `path.source` - Path to the source files. Default: `assets/`
// - `path.dist` - Path to the build directory. Default: `dist/`
var path = manifest.paths;

// `config` - Store arbitrary configuration values here.
var config = manifest.config || {};

// `globs` - These ultimately end up in their respective `gulp.src`.
// - `globs.js` - Array of asset-builder JS dependency objects. Example:
//   ```
//   {type: 'js', name: 'main.js', globs: []}
//   ```
// - `globs.css` - Array of asset-builder CSS dependency objects. Example:
//   ```
//   {type: 'css', name: 'main.css', globs: []}
//   ```
// - `globs.fonts` - Array of font path globs.
// - `globs.images` - Array of image path globs.
// - `globs.bower` - Array of all the main Bower files.
var globs = manifest.globs;

// `project` - paths to first-party assets.
// - `project.js` - Array of first-party JS assets.
// - `project.css` - Array of first-party CSS assets.
var project = manifest.getProjectGlobs();

// CLI options
var enabled = {
  // Enable static asset revisioning when `--production`
  rev: argv.production,
  // Disable source maps when `--production`
  maps: !argv.production,
  // Fail styles task on error when `--production`
  failStyleTask: argv.production,
  // Fail due to JSHint warnings only when `--production`
  failJSHint: argv.production,
  // Strip debug statments from javascript when `--production`
  stripJSDebug: argv.production,
  // Minify CSS, JS, and Images
  minify: !argv.fast,
  // Split minified css when '--production'
  split: argv.production
};

// Path to the compiled assets manifest in the dist directory
var revManifest = path.dist + 'assets.json';

// ## Reusable Pipelines
// See https://github.com/OverZealous/lazypipe

// ### CSS processing pipeline
// Example
// ```
// gulp.src(cssFiles)
//   .pipe(cssTasks('main.css')
//   .pipe(gulp.dest(path.dist + 'styles'))
// ```
var cssTasks = function(filename) {
  return lazypipe()
    .pipe(function() {
      return gulpif(!enabled.failStyleTask, plumber());
    })
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.init());
    })
    .pipe(function() {
      return gulpif('*.less', less());
    })
    .pipe(function() {
      return gulpif('*.scss', sass({
        outputStyle: 'nested', // libsass doesn't support expanded yet
        precision: 10,
        includePaths: ['.'],
        errLogToConsole: !enabled.failStyleTask
      }));
    })
    .pipe(concat, filename)
    .pipe(autoprefixer, {
      browsers: [
        'last 2 versions',
        'ie 8',
        'ie 9',
        'android 2.3',
        'android 4',
        'opera 12'
      ]
    })
    .pipe(function() {
      return gulpif(enabled.minify, minifyCss({
        advanced: false,
        rebase: false
      }));
    })
    .pipe(function() {
      return gulpif(enabled.rev, rev());
    })
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.write('.', {
        sourceRoot: 'assets/styles/'
      }));
    })();
};

// ### Bless
gulp.task('bless', function() {
  if(enabled.split) {
    return gulp.src(path.dist + 'styles/*.css')
    .pipe(bless())
     .pipe(gulp.dest(path.dist + 'styles'));
  }
});

// ### JS processing pipeline
// Example
// ```
// gulp.src(jsFiles)
//   .pipe(jsTasks('main.js')
//   .pipe(gulp.dest(path.dist + 'scripts'))
// ```
var jsTasks = function(filename) {
  return lazypipe()
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.init());
    })
    .pipe(concat, filename)
    .pipe(function() {
      return gulpif(enabled.minify, uglify({
        compress: {
          'drop_debugger': enabled.stripJSDebug
        }
      }));
    })
    .pipe(function() {
      return gulpif(enabled.rev, rev());
    })
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.write('.', {
        sourceRoot: 'assets/scripts/'
      }));
    })();
};

// ### Write to rev manifest
// If there are any revved files then write them to the rev manifest.
// See https://github.com/sindresorhus/gulp-rev
var writeToManifest = function(directory) {
  return lazypipe()
    .pipe(gulp.dest, path.dist + directory)
    .pipe(browserSync.stream, {match: '**/*.{js,css}'})
    .pipe(rev.manifest, revManifest, {
      base: path.dist,
      merge: true
    })
    .pipe(gulp.dest, path.dist)();
};

// ## Gulp tasks
// Run `gulp -T` for a task summary

// ### Styles
// `gulp styles` - Compiles, combines, and optimizes Bower CSS and project CSS.
// By default this task will only log a warning if a precompiler error is
// raised. If the `--production` flag is set: this task will fail outright.
gulp.task('styles', ['wiredep'], function() {
  var merged = merge();
  manifest.forEachDependency('css', function(dep) {
    var cssTasksInstance = cssTasks(dep.name);
    if (!enabled.failStyleTask) {
      cssTasksInstance.on('error', function(err) {
        console.error(err.message);
        this.emit('end');
      });
    }
    merged.add(gulp.src(dep.globs, {base: 'styles'})
      .pipe(cssTasksInstance));
  });
  return merged
    .pipe(writeToManifest('styles'));
});

// ### Scripts
// `gulp scripts` - Runs JSHint then compiles, combines, and optimizes Bower JS
// and project JS.
gulp.task('scripts', ['jshint'], function() {
  var merged = merge();
  manifest.forEachDependency('js', function(dep) {
    merged.add(
      gulp.src(dep.globs, {base: 'scripts'})
        .pipe(jsTasks(dep.name))
    );
  });
  return merged
    .pipe(writeToManifest('scripts'));
});

// ### Fonts
// `gulp fonts` - Grabs all the fonts and outputs them in a flattened directory
// structure. See: https://github.com/armed/gulp-flatten
gulp.task('fonts', function() {
  return gulp.src(globs.fonts)
    .pipe(flatten())
    .pipe(gulp.dest(path.dist + 'fonts'))
    .pipe(browserSync.stream());
});

// ### Images
// `gulp images` - Run lossless compression on all the images.
gulp.task('images', function() {
  return gulp.src(globs.images)
    .pipe(gulpif(enabled.minify, imagemin({
      progressive: true,
      interlaced: true,
      svgoPlugins: [{removeUnknownsAndDefaults: false}, {cleanupIDs: false}]
    })))
    .pipe(gulp.dest(path.dist + 'images'))
    .pipe(browserSync.stream());
});

// ### JSHint
// `gulp jshint` - Lints configuration JSON and project JS.
gulp.task('jshint', function() {
  return gulp.src([
    'bower.json', 'gulpfile.js'
  ].concat(project.js))
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'))
    .pipe(gulpif(enabled.failJSHint, jshint.reporter('fail')));
});

// ### Clean
// `gulp clean` - Deletes the build folder entirely.
gulp.task('clean', require('del').bind(null, [path.dist]));

// ### Watch
// `gulp watch` - Use BrowserSync to proxy your dev server and synchronize code
// changes across devices. Specify the hostname of your dev server at
// `manifest.config.devUrl`. When a modification is made to an asset, run the
// build step for that asset and inject the changes into the page.
// See: http://www.browsersync.io
gulp.task('watch', function() {
	var url = process.cwd();
	url = url.split('/');
	var finalurl = "http://" + url[4] + "." + url[2] + ".56.cubelab.ch";
	browserSync.init({
		files: ['{lib,templates}/**/*.php', '*.php'],
		proxy: finalurl, snippetOptions: {
			whitelist: ['/wp-admin/admin-ajax.php'],
			blacklist: ['/wp-admin/**']
		}
	});
	gulp.watch([path.source + 'styles/**/*'], ['styles']);
	gulp.watch([path.source + 'scripts/**/*'], ['jshint', 'scripts']);
	gulp.watch([path.source + 'fonts/**/*'], ['fonts']);
	gulp.watch([path.source + 'images/**/*'], ['images']);
	gulp.watch(['bower.json', 'assets/manifest.json'], ['build']);
});

// ### Build
// `gulp build` - Run all the build tasks but don't clean up beforehand.
// Generally you should be running `gulp` instead of `gulp build`.
gulp.task('build', function(callback) {
  runSequence('styles',
  			  'bless',
              'scripts',
              ['fonts', 'images'],
              callback);
});

// ### Wiredep
// `gulp wiredep` - Automatically inject Less and Sass Bower dependencies. See
// https://github.com/taptapship/wiredep
gulp.task('wiredep', function() {
  var wiredep = require('wiredep').stream;
  return gulp.src(project.css)
    .pipe(wiredep())
    .pipe(changed(path.source + 'styles', {
      hasChanged: changed.compareSha1Digest
    }))
    .pipe(gulp.dest(path.source + 'styles'));
});

// ### Gulp
// `gulp` - Run a complete build. To compile for production run `gulp --production`.
gulp.task('default', ['clean'], function() {
  gulp.start('build');
});<commit_msg>added crossorigin for fixing ajax with gulp watch<commit_after>// ## Globals
var argv         = require('minimist')(process.argv.slice(2));
var autoprefixer = require('gulp-autoprefixer');
var browserSync  = require('browser-sync').create();
var changed      = require('gulp-changed');
var concat       = require('gulp-concat');
var flatten      = require('gulp-flatten');
var gulp         = require('gulp');
var bless        = require('gulp-bless');
var gulpif       = require('gulp-if');
var imagemin     = require('gulp-imagemin');
var jshint       = require('gulp-jshint');
var lazypipe     = require('lazypipe');
var less         = require('gulp-less');
var merge        = require('merge-stream');
var minifyCss    = require('gulp-minify-css');
var plumber      = require('gulp-plumber');
var rev          = require('gulp-rev');
var runSequence  = require('run-sequence');
var sass         = require('gulp-sass');
var sourcemaps   = require('gulp-sourcemaps');
var uglify       = require('gulp-uglify');

// See https://github.com/austinpray/asset-builder
var manifest = require('asset-builder')('./assets/manifest.json');

// `path` - Paths to base asset directories. With trailing slashes.
// - `path.source` - Path to the source files. Default: `assets/`
// - `path.dist` - Path to the build directory. Default: `dist/`
var path = manifest.paths;

// `config` - Store arbitrary configuration values here.
var config = manifest.config || {};

// `globs` - These ultimately end up in their respective `gulp.src`.
// - `globs.js` - Array of asset-builder JS dependency objects. Example:
//   ```
//   {type: 'js', name: 'main.js', globs: []}
//   ```
// - `globs.css` - Array of asset-builder CSS dependency objects. Example:
//   ```
//   {type: 'css', name: 'main.css', globs: []}
//   ```
// - `globs.fonts` - Array of font path globs.
// - `globs.images` - Array of image path globs.
// - `globs.bower` - Array of all the main Bower files.
var globs = manifest.globs;

// `project` - paths to first-party assets.
// - `project.js` - Array of first-party JS assets.
// - `project.css` - Array of first-party CSS assets.
var project = manifest.getProjectGlobs();

// CLI options
var enabled = {
  // Enable static asset revisioning when `--production`
  rev: argv.production,
  // Disable source maps when `--production`
  maps: !argv.production,
  // Fail styles task on error when `--production`
  failStyleTask: argv.production,
  // Fail due to JSHint warnings only when `--production`
  failJSHint: argv.production,
  // Strip debug statments from javascript when `--production`
  stripJSDebug: argv.production,
  // Minify CSS, JS, and Images
  minify: !argv.fast,
  // Split minified css when '--production'
  split: argv.production
};

// Path to the compiled assets manifest in the dist directory
var revManifest = path.dist + 'assets.json';

// ## Reusable Pipelines
// See https://github.com/OverZealous/lazypipe

// ### CSS processing pipeline
// Example
// ```
// gulp.src(cssFiles)
//   .pipe(cssTasks('main.css')
//   .pipe(gulp.dest(path.dist + 'styles'))
// ```
var cssTasks = function(filename) {
  return lazypipe()
    .pipe(function() {
      return gulpif(!enabled.failStyleTask, plumber());
    })
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.init());
    })
    .pipe(function() {
      return gulpif('*.less', less());
    })
    .pipe(function() {
      return gulpif('*.scss', sass({
        outputStyle: 'nested', // libsass doesn't support expanded yet
        precision: 10,
        includePaths: ['.'],
        errLogToConsole: !enabled.failStyleTask
      }));
    })
    .pipe(concat, filename)
    .pipe(autoprefixer, {
      browsers: [
        'last 2 versions',
        'ie 8',
        'ie 9',
        'android 2.3',
        'android 4',
        'opera 12'
      ]
    })
    .pipe(function() {
      return gulpif(enabled.minify, minifyCss({
        advanced: false,
        rebase: false
      }));
    })
    .pipe(function() {
      return gulpif(enabled.rev, rev());
    })
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.write('.', {
        sourceRoot: 'assets/styles/'
      }));
    })();
};

// ### Bless
gulp.task('bless', function() {
  if(enabled.split) {
    return gulp.src(path.dist + 'styles/*.css')
    .pipe(bless())
     .pipe(gulp.dest(path.dist + 'styles'));
  }
});

// ### JS processing pipeline
// Example
// ```
// gulp.src(jsFiles)
//   .pipe(jsTasks('main.js')
//   .pipe(gulp.dest(path.dist + 'scripts'))
// ```
var jsTasks = function(filename) {
  return lazypipe()
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.init());
    })
    .pipe(concat, filename)
    .pipe(function() {
      return gulpif(enabled.minify, uglify({
        compress: {
          'drop_debugger': enabled.stripJSDebug
        }
      }));
    })
    .pipe(function() {
      return gulpif(enabled.rev, rev());
    })
    .pipe(function() {
      return gulpif(enabled.maps, sourcemaps.write('.', {
        sourceRoot: 'assets/scripts/'
      }));
    })();
};

// ### Write to rev manifest
// If there are any revved files then write them to the rev manifest.
// See https://github.com/sindresorhus/gulp-rev
var writeToManifest = function(directory) {
  return lazypipe()
    .pipe(gulp.dest, path.dist + directory)
    .pipe(browserSync.stream, {match: '**/*.{js,css}'})
    .pipe(rev.manifest, revManifest, {
      base: path.dist,
      merge: true
    })
    .pipe(gulp.dest, path.dist)();
};

// ## Gulp tasks
// Run `gulp -T` for a task summary

// ### Styles
// `gulp styles` - Compiles, combines, and optimizes Bower CSS and project CSS.
// By default this task will only log a warning if a precompiler error is
// raised. If the `--production` flag is set: this task will fail outright.
gulp.task('styles', ['wiredep'], function() {
  var merged = merge();
  manifest.forEachDependency('css', function(dep) {
    var cssTasksInstance = cssTasks(dep.name);
    if (!enabled.failStyleTask) {
      cssTasksInstance.on('error', function(err) {
        console.error(err.message);
        this.emit('end');
      });
    }
    merged.add(gulp.src(dep.globs, {base: 'styles'})
      .pipe(cssTasksInstance));
  });
  return merged
    .pipe(writeToManifest('styles'));
});

// ### Scripts
// `gulp scripts` - Runs JSHint then compiles, combines, and optimizes Bower JS
// and project JS.
gulp.task('scripts', ['jshint'], function() {
  var merged = merge();
  manifest.forEachDependency('js', function(dep) {
    merged.add(
      gulp.src(dep.globs, {base: 'scripts'})
        .pipe(jsTasks(dep.name))
    );
  });
  return merged
    .pipe(writeToManifest('scripts'));
});

// ### Fonts
// `gulp fonts` - Grabs all the fonts and outputs them in a flattened directory
// structure. See: https://github.com/armed/gulp-flatten
gulp.task('fonts', function() {
  return gulp.src(globs.fonts)
    .pipe(flatten())
    .pipe(gulp.dest(path.dist + 'fonts'))
    .pipe(browserSync.stream());
});

// ### Images
// `gulp images` - Run lossless compression on all the images.
gulp.task('images', function() {
  return gulp.src(globs.images)
    .pipe(gulpif(enabled.minify, imagemin({
      progressive: true,
      interlaced: true,
      svgoPlugins: [{removeUnknownsAndDefaults: false}, {cleanupIDs: false}]
    })))
    .pipe(gulp.dest(path.dist + 'images'))
    .pipe(browserSync.stream());
});

// ### JSHint
// `gulp jshint` - Lints configuration JSON and project JS.
gulp.task('jshint', function() {
  return gulp.src([
    'bower.json', 'gulpfile.js'
  ].concat(project.js))
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'))
    .pipe(gulpif(enabled.failJSHint, jshint.reporter('fail')));
});

// ### Clean
// `gulp clean` - Deletes the build folder entirely.
gulp.task('clean', require('del').bind(null, [path.dist]));

// ### Watch
// `gulp watch` - Use BrowserSync to proxy your dev server and synchronize code
// changes across devices. Specify the hostname of your dev server at
// `manifest.config.devUrl`. When a modification is made to an asset, run the
// build step for that asset and inject the changes into the page.
// See: http://www.browsersync.io
gulp.task('watch', function() {
	var url = process.cwd();
	url = url.split('/');
	var finalurl = "http://" + url[4] + "." + url[2] + ".56.cubelab.ch";
	browserSync.init({
		files: ['{lib,templates}/**/*.php', '*.php'],
		proxy: finalurl, snippetOptions: {
			whitelist: ['/wp-admin/admin-ajax.php'],
			blacklist: ['/wp-admin/**']
		},
		middleware: function (req, res, next) {
			res.setHeader('Access-Control-Allow-Origin', '*');
			next();
		}
	});
	gulp.watch([path.source + 'styles/**/*'], ['styles']);
	gulp.watch([path.source + 'scripts/**/*'], ['jshint', 'scripts']);
	gulp.watch([path.source + 'fonts/**/*'], ['fonts']);
	gulp.watch([path.source + 'images/**/*'], ['images']);
	gulp.watch(['bower.json', 'assets/manifest.json'], ['build']);
});

// ### Build
// `gulp build` - Run all the build tasks but don't clean up beforehand.
// Generally you should be running `gulp` instead of `gulp build`.
gulp.task('build', function(callback) {
  runSequence('styles',
  			  'bless',
              'scripts',
              ['fonts', 'images'],
              callback);
});

// ### Wiredep
// `gulp wiredep` - Automatically inject Less and Sass Bower dependencies. See
// https://github.com/taptapship/wiredep
gulp.task('wiredep', function() {
  var wiredep = require('wiredep').stream;
  return gulp.src(project.css)
    .pipe(wiredep())
    .pipe(changed(path.source + 'styles', {
      hasChanged: changed.compareSha1Digest
    }))
    .pipe(gulp.dest(path.source + 'styles'));
});

// ### Gulp
// `gulp` - Run a complete build. To compile for production run `gulp --production`.
gulp.task('default', ['clean'], function() {
  gulp.start('build');
});<|endoftext|>


<commit_before>'use strict';

// TODO: clean-up

var abs = require( '@stdlib/math/base/special/abs' );
var divide = require( 'compute-divide' );
var mean = require( 'compute-mean' );
var subtract = require( 'compute-subtract' );
var acosh = require( './../lib' );

var data = require( './fixtures/julia/data.json' );

var x = data.x;
var yexpected = data.expected;
var ycustom = new Array( x.length );
var ynative = new Array( x.length );
for ( var i = 0; i < x.length; i++ ) {
	if ( yexpected[ i ] === 0.0 ) {
		yexpected[ i ] += 1e-16;
	}
	ycustom[ i ] = acosh( x[ i ] );
	ynative[ i ] = Math.acosh( x[ i ] );
}

var customErrs = abs( divide( subtract( ycustom, yexpected ), yexpected ) );
var nativeErrs = abs( divide( subtract( ynative, yexpected ), yexpected ) );

console.log( 'The mean relative error of Math.acosh compared to Julia is %d', mean( nativeErrs ) );
console.log( 'The mean relative error of this module compared to Julia is %d', mean( customErrs ) );
<commit_msg>Move variable declarations and add section headers<commit_after>'use strict';

// TODO: clean-up

// MODULES //

var abs = require( '@stdlib/math/base/special/abs' );
var divide = require( 'compute-divide' );
var mean = require( 'compute-mean' );
var subtract = require( 'compute-subtract' );
var acosh = require( './../lib' );

// FIXTURES //

var data = require( './fixtures/julia/data.json' );

// MAIN //

var customErrs;
var nativeErrs;
var yexpected;
var ynative;
var ycustom;
var x;
var i;

x = data.x;
yexpected = data.expected;
ycustom = new Array( x.length );
ynative = new Array( x.length );
for ( i = 0; i < x.length; i++ ) {
	if ( yexpected[ i ] === 0.0 ) {
		yexpected[ i ] += 1e-16;
	}
	ycustom[ i ] = acosh( x[ i ] );
	ynative[ i ] = Math.acosh( x[ i ] );
}

customErrs = abs( divide( subtract( ycustom, yexpected ), yexpected ) );
nativeErrs = abs( divide( subtract( ynative, yexpected ), yexpected ) );

console.log( 'The mean relative error of Math.acosh compared to Julia is %d', mean( nativeErrs ) );
console.log( 'The mean relative error of this module compared to Julia is %d', mean( customErrs ) );
<|endoftext|>


<commit_before>const gulp = require('gulp');
const less = require('gulp-less');
const dest = require('gulp-dest');
const watch = require('gulp-watch');
const uglify = require('gulp-uglify');
const concat = require('gulp-concat');
const rename = require('gulp-rename');
const gutil = require('gulp-util');
const proxy    = require('http-proxy-middleware')
const sync     = require('browser-sync')
const history  = require('connect-history-api-fallback')

gulp.task('server', function() {
    const proxyDjango = proxy('/', {target: 'http://localhost:8888', xfwd: true})

    sync.init({
        notify: false,
        open: false,
        port: 8000,
        server: {
            baseDir: '/galaxy',
            middleware: [proxyDjango, history()]
        }
    });
});

gulp.task('accountApp', function() {
    return gulp.src([
        './galaxy/static/js/accountApp/*.js',
        './galaxy/static/js/commonDirectives/*.js',
        './galaxy/static/js/commonServices/*.js'
    ])
    .pipe(concat('galaxy.accountApp.js'))
    .pipe(uglify({ 'mangle': true, 'compress': true }))
    .pipe(rename({extname: ".min.js"}))
    .pipe(gulp.dest('./galaxy/static/dist'));
});

gulp.task('detailApp', function() {
    return gulp.src([
        './galaxy/static/js/detailApp/*.js',
        './galaxy/static/js/commonDirectives/*.js',
        './galaxy/static/js/commonServices/*.js'
    ])
    .pipe(concat('galaxy.detailApp.js'))
    .pipe(uglify({ 'mangle': true, 'compress': true }))
    .pipe(rename({extname: ".min.js"}))
    .pipe(gulp.dest('./galaxy/static/dist'));
});

gulp.task('listApp', function() {
    return gulp.src([
        './galaxy/static/js/listApp/*.js',
        './galaxy/static/js/commonDirectives/*.js',
        './galaxy/static/js/commonServices/*.js'
    ])
    .pipe(concat('galaxy.listApp.js'))
    .pipe(uglify({ 'mangle': true, 'compress': true }))
    .pipe(rename({extname: ".min.js"}))
    .pipe(gulp.dest('./galaxy/static/dist'));
});

gulp.task('exploreApp', function() {
    return gulp.src([
        './galaxy/static/js/exploreApp/*.js',
        './galaxy/static/js/commonDirectives/*.js',
        './galaxy/static/js/commonServices/*.js'
    ])
    .pipe(concat('galaxy.exploreApp.js'))
    .pipe(uglify({ 'mangle': true, 'compress': true }))
    .pipe(rename({extname: ".min.js"}))
    .pipe(gulp.dest('./galaxy/static/dist'));
});

gulp.task('importStatusApp', function() {
    return gulp.src([
        './galaxy/static/js/importStatusApp/*.js',
        './galaxy/static/js/commonDirectives/*.js',
        './galaxy/static/js/commonServices/*.js'
    ])
    .pipe(concat('galaxy.importStatusApp.js'))
    .pipe(uglify({ 'mangle': true, 'compress': true }))
    .pipe(rename({extname: ".min.js"}))
    .pipe(gulp.dest('./galaxy/static/dist'));
});

gulp.task('roleAddApp', function() {
    return gulp.src([
        './galaxy/static/js/roleAddApp/*.js',
        './galaxy/static/js/commonDirectives/*.js',
        './galaxy/static/js/commonServices/*.js'
    ])
    .pipe(concat('galaxy.roleAddApp.js'))
    .pipe(uglify({ 'mangle': true, 'compress': true }))
    .pipe(rename({extname: ".min.js"}))
    .pipe(gulp.dest('./galaxy/static/dist'));
});

gulp.task('userStarredApp', function() {
    return gulp.src([
        './galaxy/static/js/userStarredApp/*.js',
        './galaxy/static/js/commonDirectives/*.js',
        './galaxy/static/js/commonServices/*.js'
    ])
    .pipe(concat('galaxy.userStarredApp.js'))
    .pipe(uglify({ 'mangle': true, 'compress': true }))
    .pipe(rename({extname: ".min.js"}))
    .pipe(gulp.dest('./galaxy/static/dist'));
});

gulp.task('less', function() {
    return gulp.src(['./galaxy/static/less/galaxy.less'])
        .pipe(less({
            compress: true
        }))
        .on('error', gutil.log)
        .pipe(dest('galaxy/static/css', {ext: '.min.css'}))
        .pipe(gulp.dest('./'));
});

gulp.task('less-watch', ['less'], function (done) {
    sync.reload();
    done();
});

gulp.task('generic-watch', function(done) {
    sync.reload();
    done();
});

gulp.task('watch', function () {
    gulp.watch('./galaxy/static/less/*.less', ['less-watch']);
    gulp.watch('./galaxy/static/js/*/*.js', ['generic-watch']);
    gulp.watch('./galaxy/static/partials/*.html', ['generic-watch']);
});

gulp.task('default', ['less', 'server', 'watch']);
gulp.task('build', ['less', 'accountApp', 'listApp', 'detailApp', 'exploreApp', 'roleAddApp', 'importStatusApp']);
<commit_msg>Add `userStarredApp` task to `build` step in gulpfile<commit_after>const gulp = require('gulp');
const less = require('gulp-less');
const dest = require('gulp-dest');
const watch = require('gulp-watch');
const uglify = require('gulp-uglify');
const concat = require('gulp-concat');
const rename = require('gulp-rename');
const gutil = require('gulp-util');
const proxy    = require('http-proxy-middleware')
const sync     = require('browser-sync')
const history  = require('connect-history-api-fallback')

gulp.task('server', function() {
    const proxyDjango = proxy('/', {target: 'http://localhost:8888', xfwd: true})

    sync.init({
        notify: false,
        open: false,
        port: 8000,
        server: {
            baseDir: '/galaxy',
            middleware: [proxyDjango, history()]
        }
    });
});

gulp.task('accountApp', function() {
    return gulp.src([
        './galaxy/static/js/accountApp/*.js',
        './galaxy/static/js/commonDirectives/*.js',
        './galaxy/static/js/commonServices/*.js'
    ])
    .pipe(concat('galaxy.accountApp.js'))
    .pipe(uglify({ 'mangle': true, 'compress': true }))
    .pipe(rename({extname: ".min.js"}))
    .pipe(gulp.dest('./galaxy/static/dist'));
});

gulp.task('detailApp', function() {
    return gulp.src([
        './galaxy/static/js/detailApp/*.js',
        './galaxy/static/js/commonDirectives/*.js',
        './galaxy/static/js/commonServices/*.js'
    ])
    .pipe(concat('galaxy.detailApp.js'))
    .pipe(uglify({ 'mangle': true, 'compress': true }))
    .pipe(rename({extname: ".min.js"}))
    .pipe(gulp.dest('./galaxy/static/dist'));
});

gulp.task('listApp', function() {
    return gulp.src([
        './galaxy/static/js/listApp/*.js',
        './galaxy/static/js/commonDirectives/*.js',
        './galaxy/static/js/commonServices/*.js'
    ])
    .pipe(concat('galaxy.listApp.js'))
    .pipe(uglify({ 'mangle': true, 'compress': true }))
    .pipe(rename({extname: ".min.js"}))
    .pipe(gulp.dest('./galaxy/static/dist'));
});

gulp.task('exploreApp', function() {
    return gulp.src([
        './galaxy/static/js/exploreApp/*.js',
        './galaxy/static/js/commonDirectives/*.js',
        './galaxy/static/js/commonServices/*.js'
    ])
    .pipe(concat('galaxy.exploreApp.js'))
    .pipe(uglify({ 'mangle': true, 'compress': true }))
    .pipe(rename({extname: ".min.js"}))
    .pipe(gulp.dest('./galaxy/static/dist'));
});

gulp.task('importStatusApp', function() {
    return gulp.src([
        './galaxy/static/js/importStatusApp/*.js',
        './galaxy/static/js/commonDirectives/*.js',
        './galaxy/static/js/commonServices/*.js'
    ])
    .pipe(concat('galaxy.importStatusApp.js'))
    .pipe(uglify({ 'mangle': true, 'compress': true }))
    .pipe(rename({extname: ".min.js"}))
    .pipe(gulp.dest('./galaxy/static/dist'));
});

gulp.task('roleAddApp', function() {
    return gulp.src([
        './galaxy/static/js/roleAddApp/*.js',
        './galaxy/static/js/commonDirectives/*.js',
        './galaxy/static/js/commonServices/*.js'
    ])
    .pipe(concat('galaxy.roleAddApp.js'))
    .pipe(uglify({ 'mangle': true, 'compress': true }))
    .pipe(rename({extname: ".min.js"}))
    .pipe(gulp.dest('./galaxy/static/dist'));
});

gulp.task('userStarredApp', function() {
    return gulp.src([
        './galaxy/static/js/userStarredApp/*.js',
        './galaxy/static/js/commonDirectives/*.js',
        './galaxy/static/js/commonServices/*.js'
    ])
    .pipe(concat('galaxy.userStarredApp.js'))
    .pipe(uglify({ 'mangle': true, 'compress': true }))
    .pipe(rename({extname: ".min.js"}))
    .pipe(gulp.dest('./galaxy/static/dist'));
});

gulp.task('less', function() {
    return gulp.src(['./galaxy/static/less/galaxy.less'])
        .pipe(less({
            compress: true
        }))
        .on('error', gutil.log)
        .pipe(dest('galaxy/static/css', {ext: '.min.css'}))
        .pipe(gulp.dest('./'));
});

gulp.task('less-watch', ['less'], function (done) {
    sync.reload();
    done();
});

gulp.task('generic-watch', function(done) {
    sync.reload();
    done();
});

gulp.task('watch', function () {
    gulp.watch('./galaxy/static/less/*.less', ['less-watch']);
    gulp.watch('./galaxy/static/js/*/*.js', ['generic-watch']);
    gulp.watch('./galaxy/static/partials/*.html', ['generic-watch']);
});

gulp.task('default', ['less', 'server', 'watch']);
gulp.task('build', [
    'less', 'accountApp', 'listApp', 'detailApp',
    'exploreApp', 'roleAddApp', 'importStatusApp', 'userStarredApp'
]);
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var tape = require( 'tape' );
var abs = require( '@stdlib/math/base/special/abs' );
var linspace = require( '@stdlib/math/generics/utils/linspace' );
var pow = require( '@stdlib/math/base/special/pow' );
var PINF = require( '@stdlib/math/constants/float64-pinf' );
var NINF = require( '@stdlib/math/constants/float64-ninf' );
var EPS = require( '@stdlib/math/constants/float64-eps' );
var zeta = require( './../lib' );

// FIXTURES //

var data = require( './fixtures/output.json' ).program_message;
data = JSON.parse( data );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof zeta, 'function', 'main export is a function' );
	t.end();
});

tape( 'if provided `NaN`, the function returns `NaN`', function test( t ) {
	var v = zeta( NaN );
	t.ok( v !== v, 'returns NaN when provided a NaN' );
	t.end();
});

tape( 'the function evaluates the Riemann zeta function', function test( t ) {
	var expected;
	var delta;
	var tol;
	var s;
	var v;
	var i;

	s = data.x;
	expected = data.expected;
	for ( i = 0; i < s.length; i++ ) {
		v = zeta( s[i] );
		delta = abs( v - expected[i] );
		tol = 34 * EPS * abs( expected[i] );
		t.ok( delta <= tol, 'within tolerance. s: '+s[i]+'. v: '+v+'. E: '+expected[i]+'. Δ: '+delta+'. Tol: '+tol+'.' );
	}
	t.end();
});

tape( 'the function evaluates the Riemann zeta function for very small values', function test( t ) {
	var v = zeta( 1e-10 );

	// Checked against Julia:
	t.equal( v, -0.5000000000918938 );

	t.end();
});

tape( 'if evaluated at a pole (`s = 1`), the function returns `NaN`', function test( t ) {
	var v = zeta( 1.0 );
	t.ok( v !== v, 'returns NaN when provided 1' );
	t.end();
});

tape( 'the function returns `1` for all input values greater or equal than `56`', function test( t ) {
	var s;
	var v;
	var i;

	s = linspace( 56, 100, 200 );
	for ( i = 0; i < s.length; i++ ) {
		v = zeta( s[ i ] );
		t.equal( v, 1, 'returns 1 when provided '+s[i] );
	}
	v = zeta( PINF );
	t.equal( v, 1, 'returns 1 when provided +infinity' );

	t.end();
});

tape( 'the function returns `0` for all even negative integers', function test( t ) {
	var s;
	var v;
	var i;

	s = linspace( -2, -200, 100 );
	for ( i = 0; i < s.length; i++ ) {
		v = zeta( s[ i ] );
		t.equal( v, 0.0, 'returns 0 when provided '+s[i] );
	}
	s = -pow( 2, 32 ); // |s| is greater than MAX_INT32
	v = zeta( s );
	t.equal( v, 0.0, 'returns 0 when provided '+s );
	t.end();
});

tape( 'the function handles negative values which are larger in magnitude than the maximum factorial', function test( t ) {
	var expected;
	var delta;
	var tol;
	var s;
	var v;

	// Wolfram: zeta( -170.7 )
	expected = 4.236821692180446371109004075383326908604561232133963e171;

	s = -170.7;
	v = zeta( s );
	delta = abs( v - expected );
	tol = 53 * EPS * abs( expected );

	t.ok( delta <= tol, 'within tolerance. s: '+s+'. v: '+v+'. E: '+expected+' Δ: '+delta+'. tol: '+tol );

	// Wolfram: zeta( -171.1 )
	expected = 1.762429756041972327545919944532107376580768035147432e172;

	s = -171.1;
	v = zeta( s );
	delta = abs( v - expected );

	// Note: FF seems to return less precise results (https://travis-ci.org/math-io/riemann-zeta/jobs/115748766). For Node/Chrome, 286*eps.
	tol = 355 * EPS * abs( expected );

	t.ok( delta <= tol, 'within tolerance. s: '+s+'. v: '+v+'. E: '+expected+' Δ: '+delta+'. tol: '+tol );

	t.end();
});

tape( 'the function handles negative integer values which are larger in magnitude than twice the index of the maximum Bernoulli number', function test( t ) {
	var expected;
	var delta;
	var tol;
	var s;
	var v;

	// Only value satisfies this criterion without overflowing: -259. (|-257|+1)/2| = 128, which is the index of the largest Bernoulli number. -261 overflows.

	// Wolfram: zeta( -259 )
	expected = 8.760156344622921514904073013488223219302793651253880e306;

	s = -259;
	v = zeta( s );
	delta = abs( v - expected );
	tol = 352 * EPS * abs( expected );

	t.ok( delta <= tol, 'within tolerance. s: '+s+'. v: '+v+'. E: '+expected+' Δ: '+delta+'. tol: '+tol );

	t.end();
});

tape( 'the function returns `+-infinity` for large negative non-integer values', function test( t ) {
	var s;
	var v;
	var i;

	s = linspace( -259.78778778778684, -10000.123, 103 );
	for ( i = 0; i < s.length; i++ ) {
		v = zeta( s[ i ] );
		t.ok( v === PINF || v === NINF, 'returns '+v+' when provided '+s[i] );
	}
	t.end();
});

tape( 'if provided `0` (special value), the function returns `-0.5`', function test( t ) {
	var v = zeta( 0 );
	t.equal( v, -0.5, 'returns -0.5' );
	t.end();
});

tape( 'if provided `-1` (special value), the function returns `-1/12`', function test( t ) {
	var v = zeta( -1 );
	t.equal( v, -1/12, 'returns -1/12' );
	t.end();
});

tape( 'if provided `-13` (special value), the function returns `-1/12`', function test( t ) {
	var expected;
	var delta;
	var tol;
	var s;
	var v;

	expected = -1/12;

	s = -13;
	v = zeta( s );
	delta = abs( v - expected );
	tol = EPS * abs( expected );

	t.ok( delta <= tol, 'within tolerance. s: '+s+'. v: '+v+'. E: '+expected+' Δ: '+delta+'. tol: '+tol );
	t.end();
});

tape( 'if provided `4` (special value), the function returns `~1.0823`', function test( t ) {
	var expected;
	var delta;
	var tol;
	var s;
	var v;

	// https://oeis.org/A0013662
	expected = 1.082323233711138191516003696541167;

	s = 4;
	v = zeta( s );
	delta = abs( v - expected );
	tol = EPS * abs( expected );

	t.ok( delta <= tol, 'within tolerance. s: '+s+'. v: '+v+'. E: '+expected+' Δ: '+delta+'. tol: '+tol );
	t.end();
});

tape( 'if provided `3` (special value), the function returns `~1.202`', function test( t ) {
	var expected;
	var delta;
	var tol;
	var s;
	var v;

	// https://oeis.org/A002117
	expected = 1.2020569031595942853997;

	s = 3;
	v = zeta( s );
	delta = abs( v - expected );
	tol = EPS * abs( expected );

	t.ok( delta <= tol, 'within tolerance. s: '+s+'. v: '+v+'. E: '+expected+' Δ: '+delta+'. tol: '+tol );
	t.end();
});

tape( 'if provided `2` (special value), the function returns `~1.645`', function test( t ) {
	var expected;
	var delta;
	var tol;
	var s;
	var v;

	// https://oeis.org/A013661
	expected = 1.6449340668482264364724151666460251892189499012067984377355582293700074704032;

	s = 2;
	v = zeta( s );
	delta = abs( v - expected );
	tol = EPS * abs( expected );

	t.ok( delta <= tol, 'within tolerance. s: '+s+'. v: '+v+'. E: '+expected+' Δ: '+delta+'. tol: '+tol );
	t.end();
});

tape( 'if provided `3/2` (special value), the function returns `~2.612`', function test( t ) {
	var expected;
	var delta;
	var tol;
	var s;
	var v;

	// https://oeis.org/A078434
	expected = 2.61237534868548834334856756792407163057080065240006340757332824881492776768827286099624386812631195238297;

	s = 3/2;
	v = zeta( s );
	delta = abs( v - expected );
	tol = EPS * abs( expected );

	t.ok( delta <= tol, 'within tolerance. s: '+s+'. v: '+v+'. E: '+expected+' Δ: '+delta+'. tol: '+tol );
	t.end();
});

tape( 'if provided `1/2` (special value), the function returns `~-1.46`', function test( t ) {
	var expected;
	var delta;
	var tol;
	var s;
	var v;

	// https://oeis.org/A059750
	expected = -1.4603545088095868128894991525152980124672293310125814905428860878;

	s = 1/2;
	v = zeta( s );
	delta = abs( v - expected );
	tol = EPS * abs( expected );

	t.ok( delta <= tol, 'within tolerance. s: '+s+'. v: '+v+'. E: '+expected+' Δ: '+delta+'. tol: '+tol );
	t.end();
});
<commit_msg>Use is-nan util to check for NaN return values<commit_after>'use strict';

// MODULES //

var tape = require( 'tape' );
var isnan = require( '@stdlib/math/base/utils/is-nan' );
var abs = require( '@stdlib/math/base/special/abs' );
var linspace = require( '@stdlib/math/generics/utils/linspace' );
var pow = require( '@stdlib/math/base/special/pow' );
var PINF = require( '@stdlib/math/constants/float64-pinf' );
var NINF = require( '@stdlib/math/constants/float64-ninf' );
var EPS = require( '@stdlib/math/constants/float64-eps' );
var zeta = require( './../lib' );

// FIXTURES //

var data = require( './fixtures/output.json' ).program_message;
data = JSON.parse( data );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof zeta, 'function', 'main export is a function' );
	t.end();
});

tape( 'if provided `NaN`, the function returns `NaN`', function test( t ) {
	var v = zeta( NaN );
	t.equal( isnan( v ), true, 'returns NaN when provided a NaN' );
	t.end();
});

tape( 'the function evaluates the Riemann zeta function', function test( t ) {
	var expected;
	var delta;
	var tol;
	var s;
	var v;
	var i;

	s = data.x;
	expected = data.expected;
	for ( i = 0; i < s.length; i++ ) {
		v = zeta( s[i] );
		delta = abs( v - expected[i] );
		tol = 34 * EPS * abs( expected[i] );
		t.ok( delta <= tol, 'within tolerance. s: '+s[i]+'. v: '+v+'. E: '+expected[i]+'. Δ: '+delta+'. Tol: '+tol+'.' );
	}
	t.end();
});

tape( 'the function evaluates the Riemann zeta function for very small values', function test( t ) {
	var v = zeta( 1e-10 );

	// Checked against Julia:
	t.equal( v, -0.5000000000918938 );

	t.end();
});

tape( 'if evaluated at a pole (`s = 1`), the function returns `NaN`', function test( t ) {
	var v = zeta( 1.0 );
	t.equal( isnan( v ), true, 'returns NaN when provided 1' );
	t.end();
});

tape( 'the function returns `1` for all input values greater or equal than `56`', function test( t ) {
	var s;
	var v;
	var i;

	s = linspace( 56, 100, 200 );
	for ( i = 0; i < s.length; i++ ) {
		v = zeta( s[ i ] );
		t.equal( v, 1, 'returns 1 when provided '+s[i] );
	}
	v = zeta( PINF );
	t.equal( v, 1, 'returns 1 when provided +infinity' );

	t.end();
});

tape( 'the function returns `0` for all even negative integers', function test( t ) {
	var s;
	var v;
	var i;

	s = linspace( -2, -200, 100 );
	for ( i = 0; i < s.length; i++ ) {
		v = zeta( s[ i ] );
		t.equal( v, 0.0, 'returns 0 when provided '+s[i] );
	}
	s = -pow( 2, 32 ); // |s| is greater than MAX_INT32
	v = zeta( s );
	t.equal( v, 0.0, 'returns 0 when provided '+s );
	t.end();
});

tape( 'the function handles negative values which are larger in magnitude than the maximum factorial', function test( t ) {
	var expected;
	var delta;
	var tol;
	var s;
	var v;

	// Wolfram: zeta( -170.7 )
	expected = 4.236821692180446371109004075383326908604561232133963e171;

	s = -170.7;
	v = zeta( s );
	delta = abs( v - expected );
	tol = 53 * EPS * abs( expected );

	t.ok( delta <= tol, 'within tolerance. s: '+s+'. v: '+v+'. E: '+expected+' Δ: '+delta+'. tol: '+tol );

	// Wolfram: zeta( -171.1 )
	expected = 1.762429756041972327545919944532107376580768035147432e172;

	s = -171.1;
	v = zeta( s );
	delta = abs( v - expected );

	// Note: FF seems to return less precise results (https://travis-ci.org/math-io/riemann-zeta/jobs/115748766). For Node/Chrome, 286*eps.
	tol = 355 * EPS * abs( expected );

	t.ok( delta <= tol, 'within tolerance. s: '+s+'. v: '+v+'. E: '+expected+' Δ: '+delta+'. tol: '+tol );

	t.end();
});

tape( 'the function handles negative integer values which are larger in magnitude than twice the index of the maximum Bernoulli number', function test( t ) {
	var expected;
	var delta;
	var tol;
	var s;
	var v;

	// Only value satisfies this criterion without overflowing: -259. (|-257|+1)/2| = 128, which is the index of the largest Bernoulli number. -261 overflows.

	// Wolfram: zeta( -259 )
	expected = 8.760156344622921514904073013488223219302793651253880e306;

	s = -259;
	v = zeta( s );
	delta = abs( v - expected );
	tol = 352 * EPS * abs( expected );

	t.ok( delta <= tol, 'within tolerance. s: '+s+'. v: '+v+'. E: '+expected+' Δ: '+delta+'. tol: '+tol );

	t.end();
});

tape( 'the function returns `+-infinity` for large negative non-integer values', function test( t ) {
	var s;
	var v;
	var i;

	s = linspace( -259.78778778778684, -10000.123, 103 );
	for ( i = 0; i < s.length; i++ ) {
		v = zeta( s[ i ] );
		t.ok( v === PINF || v === NINF, 'returns '+v+' when provided '+s[i] );
	}
	t.end();
});

tape( 'if provided `0` (special value), the function returns `-0.5`', function test( t ) {
	var v = zeta( 0 );
	t.equal( v, -0.5, 'returns -0.5' );
	t.end();
});

tape( 'if provided `-1` (special value), the function returns `-1/12`', function test( t ) {
	var v = zeta( -1 );
	t.equal( v, -1/12, 'returns -1/12' );
	t.end();
});

tape( 'if provided `-13` (special value), the function returns `-1/12`', function test( t ) {
	var expected;
	var delta;
	var tol;
	var s;
	var v;

	expected = -1/12;

	s = -13;
	v = zeta( s );
	delta = abs( v - expected );
	tol = EPS * abs( expected );

	t.ok( delta <= tol, 'within tolerance. s: '+s+'. v: '+v+'. E: '+expected+' Δ: '+delta+'. tol: '+tol );
	t.end();
});

tape( 'if provided `4` (special value), the function returns `~1.0823`', function test( t ) {
	var expected;
	var delta;
	var tol;
	var s;
	var v;

	// https://oeis.org/A0013662
	expected = 1.082323233711138191516003696541167;

	s = 4;
	v = zeta( s );
	delta = abs( v - expected );
	tol = EPS * abs( expected );

	t.ok( delta <= tol, 'within tolerance. s: '+s+'. v: '+v+'. E: '+expected+' Δ: '+delta+'. tol: '+tol );
	t.end();
});

tape( 'if provided `3` (special value), the function returns `~1.202`', function test( t ) {
	var expected;
	var delta;
	var tol;
	var s;
	var v;

	// https://oeis.org/A002117
	expected = 1.2020569031595942853997;

	s = 3;
	v = zeta( s );
	delta = abs( v - expected );
	tol = EPS * abs( expected );

	t.ok( delta <= tol, 'within tolerance. s: '+s+'. v: '+v+'. E: '+expected+' Δ: '+delta+'. tol: '+tol );
	t.end();
});

tape( 'if provided `2` (special value), the function returns `~1.645`', function test( t ) {
	var expected;
	var delta;
	var tol;
	var s;
	var v;

	// https://oeis.org/A013661
	expected = 1.6449340668482264364724151666460251892189499012067984377355582293700074704032;

	s = 2;
	v = zeta( s );
	delta = abs( v - expected );
	tol = EPS * abs( expected );

	t.ok( delta <= tol, 'within tolerance. s: '+s+'. v: '+v+'. E: '+expected+' Δ: '+delta+'. tol: '+tol );
	t.end();
});

tape( 'if provided `3/2` (special value), the function returns `~2.612`', function test( t ) {
	var expected;
	var delta;
	var tol;
	var s;
	var v;

	// https://oeis.org/A078434
	expected = 2.61237534868548834334856756792407163057080065240006340757332824881492776768827286099624386812631195238297;

	s = 3/2;
	v = zeta( s );
	delta = abs( v - expected );
	tol = EPS * abs( expected );

	t.ok( delta <= tol, 'within tolerance. s: '+s+'. v: '+v+'. E: '+expected+' Δ: '+delta+'. tol: '+tol );
	t.end();
});

tape( 'if provided `1/2` (special value), the function returns `~-1.46`', function test( t ) {
	var expected;
	var delta;
	var tol;
	var s;
	var v;

	// https://oeis.org/A059750
	expected = -1.4603545088095868128894991525152980124672293310125814905428860878;

	s = 1/2;
	v = zeta( s );
	delta = abs( v - expected );
	tol = EPS * abs( expected );

	t.ok( delta <= tol, 'within tolerance. s: '+s+'. v: '+v+'. E: '+expected+' Δ: '+delta+'. tol: '+tol );
	t.end();
});
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    tinylr = require('tiny-lr'), // Mini webserver for livereload
    minifyCSS = require('gulp-minify-css'), // CSS minifying
    watch = require('gulp-watch'),
    shell = require('gulp-shell'),
    print = require('gulp-print'),
    jshint = require('gulp-jshint'),
    stylish = require('jshint-stylish'),
    //imagemin = require('gulp-imagemin'), // Img minifying
    uglify = require('gulp-uglify'),    // JS minifying
    concat = require('gulp-concat'),    // Files merging
    rev = require('gulp-rev'),          // Files versioning
    compass = require('gulp-compass'),  // Compass to work with CSS
    rjs = require("gulp-requirejs"),    //A gulp interface to r.js
    connect = require('gulp-connect'),  // Webserver
    rename = require("gulp-rename"),    //Rename files
    useref = require('gulp-useref'),    //Removes <!-- build:js ... blocks from html
    replaceRevRef = require('gulp-rev-manifest-replace'), //Plugin to replace assets urls based on generated manifest file
    reverse = require('reversible'),
    rimraf = require('gulp-rimraf');                      // Remove files and folders
    //wait = require('gulp-wait'),
    //
    //server = lr(),
    //livereload = require('gulp-livereload'), // Livereload for Gulp

var buildConfig = {
        jekyllStageConfig : "_config.stage.yml",
        jekyllProdConfig : "_config.prod.yml",
        jekyllGHConfig : "_config.gh.yml",
        jekyllEEConfig : "_config.enterprise.yml",
    };

var paths = {
        src: 'app/',
        prod: './target/prod/',
        stage: './target/stage/',
        gh: './target/gh/',
        temp: 'target/temp/',
        dist: 'target/dist/',
        config: 'assembly/build/',
        site: 'app/_site/'
};

// This task creates local server
gulp.task('connect', ['gh'], function() {
  connect.server({
    root: paths.gh
  });
});

// --------------------------- Building Prod -----------------------------
//----------------
//----------
gulp.task('prod',['copy_src','lint','prod_cfg','css','jekyll','rjs','myrev','replace','rmbuild','copy_prod'], function(){

})

gulp.task('prod_cfg', function(){
  return gulp.src(paths.config + buildConfig.jekyllProdConfig)
  .pipe(rename('_config.yml'))
  .pipe(gulp.dest(paths.temp))
})

gulp.task('css', ['copy_src'], function() {
  return gulp.src(paths.temp+'site/styles/*.scss')
  .pipe(compass({
    //config_file: './compass-config.rb',
    css: paths.temp +'site/styles',
    sass: paths.temp +'site/styles'
  }))
  .pipe(minifyCSS())
  .pipe(gulp.dest(paths.prod + 'site/styles/'));
});

gulp.task('lint',function(){
  gulp.src(['!'+paths.src+'site/scripts/vendor/*.*',paths.src+'site/scripts/**/*.js'])
    .pipe(jshint())
  .pipe(jshint.reporter('jshint-stylish'))
  .pipe(jshint.reporter('fail'))
});

// Builds projects using require.js's optimizer + Minify files with UglifyJS
gulp.task('rjs',['copy_src','jekyll'], function(){
      return  rjs({
            mainConfigFile: paths.temp +'site/scripts/main.js',
            //optimize: 'none', //hardcoded in requirejs plugin
            baseUrl: paths.temp + 'site/scripts',
            wrap: true,
            name: 'main',
            mainFile: paths.temp+'site/index.html',
            out: 'amd-main.js'
        })
      .pipe(print(function(filepath) {
        return "rjs -> built: " + filepath;
      }))
      .pipe(gulp.src(paths.temp +'site/scripts/vendor/require.js'))
      .pipe(reverse({objectMode: true})) // requirejs should be at the begining
      .pipe(concat('amd-app.js'))
      .pipe(uglify())
      .pipe(gulp.dest(paths.prod + 'site/scripts'));
 });

gulp.task('jekyll',['copy_src','prod_cfg'], function () {
       console.log('Jekyll building ......... ');
   return gulp.src(paths.temp+'_config.yml', {read: false})
    .pipe(shell([
      'jekyll build'
    ], {
      cwd: 'target/temp',
      templateData: {
        f: function (s) {
          return s.replace(/$/, '.bak')
        }
      }
    }))
});

// Replaces references with reved names
  gulp.task ('myrev', ['copy_src','prod_cfg','css','rjs','jekyll'], function(){
    return gulp.src([paths.prod + 'site/scripts/amd-app.js', paths.prod + 'site/styles/*.css'],{base:paths.prod})
    //.pipe(wait(1500))
    .pipe(rev())
    .pipe(print(function(filepath) {
        return "rev -> built: " + filepath;
      }))
    .pipe(gulp.dest(paths.prod))
    .pipe(rev.manifest())
    .pipe(print(function(filepath) {
        return "manifest -> built: " + filepath;
      }))
    .pipe(gulp.dest(paths.prod));
  });

// Start replacing rev references
gulp.task('replace',['copy_src','prod_cfg','css','rjs','jekyll','myrev'], function(){

  var manifest = require(paths.prod+'rev-manifest.json')
  console.log('Process rev-manifest.json: \n');
  console.log(manifest);
  return gulp.src([paths.prod+'**/*.html'])
  .pipe(replaceRevRef({
    base: process.cwd()+'/target/prod',
    manifest: manifest,
    path: ''/*,
    cdnPrefix: 'http://absolute.path/cdn/'*/
  }))
  .pipe(gulp.dest(paths.prod));

});

// Removes <!-- build:js ... blocks from html for prod configeration
gulp.task('rmbuild', ['copy_src','prod_cfg','css','rjs','jekyll','myrev','replace'], function(){
  return gulp.src(paths.prod+'**/*.html')
  .pipe(useref())
  .pipe(print(function(filepath) {
        return "remove <!-- build:js ... blocks -> built: " + filepath;
      }))
  .pipe(gulp.dest(paths.prod));

});

gulp.task('copy_prod',['copy_src','prod_cfg','css','rjs','jekyll','myrev','replace','rmbuild'], function(){
  gulp.src([paths.prod+'/**/*.html', // all HTML
    paths.prod+'**/amd-app-*.js', // minified JS
    paths.prod+'**/*-*.css', // minified CSS
    paths.prod+'**/*.jpg',
    paths.prod+'**/*.ico',
    paths.prod+'**/*.png',
    paths.prod+'**/*.svg',
    paths.prod+'**/*.txt',
    paths.prod+'**/modernizr.custom.*.js'] // robots.txt
    )
      .pipe(print(function(filepath) {
        if (filepath){return "copy prod -> built: " + filepath;}

      }))
  .pipe(gulp.dest(paths.dist+'prod'));
});

// Cleans gulp's folders
gulp.task('clean',function(){
  return gulp.src([paths.temp,paths.prod,paths.stage,paths.dist],{ read: false }) // much faster
    .pipe(rimraf());
})

// --------------------------- Building Stage -----------------------------
//----------------
//----------
gulp.task('stage',['copy_src','stage_cfg','css_stage','jekyll_stage','copy_stage'], function(){

})
// Copies src to temp folder
gulp.task('copy_src', ['duplicate_html'], function(){
  return gulp.src(paths.src + '**/*.*')
  .pipe(gulp.dest(paths.temp))
})

// Copies src to temp folder
gulp.task('duplicate_html', function(){
  return gulp.src(paths.temp + '/site/create-account.html')
  .pipe(rename('index.html'))
  .pipe(gulp.dest(paths.temp))
})

gulp.task('stage_cfg', function(){
  return gulp.src(paths.config + buildConfig.jekyllStageConfig)
  .pipe(rename('_config.yml'))
  .pipe(gulp.dest(paths.temp))
})

gulp.task('css_stage', ['copy_src'], function() {
  return gulp.src(paths.temp+'site/styles/*.scss')
  .pipe(compass({
    //config_file: './compass-config.rb',
    css: paths.temp +'site/styles',
    sass: paths.temp +'site/styles'
  }))
  .pipe(gulp.dest(paths.stage + 'site/styles/'));
});
// Ensure waiting for Jekill job finishing
gulp.task('jekyll_stage',['copy_src','stage_cfg'], function () {
         console.log('Jekyll stage......... ');
   return gulp.src(paths.temp+'_config.yml', {read: false})
    .pipe(shell([
      'jekyll build'
    ], {
      cwd: 'target/temp',
      templateData: {
        f: function (s) {
          return s.replace(/$/, '.bak')
        }
      }
    }))
});

gulp.task('copy_stage',['copy_src','stage_cfg','css_stage','jekyll_stage'], function(){
  gulp.src([paths.stage+'/**/*.html', // all HTML
    paths.stage+'**/*.js',
    paths.stage+'**/*.css',
    paths.stage+'**/*.jpg',
    paths.prod+'**/*.ico',
    paths.stage+'**/*.png',
    paths.stage+'**/*.svg',
    paths.stage+'**/*.txt'  // robots.txt
    ])
  .pipe(gulp.dest(paths.dist+'stage'));
});

// Cleans gulp's folders
gulp.task('clean',function(){
  return gulp.src([paths.temp,paths.prod,paths.stage,paths.dist],{ read: false }) // much faster
    .pipe(rimraf());
})

// --------------------------- Building GitHub pages (localhost:8080) -----------------------------
//----------------
//----------
gulp.task('gh',['copy_src','gh_cfg','css_gh','jekyll_gh','copy_gh'], function(){
  console.log('Update localhost .....');
})

gulp.task('gh_cfg', function(){
  return gulp.src(paths.config + buildConfig.jekyllGHConfig)
  .pipe(rename('_config.yml'))
  .pipe(gulp.dest(paths.temp))
})

gulp.task('css_gh', ['copy_src'], function() {
  return gulp.src(paths.temp+'site/styles/*.scss')
  .pipe(compass({
    //config_file: './compass-config.rb',
    css: paths.temp +'site/styles',
    sass: paths.temp +'site/styles'
  }))
  .pipe(gulp.dest(paths.gh + 'site/styles/'));
});

gulp.task('jekyll_gh',['copy_src','gh_cfg'], function () {
         console.log('Jekyll ......... ');
     return require('child_process')
        .spawn('jekyll', ['build'], {stdio: 'inherit', cwd: paths.temp});

});

gulp.task('copy_gh',['copy_src','gh_cfg','css_gh','jekyll_gh'], function(){
  gulp.src([paths.gh+'/**/*.html', // all HTML
    paths.gh+'**/*.js',
    paths.gh+'**/*.css',
    paths.gh+'**/*.jpg',
    paths.gh+'**/*.png',
    paths.gh+'**/*.svg',
    paths.gh+'**/*.txt'  // robots.txt
    ])
  .pipe(gulp.dest(paths.dist+'gh'));
});

gulp.task('watch', function(){
  console.log('Watching for changes in : '+paths.src+'*.*');
return gulp.watch(''+paths.src+'**/*.*',['gh']);

});

// --------------------------- Dev config for LiveReload localhost:8080) -----------------------------
//----------------
//----------
//  Set Up LiveReload (port 35729 which LiveReload uses by default)

gulp.task('express', function() {
  var express = require('express');
  var app = express();
  app.use(require('connect-livereload')({port: 4002}));
  app.use(express.static(__dirname));
  app.listen(4000);
});

var tinylr;
gulp.task('livereload', function() {
  tinylr = require('tiny-lr')();
  tinylr.listen(4002);
});

function notifyLiveReload(event) {
  var fileName = require('path').relative(__dirname, event.path);

  tinylr.changed({
    body: {
      files: [fileName]
    }
  });
}

gulp.task('__watch', function() {
  gulp.watch(''+paths.src+'site/styles/*.scss', ['css_gh']);
  gulp.watch(''+paths.src+'site/**/*.html', ['jekyll_gh']);
  gulp.watch(''+paths.gh+'**/*.html', notifyLiveReload);
  gulp.watch(''+paths.gh+'site/styles/*.css', notifyLiveReload);
});

gulp.task('lr', ['css_gh', 'express', 'livereload', 'watch'], function() {

});

// -------------------- Utils ------------------------
<commit_msg>CLDIDE fixed build index.html<commit_after>var gulp = require('gulp'),
    tinylr = require('tiny-lr'), // Mini webserver for livereload
    minifyCSS = require('gulp-minify-css'), // CSS minifying
    watch = require('gulp-watch'),
    shell = require('gulp-shell'),
    print = require('gulp-print'),
    jshint = require('gulp-jshint'),
    stylish = require('jshint-stylish'),
    //imagemin = require('gulp-imagemin'), // Img minifying
    uglify = require('gulp-uglify'),    // JS minifying
    concat = require('gulp-concat'),    // Files merging
    rev = require('gulp-rev'),          // Files versioning
    compass = require('gulp-compass'),  // Compass to work with CSS
    rjs = require("gulp-requirejs"),    //A gulp interface to r.js
    connect = require('gulp-connect'),  // Webserver
    rename = require("gulp-rename"),    //Rename files
    useref = require('gulp-useref'),    //Removes <!-- build:js ... blocks from html
    replaceRevRef = require('gulp-rev-manifest-replace'), //Plugin to replace assets urls based on generated manifest file
    reverse = require('reversible'),
    rimraf = require('gulp-rimraf');                      // Remove files and folders
    //wait = require('gulp-wait'),
    //
    //server = lr(),
    //livereload = require('gulp-livereload'), // Livereload for Gulp

var buildConfig = {
        jekyllStageConfig : "_config.stage.yml",
        jekyllProdConfig : "_config.prod.yml",
        jekyllGHConfig : "_config.gh.yml",
        jekyllEEConfig : "_config.enterprise.yml",
    };

var paths = {
        src: 'app/',
        prod: './target/prod/',
        stage: './target/stage/',
        gh: './target/gh/',
        temp: 'target/temp/',
        dist: 'target/dist/',
        config: 'assembly/build/',
        site: 'app/_site/'
};

// This task creates local server
gulp.task('connect', ['gh'], function() {
  connect.server({
    root: paths.gh
  });
});

// --------------------------- Building Prod -----------------------------
//----------------
//----------
gulp.task('prod',['copy_src','duplicate_html','lint','prod_cfg','css','jekyll','rjs','myrev','replace','rmbuild','copy_prod'], function(){

})

gulp.task('prod_cfg', function(){
  return gulp.src(paths.config + buildConfig.jekyllProdConfig)
  .pipe(rename('_config.yml'))
  .pipe(gulp.dest(paths.temp))
})

gulp.task('css', ['copy_src'], function() {
  return gulp.src(paths.temp+'site/styles/*.scss')
  .pipe(compass({
    //config_file: './compass-config.rb',
    css: paths.temp +'site/styles',
    sass: paths.temp +'site/styles'
  }))
  .pipe(minifyCSS())
  .pipe(gulp.dest(paths.prod + 'site/styles/'));
});

gulp.task('lint',function(){
  gulp.src(['!'+paths.src+'site/scripts/vendor/*.*',paths.src+'site/scripts/**/*.js'])
    .pipe(jshint())
  .pipe(jshint.reporter('jshint-stylish'))
  .pipe(jshint.reporter('fail'))
});

// Builds projects using require.js's optimizer + Minify files with UglifyJS
gulp.task('rjs',['copy_src','jekyll'], function(){
      return  rjs({
            mainConfigFile: paths.temp +'site/scripts/main.js',
            //optimize: 'none', //hardcoded in requirejs plugin
            baseUrl: paths.temp + 'site/scripts',
            wrap: true,
            name: 'main',
            mainFile: paths.temp+'site/index.html',
            out: 'amd-main.js'
        })
      .pipe(print(function(filepath) {
        return "rjs -> built: " + filepath;
      }))
      .pipe(gulp.src(paths.temp +'site/scripts/vendor/require.js'))
      .pipe(reverse({objectMode: true})) // requirejs should be at the begining
      .pipe(concat('amd-app.js'))
      .pipe(uglify())
      .pipe(gulp.dest(paths.prod + 'site/scripts'));
 });

gulp.task('jekyll',['copy_src','prod_cfg'], function () {
       console.log('Jekyll building ......... ');
   return gulp.src(paths.temp+'_config.yml', {read: false})
    .pipe(shell([
      'jekyll build'
    ], {
      cwd: 'target/temp',
      templateData: {
        f: function (s) {
          return s.replace(/$/, '.bak')
        }
      }
    }))
});

// Replaces references with reved names
  gulp.task ('myrev', ['copy_src','prod_cfg','css','rjs','jekyll'], function(){
    return gulp.src([paths.prod + 'site/scripts/amd-app.js', paths.prod + 'site/styles/*.css'],{base:paths.prod})
    //.pipe(wait(1500))
    .pipe(rev())
    .pipe(print(function(filepath) {
        return "rev -> built: " + filepath;
      }))
    .pipe(gulp.dest(paths.prod))
    .pipe(rev.manifest())
    .pipe(print(function(filepath) {
        return "manifest -> built: " + filepath;
      }))
    .pipe(gulp.dest(paths.prod));
  });

// Start replacing rev references
gulp.task('replace',['copy_src','prod_cfg','css','rjs','jekyll','myrev'], function(){

  var manifest = require(paths.prod+'rev-manifest.json')
  console.log('Process rev-manifest.json: \n');
  console.log(manifest);
  return gulp.src([paths.prod+'**/*.html'])
  .pipe(replaceRevRef({
    base: process.cwd()+'/target/prod',
    manifest: manifest,
    path: ''/*,
    cdnPrefix: 'http://absolute.path/cdn/'*/
  }))
  .pipe(gulp.dest(paths.prod));

});

// Removes <!-- build:js ... blocks from html for prod configeration
gulp.task('rmbuild', ['copy_src','prod_cfg','css','rjs','jekyll','myrev','replace'], function(){
  return gulp.src(paths.prod+'**/*.html')
  .pipe(useref())
  .pipe(print(function(filepath) {
        return "remove <!-- build:js ... blocks -> built: " + filepath;
      }))
  .pipe(gulp.dest(paths.prod));

});

gulp.task('copy_prod',['copy_src','duplicate_html','prod_cfg','css','rjs','jekyll','myrev','replace','rmbuild'], function(){
  gulp.src([paths.prod+'/**/*.html', // all HTML
    paths.prod+'**/amd-app-*.js', // minified JS
    paths.prod+'**/*-*.css', // minified CSS
    paths.prod+'**/*.jpg',
    paths.prod+'**/*.ico',
    paths.prod+'**/*.png',
    paths.prod+'**/*.svg',
    paths.prod+'**/*.txt',
    paths.prod+'**/modernizr.custom.*.js'] // robots.txt
    )
      .pipe(print(function(filepath) {
        if (filepath){return "copy prod -> built: " + filepath;}

      }))
  .pipe(gulp.dest(paths.dist+'prod'));
});

// Cleans gulp's folders
gulp.task('clean',function(){
  return gulp.src([paths.temp,paths.prod,paths.stage,paths.dist],{ read: false }) // much faster
    .pipe(rimraf());
})

// --------------------------- Building Stage -----------------------------
//----------------
//----------
gulp.task('stage',['copy_src','stage_cfg','css_stage','jekyll_stage','copy_stage'], function(){

})
// Copies src to temp folder
gulp.task('copy_src', ['duplicate_html'], function(){
  return gulp.src(paths.src + '**/*.*')
  .pipe(gulp.dest(paths.temp))
})

// Copies src to temp folder
gulp.task('duplicate_html', function(){
  return gulp.src(paths.src + '/site/create-account.html')
  .pipe(rename('index.html'))
  .pipe(gulp.dest(paths.temp))
})

gulp.task('stage_cfg', function(){
  return gulp.src(paths.config + buildConfig.jekyllStageConfig)
  .pipe(rename('_config.yml'))
  .pipe(gulp.dest(paths.temp))
})

gulp.task('css_stage', ['copy_src'], function() {
  return gulp.src(paths.temp+'site/styles/*.scss')
  .pipe(compass({
    //config_file: './compass-config.rb',
    css: paths.temp +'site/styles',
    sass: paths.temp +'site/styles'
  }))
  .pipe(gulp.dest(paths.stage + 'site/styles/'));
});
// Ensure waiting for Jekill job finishing
gulp.task('jekyll_stage',['copy_src','stage_cfg'], function () {
         console.log('Jekyll stage......... ');
   return gulp.src(paths.temp+'_config.yml', {read: false})
    .pipe(shell([
      'jekyll build'
    ], {
      cwd: 'target/temp',
      templateData: {
        f: function (s) {
          return s.replace(/$/, '.bak')
        }
      }
    }))
});

gulp.task('copy_stage',['copy_src','stage_cfg','css_stage','jekyll_stage'], function(){
  gulp.src([paths.stage+'/**/*.html', // all HTML
    paths.stage+'**/*.js',
    paths.stage+'**/*.css',
    paths.stage+'**/*.jpg',
    paths.prod+'**/*.ico',
    paths.stage+'**/*.png',
    paths.stage+'**/*.svg',
    paths.stage+'**/*.txt'  // robots.txt
    ])
  .pipe(gulp.dest(paths.dist+'stage'));
});

// Cleans gulp's folders
gulp.task('clean',function(){
  return gulp.src([paths.temp,paths.prod,paths.stage,paths.dist],{ read: false }) // much faster
    .pipe(rimraf());
})

// --------------------------- Building GitHub pages (localhost:8080) -----------------------------
//----------------
//----------
gulp.task('gh',['copy_src','gh_cfg','css_gh','jekyll_gh','copy_gh'], function(){
  console.log('Update localhost .....');
})

gulp.task('gh_cfg', function(){
  return gulp.src(paths.config + buildConfig.jekyllGHConfig)
  .pipe(rename('_config.yml'))
  .pipe(gulp.dest(paths.temp))
})

gulp.task('css_gh', ['copy_src'], function() {
  return gulp.src(paths.temp+'site/styles/*.scss')
  .pipe(compass({
    //config_file: './compass-config.rb',
    css: paths.temp +'site/styles',
    sass: paths.temp +'site/styles'
  }))
  .pipe(gulp.dest(paths.gh + 'site/styles/'));
});

gulp.task('jekyll_gh',['copy_src','gh_cfg'], function () {
         console.log('Jekyll ......... ');
     return require('child_process')
        .spawn('jekyll', ['build'], {stdio: 'inherit', cwd: paths.temp});

});

gulp.task('copy_gh',['copy_src','gh_cfg','css_gh','jekyll_gh'], function(){
  gulp.src([paths.gh+'/**/*.html', // all HTML
    paths.gh+'**/*.js',
    paths.gh+'**/*.css',
    paths.gh+'**/*.jpg',
    paths.gh+'**/*.png',
    paths.gh+'**/*.svg',
    paths.gh+'**/*.txt'  // robots.txt
    ])
  .pipe(gulp.dest(paths.dist+'gh'));
});

gulp.task('watch', function(){
  console.log('Watching for changes in : '+paths.src+'*.*');
return gulp.watch(''+paths.src+'**/*.*',['gh']);

});

// --------------------------- Dev config for LiveReload localhost:8080) -----------------------------
//----------------
//----------
//  Set Up LiveReload (port 35729 which LiveReload uses by default)

gulp.task('express', function() {
  var express = require('express');
  var app = express();
  app.use(require('connect-livereload')({port: 4002}));
  app.use(express.static(__dirname));
  app.listen(4000);
});

var tinylr;
gulp.task('livereload', function() {
  tinylr = require('tiny-lr')();
  tinylr.listen(4002);
});

function notifyLiveReload(event) {
  var fileName = require('path').relative(__dirname, event.path);

  tinylr.changed({
    body: {
      files: [fileName]
    }
  });
}

gulp.task('__watch', function() {
  gulp.watch(''+paths.src+'site/styles/*.scss', ['css_gh']);
  gulp.watch(''+paths.src+'site/**/*.html', ['jekyll_gh']);
  gulp.watch(''+paths.gh+'**/*.html', notifyLiveReload);
  gulp.watch(''+paths.gh+'site/styles/*.css', notifyLiveReload);
});

gulp.task('lr', ['css_gh', 'express', 'livereload', 'watch'], function() {

});

// -------------------- Utils ------------------------
<|endoftext|>


<commit_before>const http = require('http');
const path = require('path');
const bodyParser = require('body-parser');
const express = require('express');
const WebSocket = require('ws');
const shortid = require('shortid');
const debug = require('debug')('luaus');
const toString = require('vdom-to-html');
const render = require('./render');
const wrapper = require('./views/wrapper');
const broadcast = require('./broadcast');

/**
 * Main store of all game rooms
 * Is used as in-memory database
 *
 * Structure:
 * {
 *   [id]: {
 *     players: {
 *       [id]: {
 *         color: Array,
 *         type: String,
 *         score: Number,
 *         name: String
 *       }
 *     },
 *     maxScore: Number,
 *     playing: Boolean,
 *     ended: Boolean
 *   }
 * }
 * @type {Object}
 */
let games = {};

const port = process.env.PORT || 3000;

const app = express()
  .use(bodyParser.urlencoded({ extended: false }))
  .use(express.static(path.join(__dirname, 'public')))
  .get('/', renderHome)
  .post('/', createRoom)
  .get('/:gameID', renderSingleRoom)
  .get('/new-player/:gameID', renderNewPlayerForm)
  .post('/new-player/:gameID', addNewPlayerToGame)
  .get('/:gameID/:playerID', getController)
  .post('/:gameID/:playerID', postUpdateScore);

const server = http.createServer(app);
const webSocketServer = new WebSocket.Server({ server });

webSocketServer.broadcast = function broadcast(data) {
  webSocketServer.clients.forEach(sendData);

  function sendData(client) {
    if (client.readyState === WebSocket.OPEN) {
      client.send(data);
    }
  }
}

server.listen(port, function onListen() {
  console.log('Server started at port ' + port);
});

webSocketServer.on('connection', onSocketConnection);

/**
 * [GET] / handler
 * @param  {Object} req Express request object
 * @param  {Object} res Express response object
 */
function renderHome(req, res) {
  debug('[GET] / Render homepage');
  res.send(wrapper(toString(render('index', games))));
}

/**
 * [POST] / handler
 * Creates new game in store and redirects user to new gameroom
 * @param  {Object} req Express request object
 * @param  {Object} res Express response object
 */
function createRoom(req, res) {
  debug('[POST] / Create gameroom & redirect');
  const gameID = shortid.generate();
  games[gameID] = new Game();

  debug(`[WS] Send NEW_GAME ${gameID}`);
  webSocketServer.broadcast(
    JSON.stringify({
      action: 'NEW_GAME',
      gameID
    })
  );
  res.redirect(gameID);
}

/**
 * [GET] /:id handler
 * Renders game room which matches ID in param
 * @param  {Object} req Express request object
 * @param  {Object} res Express response object
 */
function renderSingleRoom(req, res) {
  // Return the user to the homepage when the room doesn't exist
  if (!games[req.params.gameID]) {
    debug(`[GET] /${req.params.gameID} Redirect. Game doens't exist`);
    return res.redirect('/');
  }

  debug(`[GET] /${req.params.gameID} Render gameroom`);
  return res.send(
    wrapper(
      toString(
        render('room', {
          gameID: req.params.gameID,
          game: games[req.params.gameID]
        })
      )
    )
  );
}

/**
 * [GET] /new-player/:id
 * renders a form which allows the user to create a new controller instance
 * @param  {Object} req Express request object
 * @param  {Object} res Express response object
 */
function renderNewPlayerForm(req, res) {
  debug(`[GET] /new-player/${req.params.gameID} Render new player form`);
  return res.send(wrapper(toString(render('newPlayer', req.params.gameID))));
}

/**
 * [POST] /new-player/:id
 * Adds new user to game with corresponding ID and redirects to buttonview
 * @param  {Object} req Express request object
 * @param  {Object} res Express response object
 */
function addNewPlayerToGame(req, res) {
  debug(`[POST] /new-player/${req.params.gameID} Add player to game`);
  const playerID = shortid.generate();
  games[req.params.gameID].players[playerID] = new Player('web', req.body.name);
  res.redirect(`/${req.params.gameID}/${playerID}`);
}

/**
 * [GET] /:gameID/:playerID
 * @param  {Object} req Express request object
 * @param  {Object} res Express response object
 */
function getController(req, res) {
  if (
    games[req.params.gameID] &&
    games[req.params.gameID].players[req.params.playerID]
  ) {
    debug(`[GET] /${req.params.gameID}/${req.params.playerID} Controller`);
    return res.send(
      wrapper(
        toString(
          render('controller', {
            name: games[req.params.gameID].players[req.params.playerID].name,
            gameID: req.params.gameID,
            playerID: req.params.playerID
          })
        )
      )
    );
  }
  debug(`[GET] /${req.params.gameID}/${req.params.playerID} Game/player doesn't exists`);
  return res.redirect('/');
}

/**
 * [POST] /:gameID/:playerID
 * @param  {Object} req Express request object
 * @param  {Object} res Express response object
 */
function postUpdateScore(req, res) {
  // If game && player exists
  if (
    games[req.params.gameID] &&
    games[req.params.gameID].players[req.params.playerID]
  ) {
    debug(`[POST] /${req.params.gameID}/${req.params.playerID} Update players score`);
    updateScore(req.params.gameID, req.params.playerID);
    return res.redirect(`/${req.params.gameID}/${req.params.playerID}`);
  }

  debug(`[POST] /${req.params.gameID}/${req.params.playerID} Game/player doesn't exists`);
  return res.redirect('/');
}

/**
 * Increase the player score by 1
 * End game if max score has been reached
 * Broadcast updatescore over socket
 * @param  {String} gameID   ID of the game in which the player resides
 * @param  {String} playerID ID of the player who scored
 */
function updateScore(gameID, playerID) {
  if (games[gameID] && games[gameID].ended === false && games[gameID].playing === true) {
    games[gameID].players[playerID].score++;

    debug(`Update score player ${playerID} to ${games[gameID].players[playerID].score}`);

    if (games[gameID].players[playerID] === games[gameID].maxScore) {
      debug(`Game ${gameID} ends`);
      endGame(gameID, playerID);
    } else {
      debug(`[WS] Send UPDATE_SCORE ${playerID}`);
      webSocketServer.broadcast(
        JSON.stringify({
          action: 'UPDATE_SCORE',
          playerID
        })
      );
    }
  } else {
    debug(`[WS] Game ${gameID} doesn't exist or has ended`);
  }
}

/**
 * End the game session
 * Broadcast end_game signal
 * @param  {String} gameID   ID of the game to end
 * @param  {String} playerID ID of the player who own
 */
function endGame(gameID, playerID) {
  games[gameID].ended = true;
  games[gameID].playing = false;

  debug(`[WS] Send END_GAME ${playerID}`);
  webSocketServer.broadcast(
    JSON.stringify({
      action: 'END_GAME',
      winner: playerID
    })
  );
}

/**
 * Main socket handler
 * Maps incoming socket messages to the corresponding functions
 */
function onSocketConnection(socket) {
  socket.on('message', onSocketMessage);

  function onSocketMessage(message) {
    try {
      message = JSON.parse(message);
    } catch (err) {
      console.log('Message not in JSON:', message);
    }

    switch (message.action) {
      case 'UPDATE_SCORE':
        debug(`[WS] Receive UPDATE_SCORE`);
        updateScore(message.gameID, message.playerID);
        break;
    }
  }
}

/**
 * Game object-creator
 * Sets defaults for new game
 */
function Game() {
  this.players = {};
  this.maxScore = 10;
  this.playing = false;
  this.ended = false;
}

/**
 * Player object-creator
 * @param {String} type nodemcu | web
 * @param {String} name
 */
function Player(type, name = 'John Doe') {
  this.color = [0, 0, 0];
  this.type = type;
  this.score = 0;
  this.name = name;
}
<commit_msg>Remove broadcast require<commit_after>const http = require('http');
const path = require('path');
const bodyParser = require('body-parser');
const express = require('express');
const WebSocket = require('ws');
const shortid = require('shortid');
const debug = require('debug')('luaus');
const toString = require('vdom-to-html');
const render = require('./render');
const wrapper = require('./views/wrapper');

/**
 * Main store of all game rooms
 * Is used as in-memory database
 *
 * Structure:
 * {
 *   [id]: {
 *     players: {
 *       [id]: {
 *         color: Array,
 *         type: String,
 *         score: Number,
 *         name: String
 *       }
 *     },
 *     maxScore: Number,
 *     playing: Boolean,
 *     ended: Boolean
 *   }
 * }
 * @type {Object}
 */
let games = {};

const port = process.env.PORT || 3000;

const app = express()
  .use(bodyParser.urlencoded({ extended: false }))
  .use(express.static(path.join(__dirname, 'public')))
  .get('/', renderHome)
  .post('/', createRoom)
  .get('/:gameID', renderSingleRoom)
  .get('/new-player/:gameID', renderNewPlayerForm)
  .post('/new-player/:gameID', addNewPlayerToGame)
  .get('/:gameID/:playerID', getController)
  .post('/:gameID/:playerID', postUpdateScore);

const server = http.createServer(app);
const webSocketServer = new WebSocket.Server({ server });

webSocketServer.broadcast = function broadcast(data) {
  webSocketServer.clients.forEach(sendData);

  function sendData(client) {
    if (client.readyState === WebSocket.OPEN) {
      client.send(data);
    }
  }
}

server.listen(port, function onListen() {
  console.log('Server started at port ' + port);
});

webSocketServer.on('connection', onSocketConnection);

/**
 * [GET] / handler
 * @param  {Object} req Express request object
 * @param  {Object} res Express response object
 */
function renderHome(req, res) {
  debug('[GET] / Render homepage');
  res.send(wrapper(toString(render('index', games))));
}

/**
 * [POST] / handler
 * Creates new game in store and redirects user to new gameroom
 * @param  {Object} req Express request object
 * @param  {Object} res Express response object
 */
function createRoom(req, res) {
  debug('[POST] / Create gameroom & redirect');
  const gameID = shortid.generate();
  games[gameID] = new Game();

  debug(`[WS] Send NEW_GAME ${gameID}`);
  webSocketServer.broadcast(
    JSON.stringify({
      action: 'NEW_GAME',
      gameID
    })
  );
  res.redirect(gameID);
}

/**
 * [GET] /:id handler
 * Renders game room which matches ID in param
 * @param  {Object} req Express request object
 * @param  {Object} res Express response object
 */
function renderSingleRoom(req, res) {
  // Return the user to the homepage when the room doesn't exist
  if (!games[req.params.gameID]) {
    debug(`[GET] /${req.params.gameID} Redirect. Game doens't exist`);
    return res.redirect('/');
  }

  debug(`[GET] /${req.params.gameID} Render gameroom`);
  return res.send(
    wrapper(
      toString(
        render('room', {
          gameID: req.params.gameID,
          game: games[req.params.gameID]
        })
      )
    )
  );
}

/**
 * [GET] /new-player/:id
 * renders a form which allows the user to create a new controller instance
 * @param  {Object} req Express request object
 * @param  {Object} res Express response object
 */
function renderNewPlayerForm(req, res) {
  debug(`[GET] /new-player/${req.params.gameID} Render new player form`);
  return res.send(wrapper(toString(render('newPlayer', req.params.gameID))));
}

/**
 * [POST] /new-player/:id
 * Adds new user to game with corresponding ID and redirects to buttonview
 * @param  {Object} req Express request object
 * @param  {Object} res Express response object
 */
function addNewPlayerToGame(req, res) {
  debug(`[POST] /new-player/${req.params.gameID} Add player to game`);
  const playerID = shortid.generate();
  games[req.params.gameID].players[playerID] = new Player('web', req.body.name);
  res.redirect(`/${req.params.gameID}/${playerID}`);
}

/**
 * [GET] /:gameID/:playerID
 * @param  {Object} req Express request object
 * @param  {Object} res Express response object
 */
function getController(req, res) {
  if (
    games[req.params.gameID] &&
    games[req.params.gameID].players[req.params.playerID]
  ) {
    debug(`[GET] /${req.params.gameID}/${req.params.playerID} Controller`);
    return res.send(
      wrapper(
        toString(
          render('controller', {
            name: games[req.params.gameID].players[req.params.playerID].name,
            gameID: req.params.gameID,
            playerID: req.params.playerID
          })
        )
      )
    );
  }
  debug(`[GET] /${req.params.gameID}/${req.params.playerID} Game/player doesn't exists`);
  return res.redirect('/');
}

/**
 * [POST] /:gameID/:playerID
 * @param  {Object} req Express request object
 * @param  {Object} res Express response object
 */
function postUpdateScore(req, res) {
  // If game && player exists
  if (
    games[req.params.gameID] &&
    games[req.params.gameID].players[req.params.playerID]
  ) {
    debug(`[POST] /${req.params.gameID}/${req.params.playerID} Update players score`);
    updateScore(req.params.gameID, req.params.playerID);
    return res.redirect(`/${req.params.gameID}/${req.params.playerID}`);
  }

  debug(`[POST] /${req.params.gameID}/${req.params.playerID} Game/player doesn't exists`);
  return res.redirect('/');
}

/**
 * Increase the player score by 1
 * End game if max score has been reached
 * Broadcast updatescore over socket
 * @param  {String} gameID   ID of the game in which the player resides
 * @param  {String} playerID ID of the player who scored
 */
function updateScore(gameID, playerID) {
  if (games[gameID] && games[gameID].ended === false && games[gameID].playing === true) {
    games[gameID].players[playerID].score++;

    debug(`Update score player ${playerID} to ${games[gameID].players[playerID].score}`);

    if (games[gameID].players[playerID] === games[gameID].maxScore) {
      debug(`Game ${gameID} ends`);
      endGame(gameID, playerID);
    } else {
      debug(`[WS] Send UPDATE_SCORE ${playerID}`);
      webSocketServer.broadcast(
        JSON.stringify({
          action: 'UPDATE_SCORE',
          playerID
        })
      );
    }
  } else {
    debug(`[WS] Game ${gameID} doesn't exist or has ended`);
  }
}

/**
 * End the game session
 * Broadcast end_game signal
 * @param  {String} gameID   ID of the game to end
 * @param  {String} playerID ID of the player who own
 */
function endGame(gameID, playerID) {
  games[gameID].ended = true;
  games[gameID].playing = false;

  debug(`[WS] Send END_GAME ${playerID}`);
  webSocketServer.broadcast(
    JSON.stringify({
      action: 'END_GAME',
      winner: playerID
    })
  );
}

/**
 * Main socket handler
 * Maps incoming socket messages to the corresponding functions
 */
function onSocketConnection(socket) {
  socket.on('message', onSocketMessage);

  function onSocketMessage(message) {
    try {
      message = JSON.parse(message);
    } catch (err) {
      console.log('Message not in JSON:', message);
    }

    switch (message.action) {
      case 'UPDATE_SCORE':
        debug(`[WS] Receive UPDATE_SCORE`);
        updateScore(message.gameID, message.playerID);
        break;
    }
  }
}

/**
 * Game object-creator
 * Sets defaults for new game
 */
function Game() {
  this.players = {};
  this.maxScore = 10;
  this.playing = false;
  this.ended = false;
}

/**
 * Player object-creator
 * @param {String} type nodemcu | web
 * @param {String} name
 */
function Player(type, name = 'John Doe') {
  this.color = [0, 0, 0];
  this.type = type;
  this.score = 0;
  this.name = name;
}
<|endoftext|>


<commit_before>var gulp = require('gulp'),
  autoprefixer = require('gulp-autoprefixer'),
  concat = require('gulp-concat'),
  cssmin = require('gulp-cssmin'),
  del = require('del'),
  eslint = require('gulp-eslint'),
  eventStream = require('event-stream'),
  inject = require('gulp-inject'),
  less = require('gulp-less'),
  plumber = require('gulp-plumber'),
  rename = require('gulp-rename'),
  replace = require('gulp-replace'),
  templateCache = require('gulp-angular-templatecache'),
  uglify = require('gulp-uglify'),
  util = require('gulp-util'),
  watch = require('gulp-watch'),
  webserver = require('gulp-webserver'),
  paths = require('./gulp.config.json');

/*******************************************[MAIN TASKS]******************************************/

/**
 * Build optimized app
 */
gulp.task('build', ['clean'], function () {
  return gulp.start('create-app');
});

/**
 * Serve dev environment with JS and less watchers
 */
gulp.task('serve', ['watch'], function () {
  gulp.src(paths.app)
    .pipe(webserver({
      open: true
    }));
});

/**
 * Print description
 */
gulp.task('default', function () {
  util.log();
  util.log(util.colors.bold.green('Available commands:'));
  util.log('-', util.colors.green('gulp build'), '- build optimized app, it creates dist directory with minified scripts and styles');
  util.log('-', util.colors.green('gulp serve'), '- serve dev environment with JS and less watchers');
  util.log();
});

/******************************************[HELPER TASKS]*****************************************/

var glyphiconsRegex = /\.\.\/fonts\/glyphicons-([a-z-]+)\.([a-z]{2,5})/g,
  fontAwesomeRegex = /\.\.\/fonts\/fontawesome-([a-z-]+)\.([a-z]{2,5})/g;

/**
 * Remove dist directory
 */
gulp.task('clean', function () {
  return del(paths.dist);
});

/**
 * Create optimized app
 */
gulp.task('create-app', ['jsmin', 'cssmin', 'copy-fonts', 'copy-images'], function () {
  var jsSrc = gulp.src(paths.dist + paths.jsMinified, {
    read: false
  });

  var cssSrc = gulp.src(paths.dist + paths.cssMinified, {
    read: false
  });

  return gulp.src(paths.app + 'index.html')
    .pipe(inject(jsSrc, {
      ignorePath: paths.dist.substring(1),
      addRootSlash: false
    }))
    .pipe(inject(cssSrc, {
      ignorePath: paths.dist.substring(1),
      addRootSlash: false
    }))
    .pipe(gulp.dest(paths.dist));
});

/**
 * Minify and bundle JS files
 */
gulp.task('jsmin', function () {
  var bowerComponents = gulp.src(paths.vendorJs),
    sources = gulp.src(paths.js),
    templates = gulp.src(paths.html)
      .pipe(templateCache('templates.js', {
        module: 'app',
        root: './'
      }))
      .pipe(replace('./assets/images/', './images/'));

  return eventStream.merge(bowerComponents, sources, templates)
    .pipe(concat(paths.jsMinified))
    .pipe(uglify())
    .pipe(gulp.dest(paths.dist));
});

/**
 * Minify and bundle less files
 */
gulp.task('cssmin', function () {
  return gulp.src(paths.appLess)
    .pipe(less())
    .pipe(replace(glyphiconsRegex, './fonts/glyphicons-$1.$2'))
    .pipe(replace(fontAwesomeRegex, './fonts/fontawesome-$1.$2'))
    .pipe(replace('../assets/images/', './images/'))
    .pipe(autoprefixer())
    .pipe(cssmin())
    .pipe(rename(paths.cssMinified))
    .pipe(gulp.dest(paths.dist));
});

/**
 * Copy fonts to dist directory
 */
gulp.task('copy-fonts', function () {
  return gulp.src(paths.fonts)
    .pipe(gulp.dest(paths.dist + 'fonts/'));
});

/**
 * Copy images to dist directory
 */
gulp.task('copy-images', function () {
  return gulp.src(paths.images)
    .pipe(gulp.dest(paths.dist + 'images/'));
});

/**
 * Watch JS and less file
 */
gulp.task('watch', ['lint', 'css'], function () {
  watch(paths.js, function () {
    gulp.start('lint')
  });

  watch(paths.less, function () {
    gulp.start('css')
  });
});

/**
 * Lint JS files using ESlint
 */
gulp.task('lint', function () {
  return gulp.src(paths.js)
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.results(function (results) {
      if (results.errorCount === 0 && results.warningCount === 0) {
        util.log(util.colors.bold.green('ESlint test has been passed'));
      }
    }));
});

/**
 * Compile less into css for dev server
 */
gulp.task('css', function () {
  return gulp.src(paths.appLess)
    .pipe(plumber({
      errorHandler: function (error) {
        util.log(util.colors.red(error.message));
        this.emit('end');
      }
    }))
    .pipe(less())
    .pipe(replace(glyphiconsRegex, './bower_components/bootstrap/fonts/glyphicons-$1.$2'))
    .pipe(replace(fontAwesomeRegex, './bower_components/font-awesome/fonts/fontawesome-$1.$2'))
    .pipe(autoprefixer())
    .pipe(gulp.dest(paths.app + 'pages/'));
});
<commit_msg>fix fonts url<commit_after>var gulp = require('gulp'),
  autoprefixer = require('gulp-autoprefixer'),
  concat = require('gulp-concat'),
  cssmin = require('gulp-cssmin'),
  del = require('del'),
  eslint = require('gulp-eslint'),
  eventStream = require('event-stream'),
  inject = require('gulp-inject'),
  less = require('gulp-less'),
  plumber = require('gulp-plumber'),
  rename = require('gulp-rename'),
  replace = require('gulp-replace'),
  templateCache = require('gulp-angular-templatecache'),
  uglify = require('gulp-uglify'),
  util = require('gulp-util'),
  watch = require('gulp-watch'),
  webserver = require('gulp-webserver'),
  paths = require('./gulp.config.json');

/*******************************************[MAIN TASKS]******************************************/

/**
 * Build optimized app
 */
gulp.task('build', ['clean'], function () {
  return gulp.start('create-app');
});

/**
 * Serve dev environment with JS and less watchers
 */
gulp.task('serve', ['watch'], function () {
  gulp.src(paths.app)
    .pipe(webserver({
      open: true
    }));
});

/**
 * Print description
 */
gulp.task('default', function () {
  util.log();
  util.log(util.colors.bold.green('Available commands:'));
  util.log('-', util.colors.green('gulp build'), '- build optimized app, it creates dist directory with minified scripts and styles');
  util.log('-', util.colors.green('gulp serve'), '- serve dev environment with JS and less watchers');
  util.log();
});

/******************************************[HELPER TASKS]*****************************************/

var glyphiconsRegex = /\.\.\/fonts\/glyphicons-([a-z-]+)\.([a-z]{2,5})/g,
  fontAwesomeRegex = /\.\.\/fonts\/fontawesome-([a-z-]+)\.([a-z]{2,5})/g;

/**
 * Remove dist directory
 */
gulp.task('clean', function () {
  return del(paths.dist);
});

/**
 * Create optimized app
 */
gulp.task('create-app', ['jsmin', 'cssmin', 'copy-fonts', 'copy-images'], function () {
  var jsSrc = gulp.src(paths.dist + paths.jsMinified, {
    read: false
  });

  var cssSrc = gulp.src(paths.dist + paths.cssMinified, {
    read: false
  });

  return gulp.src(paths.app + 'index.html')
    .pipe(inject(jsSrc, {
      ignorePath: paths.dist.substring(1),
      addRootSlash: false
    }))
    .pipe(inject(cssSrc, {
      ignorePath: paths.dist.substring(1),
      addRootSlash: false
    }))
    .pipe(gulp.dest(paths.dist));
});

/**
 * Minify and bundle JS files
 */
gulp.task('jsmin', function () {
  var bowerComponents = gulp.src(paths.vendorJs),
    sources = gulp.src(paths.js),
    templates = gulp.src(paths.html)
      .pipe(templateCache('templates.js', {
        module: 'app',
        root: './'
      }))
      .pipe(replace('./assets/images/', './images/'));

  return eventStream.merge(bowerComponents, sources, templates)
    .pipe(concat(paths.jsMinified))
    .pipe(uglify())
    .pipe(gulp.dest(paths.dist));
});

/**
 * Minify and bundle less files
 */
gulp.task('cssmin', function () {
  return gulp.src(paths.appLess)
    .pipe(less())
    .pipe(replace(glyphiconsRegex, './fonts/glyphicons-$1.$2'))
    .pipe(replace(fontAwesomeRegex, './fonts/fontawesome-$1.$2'))
    .pipe(replace('../assets/images/', './images/'))
    .pipe(autoprefixer())
    .pipe(cssmin())
    .pipe(rename(paths.cssMinified))
    .pipe(gulp.dest(paths.dist));
});

/**
 * Copy fonts to dist directory
 */
gulp.task('copy-fonts', function () {
  return gulp.src(paths.fonts)
    .pipe(gulp.dest(paths.dist + 'fonts/'));
});

/**
 * Copy images to dist directory
 */
gulp.task('copy-images', function () {
  return gulp.src(paths.images)
    .pipe(gulp.dest(paths.dist + 'images/'));
});

/**
 * Watch JS and less file
 */
gulp.task('watch', ['lint', 'css'], function () {
  watch(paths.js, function () {
    gulp.start('lint')
  });

  watch(paths.less, function () {
    gulp.start('css')
  });
});

/**
 * Lint JS files using ESlint
 */
gulp.task('lint', function () {
  return gulp.src(paths.js)
    .pipe(eslint())
    .pipe(eslint.format())
    .pipe(eslint.results(function (results) {
      if (results.errorCount === 0 && results.warningCount === 0) {
        util.log(util.colors.bold.green('ESlint test has been passed'));
      }
    }));
});

/**
 * Compile less into css for dev server
 */
gulp.task('css', function () {
  return gulp.src(paths.appLess)
    .pipe(plumber({
      errorHandler: function (error) {
        util.log(util.colors.red(error.message));
        this.emit('end');
      }
    }))
    .pipe(less())
    .pipe(replace(glyphiconsRegex, '../bower_components/bootstrap/fonts/glyphicons-$1.$2'))
    .pipe(replace(fontAwesomeRegex, '../bower_components/font-awesome/fonts/fontawesome-$1.$2'))
    .pipe(autoprefixer())
    .pipe(gulp.dest(paths.app + 'pages/'));
});
<|endoftext|>


<commit_before>$(function () {
    $('#map').gmap3(
        { action:'init',
            options:{
                center:[-12.047816, -77.062203],
                zoom:12,
		mapTypeId:google.maps.MapTypeId.ROADMAP,
		mapTypeControl: false,
		navigationControl: false,
		streetViewControl: false
            }
        },
	{ action: 'addMarkers',
	  markers:[ points ]
	}
    );

    $('#filter_distrito').change(function(){
	var sel = $("#filter_distrito option:selected").text();
	updateParams(sel.toLowerCase());
    });

    function updateParams(val){
	var address_lima = val + ", Lima, Peru";
	$('#map').gmap3(
	    {
		action:'getLatLng',
		address: address_lima,
		callback: function(result){
		    if(result){
			$(this).gmap3({
			    action: 'setCenter',
			    zoom: 17,
			    args: [ result[0].geometry.location ]
			});
		    } else {
			alert('foo');
		    }
		}
	    }
	);

    }

});

<commit_msg>Mapa de nuevo online.<commit_after>var points;

$(function () {
    $('#map').gmap3(
        { action:'init',
            options:{
                center:[-12.047816, -77.062203],
                zoom:12,
		mapTypeId:google.maps.MapTypeId.ROADMAP,
		mapTypeControl: false,
		navigationControl: false,
		streetViewControl: false
            }
        },
	{ action: 'addMarkers',
	  markers:[ points ]
	}
    );

    $('#filter_distrito').change(function(){
	var sel = $("#filter_distrito option:selected").text();
	updateParams(sel.toLowerCase());
    });

    function updateParams(val){
	var address_lima = val + ", Lima, Peru";
	$('#map').gmap3(
	    {
		action:'getLatLng',
		address: address_lima,
		callback: function(result){
		    if(result){
			$(this).gmap3({
			    action: 'setCenter',
			    zoom: 17,
			    args: [ result[0].geometry.location ]
			});
		    } else {
			alert('foo');
		    }
		}
	    }
	);

    }

});

<|endoftext|>


<commit_before>exports = module.exports = function(container, store, logger) {
  var oauth2orize = require('oauth2orize');

  var server = oauth2orize.createServer({
    store: store
  });

  var paramDecls = container.components('http://schemas.authnomicon.org/js/aaa/oauth2/request/parameters')
    , grantDecls = container.components('http://schemas.authnomicon.org/js/aaa/oauth2/grant')
    , exchangeDecls = container.components('http://schemas.authnomicon.org/js/aaa/oauth2/exchange')

  return Promise.all(paramDecls.map(function(spec) { return container.create(spec.id); } ))
    .then(function(plugins) {
      // Register request parameter extensions with the OAuth 2.0 server.
      plugins.forEach(function(plugin, i) {
        server.grant(plugin);
        logger.info('Loaded OAuth 2.0 request parameters: ' + paramDecls[i].a['@name']);
      });
    })
    .then(function() {
      return Promise.all(grantDecls.map(function(spec) { return container.create(spec.id); } ));
    })
    .then(function(plugins) {
      // Register response types with the OAuth 2.0 server.
      plugins.forEach(function(plugin, i) {
        server.grant(grantDecls[i].a['@type'] || plugin.name, plugin);
        logger.info('Loaded OAuth 2.0 response type: ' + (grantDecls[i].a['@type'] || plugin.name));
      });
    })
    .then(function() {
      return Promise.all(exchangeDecls.map(function(spec) { return container.create(spec.id); } ));
    })
    .then(function(plugins) {
      // Register grant types with the OAuth 2.0 server.
      plugins.forEach(function(plugin, i) {
        server.exchange(exchangeDecls[i].a['@type'] || plugin.name, plugin);
        logger.info('Loaded OAuth 2.0 grant type: ' + (exchangeDecls[i].a['@type'] || plugin.name));
      });
    })
    .then(function() {
      return server;
    });
}

exports['@implements'] = 'http://schemas.authnomicon.org/js/aaa/oauth2/Server';
exports['@singleton'] = true;
exports['@require'] = [
  '!container',
  'http://schemas.authnomicon.org/js/aaa/oauth2/TransactionStore',
  'http://i.bixbyjs.org/Logger'
];
<commit_msg>Clarify plugin loading in server.<commit_after>exports = module.exports = function(container, store, logger) {
  var oauth2orize = require('oauth2orize');

  var server = oauth2orize.createServer({
    store: store
  });

  return Promise.resolve(server)
    .then(function(server) {
      // Register request parameter extensions with the OAuth 2.0 server.
      var paramDecls = container.components('http://schemas.authnomicon.org/js/aaa/oauth2/request/parameters');

      return Promise.all(paramDecls.map(function(spec) { return container.create(spec.id); } ))
        .then(function(plugins) {
          plugins.forEach(function(plugin, i) {
            server.grant(plugin);
            logger.info('Loaded OAuth 2.0 request parameters: ' + paramDecls[i].a['@name']);
          });
        })
        .then(function() {
          return server;
        });
    })
    .then(function(server) {
      // Register response types with the OAuth 2.0 server.
      var grantDecls = container.components('http://schemas.authnomicon.org/js/aaa/oauth2/grant')

      return Promise.all(grantDecls.map(function(spec) { return container.create(spec.id); } ))
        .then(function(plugins) {
          plugins.forEach(function(plugin, i) {
            server.grant(grantDecls[i].a['@type'] || plugin.name, plugin);
            logger.info('Loaded OAuth 2.0 response type: ' + (grantDecls[i].a['@type'] || plugin.name));
          });
        })
        .then(function() {
          return server;
        });
    })
    .then(function(server) {
      // Register grant types with the OAuth 2.0 server.
      var exchangeDecls = container.components('http://schemas.authnomicon.org/js/aaa/oauth2/exchange')

      return Promise.all(exchangeDecls.map(function(spec) { return container.create(spec.id); } ))
        .then(function(plugins) {
          plugins.forEach(function(plugin, i) {
            server.exchange(exchangeDecls[i].a['@type'] || plugin.name, plugin);
            logger.info('Loaded OAuth 2.0 grant type: ' + (exchangeDecls[i].a['@type'] || plugin.name));
          });
        })
        .then(function() {
          return server;
        });
    })
    .then(function(server) {
      return server;
    });
}

exports['@implements'] = 'http://schemas.authnomicon.org/js/aaa/oauth2/Server';
exports['@singleton'] = true;
exports['@require'] = [
  '!container',
  'http://schemas.authnomicon.org/js/aaa/oauth2/TransactionStore',
  'http://i.bixbyjs.org/Logger'
];
<|endoftext|>