<commit_before>(function() {
    function getButton(product) {
        // Look up button by its manifest URL.
        return $(format('.button[data-manifestUrl="{0}"]', product.manifestUrl));
    }

    function setButton($button, text, cls) {
        if (cls == 'purchasing' || cls == 'installing') {
            // Save the old text of the button if we know we may revert later.
            $button.data('old-text', $button.html());
        }
        $button.html(text);
        if (!(cls == 'purchasing' || cls == 'installing')) {
            $button.removeClass('purchasing installing');
        }
        $button.addClass(cls);
    }

    function revertButton($button) {
        // Cancelled install/purchase. Roll back button to its previous state.
        $button.removeClass('purchasing installing error');
        if ($button.data('old-text')) {
            $button.html($button.data('old-text'));
        }
    }

    $(window).bind('app_purchase_start', function(e, product) {
        setButton(getButton(product), gettext('Purchasing…'), 'purchasing');
    }).bind('app_purchase_success', function(e, product) {
        var $button = getButton(product),
            purchasedMark = '';
        purchasedMark += gettext('Purchased') + '';
        product['isPurchased'] = true;
        $button.data('product', product).after(purchasedMark);
        setButton($button, gettext('Purchased'), 'purchased');
    }).bind('app_install_start', function(e, product) {
        setButton(getButton(product),
                  gettext('Installing…'), 'installing');
    }).bind('app_install_success', function(e, product) {
        setButton(getButton(product), gettext('Installed'), 'installed');
    }).bind('app_purchase_error app_install_error', function(e, product, msg) {
        var $button = getButton(product),
            errSummary;

        // From the old apps.js
        switch (msg) {
            case 'DENIED':
                errSummary = gettext('App installation not allowed.');
                break;
            case 'MANIFEST_URL_ERROR':
                errSummary = gettext('App manifest is malformed.');
                break;
            case 'NETWORK_ERROR':
                errSummary = gettext('App host could not be reached.');
                break;
            case 'MANIFEST_PARSE_ERROR':
                errSummary = gettext('App manifest is unparsable.');
                break;
            case 'INVALID_MANIFEST':
                errSummary = gettext('App manifest is invalid.');
                break;
            default:
                errSummary = gettext('Unknown error.');
                break;
        }

        if (msg) {
            setButton($button, gettext('Error'), 'error');
            var $overlay = $('

');
            $overlay.append('

' + gettext('Error') + '

' +
                            errSummary + '

');
            $('#install-error').remove();
            $('body').append($overlay);
            $overlay.addClass('show');
        } else {
            // Cancelled install. Roll back.
            revertButton($button);
        }
    }).bind('buttons.overlay_dismissed', function() {
        // Dismissed error. Roll back.
        revertButton($('.button.error'));
    }).bind('app_install_disabled', function(e, product) {
        // You're not using a compatible browser.
        var $button = $('.button.product');
        setButton($button, $button.html(), 'disabled');
        $button.parent().append($('#noApps').html());
    });
})();
<commit_msg>only show one button badge at a time (bug 752680)<commit_after>(function() {
    function getButton(product) {
        // Look up button by its manifest URL.
        return $(format('.button[data-manifestUrl="{0}"]', product.manifestUrl));
    }

    function setButton($button, text, cls) {
        if (cls == 'purchasing' || cls == 'installing') {
            // Save the old text of the button if we know we may revert later.
            $button.data('old-text', $button.html());
        }
        $button.html(text);
        if (!(cls == 'purchasing' || cls == 'installing')) {
            $button.removeClass('purchasing installing');
        }
        $button.addClass(cls);
    }

    function revertButton($button) {
        // Cancelled install/purchase. Roll back button to its previous state.
        $button.removeClass('purchasing installing error');
        if ($button.data('old-text')) {
            $button.html($button.data('old-text'));
        }
    }

    $(window).bind('app_purchase_start', function(e, product) {
        setButton(getButton(product), gettext('Purchasing…'), 'purchasing');
    }).bind('app_purchase_success', function(e, product) {
        var $button = getButton(product),
            purchasedMark = '';
        purchasedMark += gettext('Purchased') + '';
        product['isPurchased'] = true;

        // Let's show only one button "badge" at a time.
        if ($button.siblings('.checkmark').length === 0) {
            $button.data('product', product).after(purchasedMark);
        }
        setButton($button, gettext('Purchased'), 'purchased');
    }).bind('app_install_start', function(e, product) {
        setButton(getButton(product),
                  gettext('Installing…'), 'installing');
    }).bind('app_install_success', function(e, product) {
        setButton(getButton(product), gettext('Installed'), 'installed');
    }).bind('app_purchase_error app_install_error', function(e, product, msg) {
        var $button = getButton(product),
            errSummary;

        // From the old apps.js
        switch (msg) {
            case 'DENIED':
                errSummary = gettext('App installation not allowed.');
                break;
            case 'MANIFEST_URL_ERROR':
                errSummary = gettext('App manifest is malformed.');
                break;
            case 'NETWORK_ERROR':
                errSummary = gettext('App host could not be reached.');
                break;
            case 'MANIFEST_PARSE_ERROR':
                errSummary = gettext('App manifest is unparsable.');
                break;
            case 'INVALID_MANIFEST':
                errSummary = gettext('App manifest is invalid.');
                break;
            default:
                errSummary = gettext('Unknown error.');
                break;
        }

        if (msg) {
            setButton($button, gettext('Error'), 'error');
            var $overlay = $('

');
            $overlay.append('

' + gettext('Error') + '

' +
                            errSummary + '

');
            $('#install-error').remove();
            $('body').append($overlay);
            $overlay.addClass('show');
        } else {
            // Cancelled install. Roll back.
            revertButton($button);
        }
    }).bind('buttons.overlay_dismissed', function() {
        // Dismissed error. Roll back.
        revertButton($('.button.error'));
    }).bind('app_install_disabled', function(e, product) {
        // You're not using a compatible browser.
        var $button = $('.button.product');
        setButton($button, $button.html(), 'disabled');
        $button.parent().append($('#noApps').html());
    });
})();
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    sass = require('gulp-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    minifycss = require('gulp-minify-css'),
    jshint = require('gulp-jshint'),
    uglify = require('gulp-uglify'),
    ts = require("gulp-typescript"),
    imagemin = require('gulp-imagemin'),
    rename = require('gulp-rename'),
    concat = require('gulp-concat'),
    notify = require('gulp-notify'),
    cache = require('gulp-cache'),
    gzip = require('gulp-gzip');
    //livereload = require('gulp-livereload'),
    del = require('del'),
    gutil = require('gulp-util'),
    babel = require('gulp-babel');

var gulp = require("gulp");
var browserify = require("browserify");
var source = require('vinyl-source-stream');
var tsify = require("tsify");
var uglify = require('gulp-uglify');
const notifier = require('node-notifier');

function handleError(err) {
  console.log(err.toString());
  notifier.notify({
  'title': 'Gulp worflow',
  'message': 'Typescript error'
  });
  this.emit('end');
}

gulp.task("scriptsHome", function () {
    return browserify({
        basedir: '.',
        debug: true,
        entries: ['src/Biopen/CoreBundle/Resources/js/home.ts'],
        cache: {},
        packageCache: {}
    })
    .plugin(tsify)
    .transform('babelify', {
        presets: ['es2015'],
        extensions: ['.ts']
    })
    .bundle()
    .on('error', handleError)
    .pipe(source('home.js'))
    .pipe(gulp.dest("web/js"));
});

gulp.task("scriptsDirectory", function () {
    return browserify({
        basedir: '.',
        debug: true,
        entries: ['src/Biopen/GeoDirectoryBundle/Resources/js/directory/app.module.ts'],
        cache: {},
        packageCache: {}
    })
    .plugin(tsify)
    .transform('babelify', {
        presets: ['es2015'],
        extensions: ['.ts']
    })
    .bundle()
    .on('error', handleError)
    .pipe(source('directory.js'))
    .pipe(gulp.dest("web/js"));
});

gulp.task('scriptsElementForm', function() {
  return gulp.src(['src/Biopen/GeoDirectoryBundle/Resources/js/element-form/**/*.js'])
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(jshint.reporter('fail'))
    .on('error', notify.onError({ message: 'JS hint fail'}))
    .pipe(concat('element-form.js'))
    //.pipe(livereload())
    .pipe(gulp.dest('web/js'));
});

gulp.task('scriptsLibs', function() {
  return gulp.src(['src/Biopen/GeoDirectoryBundle/Resources/js/libs/**/*.js', '!src/Biopen/GeoDirectoryBundle/Resources/js/libs/materialize/unused/**/*.js'])
    .pipe(concat('libs.js'))
    // .pipe(rename({suffix: '.min'}))
    // .pipe(uglify())
    .pipe(gulp.dest('web/js'));
    //.pipe(livereload());
    //.pipe(notify({ message: 'Scripts Libs task complete' }));
});

gulp.task('sass', function () {
  return gulp.src(['src/Biopen/GeoDirectoryBundle/Resources/scss/**/*.scss',
                  'src/Biopen/CoreBundle/Resources/scss/**/*.scss'])
    .pipe(sass()
    .on('error', sass.logError))
    .pipe(gulp.dest('web/assets/css'));
});

gulp.task('prod_styles', function() {
  return gulp.src('web/assets/css/**/*.css')
    //.pipe(rename({suffix: '.min'}))
    .pipe(minifycss())
    .pipe(gzip())
    .pipe(gulp.dest('web/assets/css'));
    //.pipe(notify({ message: 'Styles task complete' }));
});

gulp.task('prod_js', function() {
  return gulp.src(['web/js/*.js'])
    //.pipe(rename({suffix: '.min'}))
    .pipe(uglify())
    .pipe(gzip())
    //.pipe(minify())
    //.pipe(sourcemaps.init({loadMaps: true}))
    //.pipe(uglify().on('error', gulpUtil.log)) // notice the error event here
    //.pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('web/js'));
});

gulp.task('images', function() {
  return gulp.src('web/assets/img/*')
    .pipe(cache(imagemin({ optimizationLevel: 5, progressive: true, interlaced: true })))
    .pipe(gulp.dest('web/assets/imgMin'))
    .pipe(notify({ message: 'Images task complete' }));
});

gulp.task('watch', function() {

  //livereload.listen();
  // Watch .scss files
  gulp.watch(['src/Biopen/GeoDirectoryBundle/Resources/scss/**/*.scss',
              'src/Biopen/CoreBundle/Resources/scss/**/*.scss'],
              ['sass']);

  // Watch .js files
  gulp.watch(['src/Biopen/GeoDirectoryBundle/Resources/js/directory/**/*.ts',
              'src/Biopen/GeoDirectoryBundle/Resources/js/commons/**/*.ts'],
              ['scriptsDirectory']);

  gulp.watch(['src/Biopen/GeoDirectoryBundle/Resources/js/element-form/**/*.js'],
              ['scriptsElementForm']);

  gulp.watch('src/Biopen/GeoDirectoryBundle/Resources/js/libs/**/*.js', ['scriptsLibs']);

  gulp.watch(['src/Biopen/CoreBundle/Resources/js/**/*.ts'], ['scriptsHome']);
  // Watch image files
  //gulp.watch('src/img/*', ['images']);

});

gulp.task('clean', function(cb) {
    del(['web/assets/css', 'web/js'], cb);
});

gulp.task('build', function() {
    gulp.start('clean','sass', 'scriptsLibs', 'scriptsHome', 'scriptsElementForm','scriptsDirectory');
});

gulp.task('production', function() {
    gulp.start('build','prod_styles', 'prod_js');
});

<commit_msg>Change production task<commit_after>var gulp = require('gulp'),
    sass = require('gulp-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    minifycss = require('gulp-minify-css'),
    jshint = require('gulp-jshint'),
    uglify = require('gulp-uglify'),
    ts = require("gulp-typescript"),
    imagemin = require('gulp-imagemin'),
    rename = require('gulp-rename'),
    concat = require('gulp-concat'),
    notify = require('gulp-notify'),
    cache = require('gulp-cache'),
    gzip = require('gulp-gzip');
    //livereload = require('gulp-livereload'),
    del = require('del'),
    gutil = require('gulp-util'),
    babel = require('gulp-babel');

var gulp = require("gulp");
var browserify = require("browserify");
var source = require('vinyl-source-stream');
var tsify = require("tsify");
var uglify = require('gulp-uglify');
const notifier = require('node-notifier');

function handleError(err) {
  console.log(err.toString());
  notifier.notify({
  'title': 'Gulp worflow',
  'message': 'Typescript error'
  });
  this.emit('end');
}

gulp.task("scriptsHome", function () {
    return browserify({
        basedir: '.',
        debug: true,
        entries: ['src/Biopen/CoreBundle/Resources/js/home.ts'],
        cache: {},
        packageCache: {}
    })
    .plugin(tsify)
    .transform('babelify', {
        presets: ['es2015'],
        extensions: ['.ts']
    })
    .bundle()
    .on('error', handleError)
    .pipe(source('home.js'))
    .pipe(gulp.dest("web/js"));
});

gulp.task("scriptsDirectory", function () {
    return browserify({
        basedir: '.',
        debug: true,
        entries: ['src/Biopen/GeoDirectoryBundle/Resources/js/directory/app.module.ts'],
        cache: {},
        packageCache: {}
    })
    .plugin(tsify)
    .transform('babelify', {
        presets: ['es2015'],
        extensions: ['.ts']
    })
    .bundle()
    .on('error', handleError)
    .pipe(source('directory.js'))
    .pipe(gulp.dest("web/js"));
});

gulp.task('scriptsElementForm', function() {
  return gulp.src(['src/Biopen/GeoDirectoryBundle/Resources/js/element-form/**/*.js'])
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(jshint.reporter('fail'))
    .on('error', notify.onError({ message: 'JS hint fail'}))
    .pipe(concat('element-form.js'))
    //.pipe(livereload())
    .pipe(gulp.dest('web/js'));
});

gulp.task('scriptsLibs', function() {
  return gulp.src(['src/Biopen/GeoDirectoryBundle/Resources/js/libs/**/*.js', '!src/Biopen/GeoDirectoryBundle/Resources/js/libs/materialize/unused/**/*.js'])
    .pipe(concat('libs.js'))
    // .pipe(rename({suffix: '.min'}))
    // .pipe(uglify())
    .pipe(gulp.dest('web/js'));
    //.pipe(livereload());
    //.pipe(notify({ message: 'Scripts Libs task complete' }));
});

gulp.task('sass', function () {
  return gulp.src(['src/Biopen/GeoDirectoryBundle/Resources/scss/**/*.scss',
                  'src/Biopen/CoreBundle/Resources/scss/**/*.scss'])
    .pipe(sass()
    .on('error', sass.logError))
    .pipe(gulp.dest('web/assets/css'));
});

gulp.task('prod_styles', function() {
  return gulp.src('web/assets/css/**/*.css')
    //.pipe(rename({suffix: '.min'}))
    .pipe(minifycss())
    .pipe(gzip())
    .pipe(gulp.dest('web/assets/css'));
    //.pipe(notify({ message: 'Styles task complete' }));
});

gulp.task('prod_js', function() {
  return gulp.src(['web/js/*.js'])
    //.pipe(rename({suffix: '.min'}))
    .pipe(uglify())
    .pipe(gzip())
    //.pipe(minify())
    //.pipe(sourcemaps.init({loadMaps: true}))
    //.pipe(uglify().on('error', gulpUtil.log)) // notice the error event here
    //.pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('web/js'));
});

gulp.task('images', function() {
  return gulp.src('web/assets/img/*')
    .pipe(cache(imagemin({ optimizationLevel: 5, progressive: true, interlaced: true })))
    .pipe(gulp.dest('web/assets/imgMin'))
    .pipe(notify({ message: 'Images task complete' }));
});

gulp.task('watch', function() {

  //livereload.listen();
  // Watch .scss files
  gulp.watch(['src/Biopen/GeoDirectoryBundle/Resources/scss/**/*.scss',
              'src/Biopen/CoreBundle/Resources/scss/**/*.scss'],
              ['sass']);

  // Watch .js files
  gulp.watch(['src/Biopen/GeoDirectoryBundle/Resources/js/directory/**/*.ts',
              'src/Biopen/GeoDirectoryBundle/Resources/js/commons/**/*.ts'],
              ['scriptsDirectory']);

  gulp.watch(['src/Biopen/GeoDirectoryBundle/Resources/js/element-form/**/*.js'],
              ['scriptsElementForm']);

  gulp.watch('src/Biopen/GeoDirectoryBundle/Resources/js/libs/**/*.js', ['scriptsLibs']);

  gulp.watch(['src/Biopen/CoreBundle/Resources/js/**/*.ts'], ['scriptsHome']);
  // Watch image files
  //gulp.watch('src/img/*', ['images']);

});

gulp.task('clean', function(cb) {
    del(['web/assets/css', 'web/js'], cb);
});

gulp.task('build', function() {
    gulp.start('clean','sass', 'scriptsLibs', 'scriptsHome', 'scriptsElementForm','scriptsDirectory');
});

gulp.task('production', function() {
    gulp.start('prod_styles', 'prod_js');
});

<|endoftext|>


<commit_before>import Ember from "ember";
import Babel from "npm:babel";
import blueprints from '../lib/blueprints';

/**
 * A tiny browser version of the CLI build chain.
 * or more realistically: a hacked reconstruction of it.
 *
 * Parts of this module are directly copied from the ember-cli
 * source code at https://github.com/ember-cli/ember-cli
 */
export default Em.Service.extend({

  /**
   * Build a gist into an Ember app.
   *
   * @param  {Gist} gist    Gist to build
   * @return {Ember Object}       Source code for built Ember app
   */
  compileGist (gist) {
    var promise = new Em.RSVP.Promise((resolve, reject) => {
      var errors = [], out = [], cssOut = [];
      gist.get('files').forEach(file => {
        try {
          switch(file.get('extension')) {
            case '.js':
              out.push(this.compileJs(file.get('content'), file.get('nameWithModule')));
              break;
            case '.hbs':
              out.push(this.compileHbs(file.get('content'), file.get('nameWithModule')));
              break;
            case '.css':
              cssOut.push(this.compileCss(file.get('content'), file.get('nameWithModule')));
              break;
            case '.json':
              break;
          }
        }
        catch(e) {
          e.message = '%@: %@'.fmt(file.get('nameWithModule'), e.message);
          errors.push(e);
        }
      });

      if (errors.length) {return reject(errors);}

      // Add app
      out.push(this.compileJs(blueprints.app, 'demo-app/app'));

      // Add router
      if (!gist.get('files').findBy('nameWithModule', 'demo-app/router')) {
        out.push(this.compileJs(blueprints.router, 'demo-app/router'));
      }
      out.push(this.compileJs('import Router from \'demo-app/router\';\nRouter.reopen({\n  updateUrlBar: Ember.on(\'didTransition\', function() {\n    window.parent.demoAppUrl = this.get(\'url\');\n    window.parent.updateDemoAppUrl();\n  })\n});\nexport default {name: \'router\',\n initialize: function() {}\n};\n', 'demo-app/initializers/router'));

      // Add config
      out.push(this.compileJs('export default {modulePrefix:"demo-app"}', 'demo-app/config/environment'));

      // Add boot code
      contentForAppBoot(out, {modulePrefix:'demo-app'});

      var twiddleJson = gist.get('files').findBy('nameWithModule', 'twiddle.json');
      if (twiddleJson) {
        twiddleJson = twiddleJson.get('content');
      } else {
        twiddleJson = '{\n  "dependencies": {\n    "jquery": "assets/bower_components/jquery/dist/jquery.js",\n    "ember": "assets/bower_components/ember/ember.js",\n    "ember-data": "assets/bower_components/ember-data/ember-data.js"\n  }\n}';
      }
      twiddleJson = JSON.parse(twiddleJson);

      resolve(Ember.Object.create({ code: out.join('\n'), styles: cssOut.join('\n'), twiddleJson: twiddleJson }));
    });

    return promise;
  },

  /**
   * Compile a javascript file. This means that we
   * transform it using Babel.
   *
   * @param  {String} code       ES6 module code
   * @param  {String} moduleName Name for the module
   * @return {String}            Transpiled module code
   */
  compileJs (code, moduleName) {
    return Babel.transform(code, babelOpts(moduleName)).code;
  },

  /**
   * Compile a Handlebars template into an AMD module.
   *
   * @param  {String} code       hbs code
   * @param  {String} moduleName Name for the module
   * @return {String}            AMD module code
   */
  compileHbs (code, moduleName) {
    var templateCode = Em.HTMLBars.precompile(code || '');
    return this.compileJs('export default Ember.HTMLBars.template(' + templateCode + ');', moduleName);
  },

  compileCss(code, moduleName) {
    var prefix = "demo-app/styles/";
    if (moduleName.substring(0, prefix.length) === prefix) {
        return code;
    }
    return '';
  }
});

/**
 * Generate babel options for the specified module
 * @param  {String} moduleName
 * @return {Object}            Babel options
 */
function babelOpts(moduleName) {
  return {
    modules:'amd',
    moduleIds:true,
    moduleId: moduleName
  };
}

/**
 * Generate the application boot code
 * @param  {Array} content  Code buffer to append to
 * @param  {Object} config  App configuration
 * @return {Array}          Code buffer
 */
function contentForAppBoot (content, config) {
  // Some modules are not actually transpiled so Babel
  // doesn't recognize them properly...
  var monkeyPatchModules = [
    'ember',
    'ember-data',
    'ember/resolver',
    'ember/load-initializers'
  ];

  monkeyPatchModules.forEach(function(mod) {
    content.push('  require("'+mod+'").__esModule=true;');
  });

  content.push('  require("' +
    config.modulePrefix +
    '/app")["default"].create(' +
    calculateAppConfig(config) +
    ');');
}

/**
 * Directly copied from ember-cli
 */
function calculateAppConfig(config) {
  return JSON.stringify(config.APP || {});
}

<commit_msg>Fix bug<commit_after>import Ember from "ember";
import Babel from "npm:babel";
import blueprints from '../lib/blueprints';

/**
 * A tiny browser version of the CLI build chain.
 * or more realistically: a hacked reconstruction of it.
 *
 * Parts of this module are directly copied from the ember-cli
 * source code at https://github.com/ember-cli/ember-cli
 */
export default Em.Service.extend({

  /**
   * Build a gist into an Ember app.
   *
   * @param  {Gist} gist    Gist to build
   * @return {Ember Object}       Source code for built Ember app
   */
  compileGist (gist) {
    var promise = new Em.RSVP.Promise((resolve, reject) => {
      var errors = [], out = [], cssOut = [];
      gist.get('files').forEach(file => {
        try {
          switch(file.get('extension')) {
            case '.js':
              out.push(this.compileJs(file.get('content'), file.get('nameWithModule')));
              break;
            case '.hbs':
              out.push(this.compileHbs(file.get('content'), file.get('nameWithModule')));
              break;
            case '.css':
              cssOut.push(this.compileCss(file.get('content'), file.get('nameWithModule')));
              break;
            case '.json':
              break;
          }
        }
        catch(e) {
          e.message = '%@: %@'.fmt(file.get('nameWithModule'), e.message);
          errors.push(e);
        }
      });

      if (errors.length) {return reject(errors);}

      // Add app
      out.push(this.compileJs(blueprints.app, 'demo-app/app'));

      // Add router
      if (!gist.get('files').findBy('nameWithModule', 'demo-app/router')) {
        out.push(this.compileJs(blueprints.router, 'demo-app/router'));
      }
      out.push(this.compileJs('import Router from \'demo-app/router\';\nRouter.reopen({\n  updateUrlBar: Ember.on(\'didTransition\', function() {\n    window.parent.demoAppUrl = this.get(\'url\');\n    window.parent.updateDemoAppUrl();\n  })\n});\nexport default {name: \'router\',\n initialize: function() {}\n};\n', 'demo-app/initializers/router'));

      // Add config
      out.push(this.compileJs('export default {modulePrefix:"demo-app"}', 'demo-app/config/environment'));

      // Add boot code
      contentForAppBoot(out, {modulePrefix:'demo-app'});

      var twiddleJson = gist.get('files').findBy('nameWithModule', 'demo-app/twiddle');
      if (twiddleJson) {
        twiddleJson = twiddleJson.get('content');
      } else {
        twiddleJson = '{\n  "dependencies": {\n    "jquery": "assets/bower_components/jquery/dist/jquery.js",\n    "ember": "assets/bower_components/ember/ember.js",\n    "ember-data": "assets/bower_components/ember-data/ember-data.js"\n  }\n}';
      }
      twiddleJson = JSON.parse(twiddleJson);

      resolve(Ember.Object.create({ code: out.join('\n'), styles: cssOut.join('\n'), twiddleJson: twiddleJson }));
    });

    return promise;
  },

  /**
   * Compile a javascript file. This means that we
   * transform it using Babel.
   *
   * @param  {String} code       ES6 module code
   * @param  {String} moduleName Name for the module
   * @return {String}            Transpiled module code
   */
  compileJs (code, moduleName) {
    return Babel.transform(code, babelOpts(moduleName)).code;
  },

  /**
   * Compile a Handlebars template into an AMD module.
   *
   * @param  {String} code       hbs code
   * @param  {String} moduleName Name for the module
   * @return {String}            AMD module code
   */
  compileHbs (code, moduleName) {
    var templateCode = Em.HTMLBars.precompile(code || '');
    return this.compileJs('export default Ember.HTMLBars.template(' + templateCode + ');', moduleName);
  },

  compileCss(code, moduleName) {
    var prefix = "demo-app/styles/";
    if (moduleName.substring(0, prefix.length) === prefix) {
        return code;
    }
    return '';
  }
});

/**
 * Generate babel options for the specified module
 * @param  {String} moduleName
 * @return {Object}            Babel options
 */
function babelOpts(moduleName) {
  return {
    modules:'amd',
    moduleIds:true,
    moduleId: moduleName
  };
}

/**
 * Generate the application boot code
 * @param  {Array} content  Code buffer to append to
 * @param  {Object} config  App configuration
 * @return {Array}          Code buffer
 */
function contentForAppBoot (content, config) {
  // Some modules are not actually transpiled so Babel
  // doesn't recognize them properly...
  var monkeyPatchModules = [
    'ember',
    'ember-data',
    'ember/resolver',
    'ember/load-initializers'
  ];

  monkeyPatchModules.forEach(function(mod) {
    content.push('  require("'+mod+'").__esModule=true;');
  });

  content.push('  require("' +
    config.modulePrefix +
    '/app")["default"].create(' +
    calculateAppConfig(config) +
    ');');
}

/**
 * Directly copied from ember-cli
 */
function calculateAppConfig(config) {
  return JSON.stringify(config.APP || {});
}

<|endoftext|>


<commit_before>var video = document.getElementById('webcam');
var video_canvas = document.getElementById('video_canvas');
//$(window).load(function() {startVideo()});
"use strict";
function startVideo(callback) {
    try {
        compatibility.getUserMedia({video: true}, function (stream) {
            try {
                video.src = compatibility.URL.createObjectURL(stream);
            } catch (error) {
                video.src = stream;
            }
            setTimeout(function () {
                document.getElementById('livedemo').style.display = 'block';
                video.play();
                demo_app();
                compatibility.requestAnimationFrame(tick);
            }, 500);
            callback({success: true});
        }, function (error) {
            callback({success: false, rtcerror: true, message: "Your webcam (WebRTC) is not available."});
        });
    } catch (error) {
        callback({success: false, rtcerror: false, message: "Hmm. There is a problem connecting to your webcamera. Sorry!"});
    }
}

function stopVideo() {
    video.pause();
    video.src = null;
}

var stat = new profiler();

var gui,options,video_ctx,canvasWidth,canvasHeight;
var curr_img_pyr, prev_img_pyr, point_count, point_status, prev_xy, curr_xy;
var box, mousedown, median_x, median_y, median_s, ratio;

var demo_opt = function(){
    this.win_size = 20;
    this.max_iterations = 30;
    this.epsilon = 0.01;
    this.min_eigen = 0.001;
    this.point_density = 5;
}

function demo_app() {
    canvasWidth  = video_canvas.width;
    canvasHeight = video_canvas.height;
    video_ctx = video_canvas.getContext('2d');

    video_ctx.fillStyle = "rgb(0,255,0)";
    video_ctx.strokeStyle = "#58B4DB";
    video_ctx.lineWidth=10;

    curr_img_pyr = new jsfeat.pyramid_t(3);
    prev_img_pyr = new jsfeat.pyramid_t(3);
    curr_img_pyr.allocate(640, 480, jsfeat.U8_t|jsfeat.C1_t);
    prev_img_pyr.allocate(640, 480, jsfeat.U8_t|jsfeat.C1_t);

    point_count = 0;
    point_status = new Uint8Array(100);
    prev_xy = new Float32Array(100*2);
    curr_xy = new Float32Array(100*2);

    options = new demo_opt();

    mousedown = false;
    box = new Float32Array(4);
    ratio = 1;
}

function tick() {
    compatibility.requestAnimationFrame(tick);
    stat.new_frame();
    if (video.readyState === video.HAVE_ENOUGH_DATA) {
        video_ctx.drawImage(video, 0, 0, 640, 480);
        var imageData = video_ctx.getImageData(0, 0, 640, 480);

        // swap flow data
        var _pt_xy = prev_xy;
        prev_xy = curr_xy;
        curr_xy = _pt_xy;
        var _pyr = prev_img_pyr;
        prev_img_pyr = curr_img_pyr;
        curr_img_pyr = _pyr;

        //stat.start("grayscale");
        jsfeat.imgproc.grayscale(imageData.data, curr_img_pyr.data[0].data);
        //stat.stop("grayscale");

        //stat.start("build image pyramid");
        curr_img_pyr.build(curr_img_pyr.data[0], true);
        //stat.stop("build image pyramid");

        //stat.start("optical flow lk");
        jsfeat.optical_flow_lk.track(prev_img_pyr, curr_img_pyr, prev_xy, curr_xy, point_count, options.win_size|0, options.max_iterations|0, point_status, options.epsilon, options.min_eigen);
        //stat.stop("optical flow lk");

        //stat.start("median flow");
        if (box[0]+box[2] == 0) document.getElementById('liveinstructions').style.display = "block";
        else document.getElementById('liveinstructions').style.display = "none";
        updateBoundingBox(video_ctx);
        prune_oflow_points(video_ctx);
        generate_points(box);
        //stat.stop("median flow");

        $('#log').html(stat.log());// + '
Median x, y: ' + median_x + ", " + median_y + '
Median scale: ' + median_s);
    }
}

function add_point(x, y){
    curr_xy[point_count<<1] = x;
    curr_xy[(point_count<<1)+1] = y;
    point_count++;
}

function on_canvas_down(e) {
    var coords = video_canvas.relMouseCoords(e);
    if(coords.x > 0 & coords.y > 0 & coords.x < canvasWidth & coords.y < canvasHeight) {
        box = new Float32Array(4);
        mousedown = true;
        box[0] = coords.x;
        box[1] = coords.y;
        box[2] = coords.x;
        box[3] = coords.y;
    }
}
function on_canvas_move(e) {
    if (!mousedown) return;
    var coords = video_canvas.relMouseCoords(e);
    if(coords.x > 0 & coords.y > 0 & coords.x < canvasWidth & coords.y < canvasHeight) {
        box[2] = coords.x;
        box[3] = coords.y;
    }
}
function on_canvas_up(e) {
    if (!mousedown || box[0]+box[2] == 0) return;
    box = [Math.min(box[0], box[2]), Math.min(box[1], box[3]), Math.max(box[0], box[2]), Math.max(box[1], box[3])]
    generate_points(box);
    //RATIO width over height. used to ensure that ratio doesn't slide over til due to rounding.
    ratio = Math.abs(box[0]-box[2])/Math.abs(box[1]-box[3]);
    mousedown = false;
}
video_canvas.addEventListener('mousedown', on_canvas_down, false);
video_canvas.addEventListener('mousemove', on_canvas_move, false);
video_canvas.addEventListener('mouseup', on_canvas_up, false);

function draw_point(video_ctx, x, y) {
    video_ctx.beginPath();
    video_ctx.arc(x, y, 3, 0, Math.PI*2, true);
    video_ctx.closePath();
    video_ctx.fill();
}

function prune_oflow_points(video_ctx) {
    var n = point_count;
    var i=0,j=0;

    for(; i < n; ++i) {
        if(point_status[i] == 1) {
            if(j < i) {
                curr_xy[j<<1] = curr_xy[i<<1];
                curr_xy[(j<<1)+1] = curr_xy[(i<<1)+1];
            }
            draw_point(video_ctx, curr_xy[j<<1], curr_xy[(j<<1)+1]);
            ++j;
        }
    }
    point_count = j;
}

function generate_points(box){
    var resolution_x = options.point_density;
    var resolution_y = options.point_density;
    var min_dist = 15;
    var x = Math.min(box[0], box[2]);
    var y = Math.min(box[1], box[3]);
    var width = Math.abs(box[0]-box[2]);
    var height = Math.abs(box[1]-box[3]);
    var res_x = Math.max(Math.round(width/resolution_x), min_dist);
    var res_y = Math.max(Math.round(height/resolution_y), min_dist);

    point_count = 0;
    point_status = new Uint8Array(100);
    for (var i=res_x/2; i<width; i+=res_x){
        for (var j=res_y/2; j<height; j+=res_y){
            add_point(Math.round(x+i), Math.round(y+j));
        }
    }
}

function median(values, count) {
    Array.prototype.sort.call(values, function(a, b) { return a - b; });
    var half = Math.floor(values.length/2);
    if(values.length % 2)
        return values[half];
    else
        return (values[half-1] + values[half]) / 2.0;
}
function updateBoundingBox(video_ctx) {
    if (box[2]+box[3] != 0){
        if (!mousedown){
            var count = 0;
            for (var i=0; i<point_count; i++) if(point_status[i] == 1) count++;
            var list_x = new Float32Array(count);
            var list_y = new Float32Array(count);
            var list_s = new Float32Array(Comb(count, 2));
            var j = 0;
            var scale_counter = 0;
            for (var i=0; i<point_count; i++){
                if(point_status[i] == 1){
                    var pos = i<<1;
                    list_x[j] = curr_xy[pos]-prev_xy[pos];
                    list_y[j] = curr_xy[pos+1]-prev_xy[pos+1];
                    for (var h=i+1; h<point_count; h++){
                        if(point_status[h] == 1){
                            var pos2 = h<<1;
                            var d1 = Math.sqrt( Math.pow(prev_xy[pos]-prev_xy[pos2],2) + Math.pow(prev_xy[pos+1]-prev_xy[pos2+1],2) );
                            var d2 = Math.sqrt( Math.pow(curr_xy[pos]-curr_xy[pos2],2) + Math.pow(curr_xy[pos+1]-curr_xy[pos2+1],2) );
                            list_s[scale_counter] = d2/d1;
                            scale_counter++;
                        }
                    }
                    j++;
                }
            }
            median_x = median(list_x, count);
            median_y = median(list_y, count);
            median_s = median(list_s, scale_counter);

            var h = Math.abs(box[1]-box[3]);
            var h_mod = (h*median_s-h)/2;
            box[1] += median_y-h_mod;
            box[3] += median_y+h_mod;

            h = Math.abs(box[1]-box[3]);
            var w = Math.abs(box[0]-box[2]);
            var w_mod = (h*ratio-w)/2;
            box[0] += median_x-w_mod;
            box[2] = box[0] + h*ratio;

        }
        video_ctx.beginPath();
        video_ctx.rect(Math.min(box[0], box[2]), Math.min(box[1], box[3]), Math.abs(box[0]-box[2]), Math.abs(box[1]-box[3]));
        video_ctx.lineWidth=10;
        video_ctx.stroke();
        video_ctx.closePath();
    }

}

function relMouseCoords(event) {
    /*
    var totalOffsetX=0,totalOffsetY=0,canvasX=0,canvasY=0;
    var currentElement = this;

    do {
        totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
        totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
    } while(currentElement = currentElement.offsetParent)

    canvasX = event.pageX - totalOffsetX;
    canvasY = event.pageY - totalOffsetY;

    return {x:canvasX, y:canvasY}*/
    var rect = video_canvas.getBoundingClientRect();
    return {
        x: event.clientX - rect.left,
        y: event.clientY - rect.top
    };
}
HTMLCanvasElement.prototype.relMouseCoords = relMouseCoords;

$(window).unload(function() {
    video.pause();
    video.src=null;
});

//http://www.ciphersbyritter.com/JAVASCRP/PERMCOMB.HTM#Combinations
function Comb( n, r ) {
    // combinations of n things taken r at a time, order not impt.
    // Comb( n, 0 ) = 1, and Comb( n, n ) = 1
    // Comb( n, r ) = 0 if r > n or r < 0
    if ((r == 0) || (r == n)) return 1;
    else
    if ((r > n) || (r < 0)) return 0;
    else
    return factdivdiv( n, r, n-r );
}
function factdivdiv( n, k1, k2 ) {
    // computes (n! / k1! k2!) for combinations
    // assure k1 >= k2
    if (k1 < k2) { i = k1; k1 = k2; k2 = i; }
    if (k1 > n) t = 0;
    else {
        // accumulate the factors for k2 factorial
        var t=1;
        while (k2 > 1)
        t *= k2--;
        // accumulate the factors from n downto k1
        var t2=1;
        while (n > k1)
        t2 *= n--;
        t = t2 / t;
    }
    return t;
}<commit_msg>of by one when using other sort<commit_after>var video = document.getElementById('webcam');
var video_canvas = document.getElementById('video_canvas');
//$(window).load(function() {startVideo()});
"use strict";
function startVideo(callback) {
    try {
        compatibility.getUserMedia({video: true}, function (stream) {
            try {
                video.src = compatibility.URL.createObjectURL(stream);
            } catch (error) {
                video.src = stream;
            }
            setTimeout(function () {
                document.getElementById('livedemo').style.display = 'block';
                video.play();
                demo_app();
                compatibility.requestAnimationFrame(tick);
            }, 500);
            callback({success: true});
        }, function (error) {
            callback({success: false, rtcerror: true, message: "Your webcam (WebRTC) is not available."});
        });
    } catch (error) {
        callback({success: false, rtcerror: false, message: "Hmm. There is a problem connecting to your webcamera. Sorry!"});
    }
}

function stopVideo() {
    video.pause();
    video.src = null;
}

var stat = new profiler();

var gui,options,video_ctx,canvasWidth,canvasHeight;
var curr_img_pyr, prev_img_pyr, point_count, point_status, prev_xy, curr_xy;
var box, mousedown, median_x, median_y, median_s, ratio;

var demo_opt = function(){
    this.win_size = 20;
    this.max_iterations = 30;
    this.epsilon = 0.01;
    this.min_eigen = 0.001;
    this.point_density = 5;
}

function demo_app() {
    canvasWidth  = video_canvas.width;
    canvasHeight = video_canvas.height;
    video_ctx = video_canvas.getContext('2d');

    video_ctx.fillStyle = "rgb(0,255,0)";
    video_ctx.strokeStyle = "#58B4DB";
    video_ctx.lineWidth=10;

    curr_img_pyr = new jsfeat.pyramid_t(3);
    prev_img_pyr = new jsfeat.pyramid_t(3);
    curr_img_pyr.allocate(640, 480, jsfeat.U8_t|jsfeat.C1_t);
    prev_img_pyr.allocate(640, 480, jsfeat.U8_t|jsfeat.C1_t);

    point_count = 0;
    point_status = new Uint8Array(100);
    prev_xy = new Float32Array(100*2);
    curr_xy = new Float32Array(100*2);

    options = new demo_opt();

    mousedown = false;
    box = new Float32Array(4);
    ratio = 1;
}

function tick() {
    compatibility.requestAnimationFrame(tick);
    stat.new_frame();
    if (video.readyState === video.HAVE_ENOUGH_DATA) {
        video_ctx.drawImage(video, 0, 0, 640, 480);
        var imageData = video_ctx.getImageData(0, 0, 640, 480);

        // swap flow data
        var _pt_xy = prev_xy;
        prev_xy = curr_xy;
        curr_xy = _pt_xy;
        var _pyr = prev_img_pyr;
        prev_img_pyr = curr_img_pyr;
        curr_img_pyr = _pyr;

        //stat.start("grayscale");
        jsfeat.imgproc.grayscale(imageData.data, curr_img_pyr.data[0].data);
        //stat.stop("grayscale");

        //stat.start("build image pyramid");
        curr_img_pyr.build(curr_img_pyr.data[0], true);
        //stat.stop("build image pyramid");

        //stat.start("optical flow lk");
        jsfeat.optical_flow_lk.track(prev_img_pyr, curr_img_pyr, prev_xy, curr_xy, point_count, options.win_size|0, options.max_iterations|0, point_status, options.epsilon, options.min_eigen);
        //stat.stop("optical flow lk");

        //stat.start("median flow");
        if (box[0]+box[2] == 0) document.getElementById('liveinstructions').style.display = "block";
        else document.getElementById('liveinstructions').style.display = "none";
        updateBoundingBox(video_ctx);
        prune_oflow_points(video_ctx);
        generate_points(box);
        //stat.stop("median flow");

        $('#log').html(stat.log());// + '
Median x, y: ' + median_x + ", " + median_y + '
Median scale: ' + median_s);
    }
}

function add_point(x, y){
    curr_xy[point_count<<1] = x;
    curr_xy[(point_count<<1)+1] = y;
    point_count++;
}

function on_canvas_down(e) {
    var coords = video_canvas.relMouseCoords(e);
    if(coords.x > 0 & coords.y > 0 & coords.x < canvasWidth & coords.y < canvasHeight) {
        box = new Float32Array(4);
        mousedown = true;
        box[0] = coords.x;
        box[1] = coords.y;
        box[2] = coords.x;
        box[3] = coords.y;
    }
}
function on_canvas_move(e) {
    if (!mousedown) return;
    var coords = video_canvas.relMouseCoords(e);
    if(coords.x > 0 & coords.y > 0 & coords.x < canvasWidth & coords.y < canvasHeight) {
        box[2] = coords.x;
        box[3] = coords.y;
    }
}
function on_canvas_up(e) {
    if (!mousedown || box[0]+box[2] == 0) return;
    box = [Math.min(box[0], box[2]), Math.min(box[1], box[3]), Math.max(box[0], box[2]), Math.max(box[1], box[3])]
    generate_points(box);
    //RATIO width over height. used to ensure that ratio doesn't slide over til due to rounding.
    ratio = Math.abs(box[0]-box[2])/Math.abs(box[1]-box[3]);
    mousedown = false;
}
video_canvas.addEventListener('mousedown', on_canvas_down, false);
video_canvas.addEventListener('mousemove', on_canvas_move, false);
video_canvas.addEventListener('mouseup', on_canvas_up, false);

function draw_point(video_ctx, x, y) {
    video_ctx.beginPath();
    video_ctx.arc(x, y, 3, 0, Math.PI*2, true);
    video_ctx.closePath();
    video_ctx.fill();
}

function prune_oflow_points(video_ctx) {
    var n = point_count;
    var i=0,j=0;

    for(; i < n; ++i) {
        if(point_status[i] == 1) {
            if(j < i) {
                curr_xy[j<<1] = curr_xy[i<<1];
                curr_xy[(j<<1)+1] = curr_xy[(i<<1)+1];
            }
            draw_point(video_ctx, curr_xy[j<<1], curr_xy[(j<<1)+1]);
            ++j;
        }
    }
    point_count = j;
}

function generate_points(box){
    var resolution_x = options.point_density;
    var resolution_y = options.point_density;
    var min_dist = 15;
    var x = Math.min(box[0], box[2]);
    var y = Math.min(box[1], box[3]);
    var width = Math.abs(box[0]-box[2]);
    var height = Math.abs(box[1]-box[3]);
    var res_x = Math.max(Math.round(width/resolution_x), min_dist);
    var res_y = Math.max(Math.round(height/resolution_y), min_dist);

    point_count = 0;
    point_status = new Uint8Array(100);
    for (var i=res_x/2; i<width; i+=res_x){
        for (var j=res_y/2; j<height; j+=res_y){
            add_point(Math.round(x+i), Math.round(y+j));
        }
    }
}

function median(values, count) {
    Array.prototype.sort.call(values, function(a, b) { return a - b; });
    var half = Math.floor(values.length/2);
    if(values.length % 2)
        return values[half];
    else
        return (values[half-1] + values[half]) / 2.0;
}
function updateBoundingBox(video_ctx) {
    if (box[2]+box[3] != 0){
        if (!mousedown){
            var count = 0;
            for (var i=0; i<point_count; i++) if(point_status[i] == 1) count++;
            var list_x = new Float32Array(count);
            var list_y = new Float32Array(count);
            var list_s = new Float32Array(Comb(count, 2));
            var j = 0;
            var scale_counter = 0;
            for (var i=0; i<point_count; i++){
                if(point_status[i] == 1){
                    var pos = i<<1;
                    list_x[j] = curr_xy[pos]-prev_xy[pos];
                    list_y[j] = curr_xy[pos+1]-prev_xy[pos+1];
                    for (var h=i+1; h<point_count; h++){
                        if(point_status[h] == 1){
                            var pos2 = h<<1;
                            var d1 = Math.sqrt( Math.pow(prev_xy[pos]-prev_xy[pos2],2) + Math.pow(prev_xy[pos+1]-prev_xy[pos2+1],2) );
                            var d2 = Math.sqrt( Math.pow(curr_xy[pos]-curr_xy[pos2],2) + Math.pow(curr_xy[pos+1]-curr_xy[pos2+1],2) );
                            list_s[scale_counter] = d2/d1;
                            scale_counter++;
                        }
                    }
                    j++;
                }
            }
            median_x = median(list_x, count);
            median_y = median(list_y, count);
            median_s = median(list_s, scale_counter-1);

            var h = Math.abs(box[1]-box[3]);
            var h_mod = (h*median_s-h)/2;
            box[1] += median_y-h_mod;
            box[3] += median_y+h_mod;

            h = Math.abs(box[1]-box[3]);
            var w = Math.abs(box[0]-box[2]);
            var w_mod = (h*ratio-w)/2;
            box[0] += median_x-w_mod;
            box[2] = box[0] + h*ratio;

        }
        video_ctx.beginPath();
        video_ctx.rect(Math.min(box[0], box[2]), Math.min(box[1], box[3]), Math.abs(box[0]-box[2]), Math.abs(box[1]-box[3]));
        video_ctx.lineWidth=10;
        video_ctx.stroke();
        video_ctx.closePath();
    }

}

function relMouseCoords(event) {
    /*
    var totalOffsetX=0,totalOffsetY=0,canvasX=0,canvasY=0;
    var currentElement = this;

    do {
        totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
        totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
    } while(currentElement = currentElement.offsetParent)

    canvasX = event.pageX - totalOffsetX;
    canvasY = event.pageY - totalOffsetY;

    return {x:canvasX, y:canvasY}*/
    var rect = video_canvas.getBoundingClientRect();
    return {
        x: event.clientX - rect.left,
        y: event.clientY - rect.top
    };
}
HTMLCanvasElement.prototype.relMouseCoords = relMouseCoords;

$(window).unload(function() {
    video.pause();
    video.src=null;
});

//http://www.ciphersbyritter.com/JAVASCRP/PERMCOMB.HTM#Combinations
function Comb( n, r ) {
    // combinations of n things taken r at a time, order not impt.
    // Comb( n, 0 ) = 1, and Comb( n, n ) = 1
    // Comb( n, r ) = 0 if r > n or r < 0
    if ((r == 0) || (r == n)) return 1;
    else
    if ((r > n) || (r < 0)) return 0;
    else
    return factdivdiv( n, r, n-r );
}
function factdivdiv( n, k1, k2 ) {
    // computes (n! / k1! k2!) for combinations
    // assure k1 >= k2
    if (k1 < k2) { i = k1; k1 = k2; k2 = i; }
    if (k1 > n) t = 0;
    else {
        // accumulate the factors for k2 factorial
        var t=1;
        while (k2 > 1)
        t *= k2--;
        // accumulate the factors from n downto k1
        var t2=1;
        while (n > k1)
        t2 *= n--;
        t = t2 / t;
    }
    return t;
}<|endoftext|>


<commit_before>// @remove-on-eject-begin
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
// @remove-on-eject-end
'use strict';

const path = require('path');
const fs = require('fs');
const url = require('url');

// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebookincubator/create-react-app/issues/637
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);

const envPublicUrl = process.env.PUBLIC_URL;

function ensureSlash(path, needsSlash) {
  const hasSlash = path.endsWith('/');
  if (hasSlash && !needsSlash) {
    return path.substr(path, path.length - 1);
  } else if (!hasSlash && needsSlash) {
    return `${path}/`;
  } else {
    return path;
  }
}

const getPublicUrl = appPackageJson =>
  envPublicUrl || require(appPackageJson).homepage;

// We use `PUBLIC_URL` environment variable or "homepage" field to infer
// "public path" at which the app is served.
// Webpack needs to know it to put the right <script> hrefs into HTML even in
// single-page apps that may serve index.html for nested URLs like /todos/42.
// We can't use a relative path in HTML because we don't want to load something
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
function getServedPath(appPackageJson) {
  const publicUrl = getPublicUrl(appPackageJson);
  const servedUrl =
    envPublicUrl || (publicUrl ? url.parse(publicUrl).pathname : '/');
  return ensureSlash(servedUrl, true);
}

// config after eject: we're in ./config/
module.exports = {
  dotenv: resolveApp('.env'),
  appBuild: resolveApp('build'),
  appPublic: resolveApp('public'),
  appHtml: resolveApp('public/index.html'),
  appIndexJs: resolveApp('src/index.js'),
  appPackageJson: resolveApp('package.json'),
  appSrc: resolveApp('src'),
  yarnLockFile: resolveApp('yarn.lock'),
  testsSetup: resolveApp('src/setupTests.js'),
  appNodeModules: resolveApp('node_modules'),
  publicUrl: getPublicUrl(resolveApp('package.json')),
  servedPath: getServedPath(resolveApp('package.json')),
};

// @remove-on-eject-begin
const resolveOwn = relativePath => path.resolve(__dirname, '..', relativePath);

// config before eject: we're in ./node_modules/react-scripts/config/
module.exports = {
  dotenv: resolveApp('.env'),
  appPath: resolveApp('.'),
  appBuild: resolveApp('build'),
  appPublic: resolveApp('public'),
  appHtml: resolveApp('public/index.html'),
  appIndexJs: resolveApp('src/index.js'),
  appPackageJson: resolveApp('package.json'),
  appSrc: resolveApp('src'),
  yarnLockFile: resolveApp('yarn.lock'),
  testsSetup: resolveApp('src/setupTests.js'),
  appNodeModules: resolveApp('node_modules'),
  publicUrl: getPublicUrl(resolveApp('package.json')),
  servedPath: getServedPath(resolveApp('package.json')),
  // These properties only exist before ejecting:
  ownPath: resolveOwn('.'),
  ownNodeModules: resolveOwn('node_modules'), // This is empty on npm 3
};

const ownPackageJson = require('../package.json');
const reactScriptsPath = resolveApp(`node_modules/${ownPackageJson.name}`);
const reactScriptsLinked =
  fs.existsSync(reactScriptsPath) &&
  fs.lstatSync(reactScriptsPath).isSymbolicLink();

// config before publish: we're in ./packages/react-scripts/config/
if (
  !reactScriptsLinked &&
  __dirname.indexOf(path.join('packages', 'react-scripts', 'config')) !== -1
) {
  module.exports = {
    dotenv: resolveOwn('template/.env'),
    appPath: resolveApp('.'),
    appBuild: resolveOwn('../../build'),
    appPublic: resolveOwn('template/public'),
    appHtml: resolveOwn('template/public/index.html'),
    appIndexJs: resolveOwn('template/src/index.js'),
    appPackageJson: resolveOwn('package.json'),
    appSrc: resolveOwn('template/src'),
    yarnLockFile: resolveOwn('template/yarn.lock'),
    testsSetup: resolveOwn('template/src/setupTests.js'),
    appNodeModules: resolveOwn('node_modules'),
    publicUrl: getPublicUrl(resolveOwn('package.json')),
    servedPath: getServedPath(resolveOwn('package.json')),
    // These properties only exist before ejecting:
    ownPath: resolveOwn('.'),
    ownNodeModules: resolveOwn('node_modules'),
  };
}
// @remove-on-eject-end
<commit_msg>added custom entry point config<commit_after>// @remove-on-eject-begin
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
// @remove-on-eject-end
'use strict';

const path = require('path');
const fs = require('fs');
const url = require('url');

// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebookincubator/create-react-app/issues/637
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = relativePath => path.resolve(appDirectory, relativePath);

const envPublicUrl = process.env.PUBLIC_URL;

function ensureSlash(path, needsSlash) {
  const hasSlash = path.endsWith('/');
  if (hasSlash && !needsSlash) {
    return path.substr(path, path.length - 1);
  } else if (!hasSlash && needsSlash) {
    return `${path}/`;
  } else {
    return path;
  }
}

const getPublicUrl = appPackageJson =>
  envPublicUrl || require(appPackageJson).homepage;

// We use `PUBLIC_URL` environment variable or "homepage" field to infer
// "public path" at which the app is served.
// Webpack needs to know it to put the right <script> hrefs into HTML even in
// single-page apps that may serve index.html for nested URLs like /todos/42.
// We can't use a relative path in HTML because we don't want to load something
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
function getServedPath(appPackageJson) {
  const publicUrl = getPublicUrl(appPackageJson);
  const servedUrl =
    envPublicUrl || (publicUrl ? url.parse(publicUrl).pathname : '/');
  return ensureSlash(servedUrl, true);
}

const customEntryFile = (appPackageJson, basePath) =>
  require(appPackageJson).react_super_scripts
    ? require(appPackageJson).react_super_scripts.appEntry
      ? basePath + require(appPackageJson).react_super_scripts.appEntry
      : undefined
    : undefined;

// config after eject: we're in ./config/
module.exports = {
  dotenv: resolveApp('.env'),
  appBuild: resolveApp('build'),
  appPublic: resolveApp('public'),
  appHtml: resolveApp('public/index.html'),
  appIndexJs: resolveApp(
    customEntryFile(resolveApp('package.json'), '') || 'src/index.js'
  ),
  appPackageJson: resolveApp('package.json'),
  appSrc: resolveApp('src'),
  yarnLockFile: resolveApp('yarn.lock'),
  testsSetup: resolveApp('src/setupTests.js'),
  appNodeModules: resolveApp('node_modules'),
  publicUrl: getPublicUrl(resolveApp('package.json')),
  servedPath: getServedPath(resolveApp('package.json')),
};

// @remove-on-eject-begin
const resolveOwn = relativePath => path.resolve(__dirname, '..', relativePath);

// config before eject: we're in ./node_modules/react-scripts/config/
module.exports = {
  dotenv: resolveApp('.env'),
  appPath: resolveApp('.'),
  appBuild: resolveApp('build'),
  appPublic: resolveApp('public'),
  appHtml: resolveApp('public/index.html'),
  appIndexJs: resolveApp(
    customEntryFile(resolveApp('package.json'), '') || 'src/index.js'
  ),
  appPackageJson: resolveApp('package.json'),
  appSrc: resolveApp('src'),
  yarnLockFile: resolveApp('yarn.lock'),
  testsSetup: resolveApp('src/setupTests.js'),
  appNodeModules: resolveApp('node_modules'),
  publicUrl: getPublicUrl(resolveApp('package.json')),
  servedPath: getServedPath(resolveApp('package.json')),
  // These properties only exist before ejecting:
  ownPath: resolveOwn('.'),
  ownNodeModules: resolveOwn('node_modules'), // This is empty on npm 3
};

const ownPackageJson = require('../package.json');
const reactScriptsPath = resolveApp(`node_modules/${ownPackageJson.name}`);
const reactScriptsLinked =
  fs.existsSync(reactScriptsPath) &&
  fs.lstatSync(reactScriptsPath).isSymbolicLink();

// config before publish: we're in ./packages/react-scripts/config/
if (
  !reactScriptsLinked &&
  __dirname.indexOf(path.join('packages', 'react-scripts', 'config')) !== -1
) {
  module.exports = {
    dotenv: resolveOwn('template/.env'),
    appPath: resolveApp('.'),
    appBuild: resolveOwn('../../build'),
    appPublic: resolveOwn('template/public'),
    appHtml: resolveOwn('template/public/index.html'),
    appIndexJs: resolveOwn(
      customEntryFile(resolveOwn('package.json'), 'template/') ||
        'template/src/index.js'
    ),
    appPackageJson: resolveOwn('package.json'),
    appSrc: resolveOwn('template/src'),
    yarnLockFile: resolveOwn('template/yarn.lock'),
    testsSetup: resolveOwn('template/src/setupTests.js'),
    appNodeModules: resolveOwn('node_modules'),
    publicUrl: getPublicUrl(resolveOwn('package.json')),
    servedPath: getServedPath(resolveOwn('package.json')),
    // These properties only exist before ejecting:
    ownPath: resolveOwn('.'),
    ownNodeModules: resolveOwn('node_modules'),
  };
}
// @remove-on-eject-end
<|endoftext|>


<commit_before>$(window).on('load', function() {
    $('body').append($(""));
});

var daysRemaining=(function(){
    var oneDay = 24*60*60*1000;
    var decision = new Date(2017, 7, 8, 23, 59);
    return Math.floor(Math.abs((Date.now() - decision.getTime())/(oneDay)));
})();

$(".days-remaining-number").text(daysRemaining + " days");

/* useful vars */
var supportsSecret = null;

$(".toggle-button-question .toggle-select").click(function() {
  var $this = $(this);

  $(".toggle-button-question .toggle-select").removeClass("selected");
  $this.addClass("selected");
  $("#previewEmail").prop("disabled", false);

  supportsSecret = $this.attr('id') == "yes";
});

/* follow-up questions */
var senderSecret = null,
    emailId = null;

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}

function emailSent() {
  ga('send', 'event', 'secret-ballot-email', 'sent');

  // prep follow up questions
  var questions = [
    {
      q: "Have you ever participated in a protest march?",
      a: ["YES, I have", "NO, I have not"],
    }, {
      q: "Is this your first time emailing a Member of Parliament?",
      a: ["YES, it is", "NO, it is not"],
    }, {
      q: "Do you know that all MPs are assigned a constituency, and represent those who live in it?",
      a: ["YES, I know about that", "NO, I did not know"],
    },
  ];
  var q = questions[getRandomInt(0, questions.length)];

  ga('send', 'event', 'follow-up', 'asked', q.q);
  $('.follow-up-question p').text(q.q);
  $('#follow-up-answer-1').text(q.a[0]);
  $('#follow-up-answer-2').text(q.a[1]);

  // prep sharing
  var msg = supportsSecret ? 'I support' : 'I do not support';
  $('.twitter-share').data('message', 'I just emailed Baleka Mbete saying ' + msg + ' a secret ballot. Send an email and make your voice heard. @MbeteBaleka');
  $('.fb-share').data('message', 'I just emailed Baleka Mbete saying ' + msg + ' a secret ballot. Send an email and make your voice heard.');

  $("#secret-ballot-preview-message").hide();
  $("#secret-ballot-sent").show();
}

$(".follow-up-question-box .toggle-select-follow-up").click(function() {
  var $this = $(this);

  $(".follow-up-question-box .toggle-select-follow-up").removeClass("selected");
  $this.addClass("selected");

  var q = $('.follow-up-question').text().trim();
  var a = $this.text().trim();

  $('.follow-up-question p').text('Thanks!');
  $('.follow-up-answer-box').hide();

  // submit to server
  jQuery.ajax('/api/v1/email/' + emailId + '/qa/', {
    type: 'POST',
    data: {
      question: q,
      answer: a,
      sender_secret: senderSecret,
    },
  });

  ga('send', 'event', 'follow-up', 'answered', q);
});

$("#secret-ballot-preview-message").hide();
$("#secret-ballot-sent").hide();

$("#previewEmail").click(function(e) {
  e.preventDefault();
  var senderName = $(".name-input").val();
  var senderEmail = $(".email-input").val();

  if (senderName === '') {
    alert('Please enter your name');
    $('.name-input').focus();
    return;
  }

  if (senderEmail === '') {
    alert('Please enter your email');
    $('.email-input').focus();
    return;
  }

  if ($("#comment").val() != "") {
    var emailContent = "
Other issues that concern me about the future of South Africa are:

" + ($("#comment").val().replace(/\n/g, '
'))
  } else {
    var emailContent = "";
  };
  if ($(".toggle-select.selected").attr("id") == "no") {
    var emailSubject = "I do not support a secret ballot in the vote of no confidence";
  }
  else if ($(".toggle-select.selected").attr("id") == "yes") {
    var emailSubject = "I support a secret ballot in the vote of no confidence";
  };
  $("#name").text(senderName);
  $("#email").text(senderEmail);
  $("#email-title").text(emailSubject);

  $("#comment-preview").html("
Dear Madam Speaker,

I am a citizen of South Africa and I want to let you know that " + emailSubject + " in President Jacob Zuma.
" + emailContent + "

You represent all South Africans, including me. Please choose in favour of good governance - a governance that is best suited to realising my hopes for our future.

Yours sincerely,

" + senderName + "
");
  $("#secret-ballot-build-message").hide();
  $("#secret-ballot-preview-message").show();
  location.hash = "#secret-ballot-preview-message";
});

$("#editEmail").click(function(e) {
  e.preventDefault();
  $("#secret-ballot-build-message").show();
  $("#secret-ballot-preview-message").hide();
  location.hash = "#email-secret";
});

var reCaptchaValid = false;
var gReCaptchaValidated = function() {
  $("input[type=submit]").removeAttr('disabled');
  reCaptchaValid = true;
};

var gReCaptchaExpired = function() {
  $("input[type=submit]").attr('disabled','disabled');
  reCaptchaValid = false;
};

var recaptchaLoaded = function() {
  grecaptcha.render('recaptcha', {
    'sitekey': recaptchaKey,
    'callback': gReCaptchaValidated,
    'expired-callback': gReCaptchaExpired
  });
  if (typeof pymChild !== undefined) {
    pymChild.sendHeight();
  }
};

var reCaptchaValid = false;
var gReCaptchaValidated = function() {
  $("input[type=submit]").removeAttr('disabled');
  reCaptchaValid = true;
};

var gReCaptchaExpired = function() {
  $("input[type=submit]").attr('disabled','disabled');
  reCaptchaValid = false;
};

var recaptchaLoaded = function() {
  grecaptcha.render('recaptcha', {
    'sitekey': recaptchaKey,
    'callback': gReCaptchaValidated,
    'expired-callback': gReCaptchaExpired
  });
  if (typeof pymChild !== undefined) {
    pymChild.sendHeight();
  }
};

function submitForm(e) {
  e.preventDefault();

  var senderName = $(".name-input").val();
  var senderEmail = $(".email-input").val();
  var emailSubject = $("#email-title").text();
  var emailContent = $("#comment-preview").text();

  jQuery.ajax('/api/v1/email/', {
    type: 'POST',
    data: {
      person: recipient.id,
      name: senderName,
      email: senderEmail,
      body: emailContent,
      subject: emailSubject,
      gRecaptchaResponse: grecaptcha.getResponse(),
    },
    success: function(data) {
      console.info("success", data);

      senderSecret = data.sender_secret;
      emailId = data.secure_id;

      emailSent();
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.error(jqXHR, textStatus, errorThrown, jqXHR.responseText);
    }
  });
}

$('#email-secret').on('submit', submitForm);

// https://stackoverflow.com/a/901144/1305080
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

function getParentUrl() {
  return getParameterByName('parentUrl');
}

$(function() {
  ga('send', {
    hitType: 'event',
    eventCategory: 'environment',
    eventAction: 'loaded-by-parent-url',
    eventLabel: getParentUrl()
  });
});
<commit_msg>Send line breaks in email body<commit_after>$(window).on('load', function() {
    $('body').append($(""));
});

var daysRemaining=(function(){
    var oneDay = 24*60*60*1000;
    var decision = new Date(2017, 7, 8, 23, 59);
    return Math.floor(Math.abs((Date.now() - decision.getTime())/(oneDay)));
})();

$(".days-remaining-number").text(daysRemaining + " days");

/* useful vars */
var supportsSecret = null;

$(".toggle-button-question .toggle-select").click(function() {
  var $this = $(this);

  $(".toggle-button-question .toggle-select").removeClass("selected");
  $this.addClass("selected");
  $("#previewEmail").prop("disabled", false);

  supportsSecret = $this.attr('id') == "yes";
});

/* follow-up questions */
var senderSecret = null,
    emailId = null;

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}

function emailSent() {
  ga('send', 'event', 'secret-ballot-email', 'sent');

  // prep follow up questions
  var questions = [
    {
      q: "Have you ever participated in a protest march?",
      a: ["YES, I have", "NO, I have not"],
    }, {
      q: "Is this your first time emailing a Member of Parliament?",
      a: ["YES, it is", "NO, it is not"],
    }, {
      q: "Do you know that all MPs are assigned a constituency, and represent those who live in it?",
      a: ["YES, I know about that", "NO, I did not know"],
    },
  ];
  var q = questions[getRandomInt(0, questions.length)];

  ga('send', 'event', 'follow-up', 'asked', q.q);
  $('.follow-up-question p').text(q.q);
  $('#follow-up-answer-1').text(q.a[0]);
  $('#follow-up-answer-2').text(q.a[1]);

  // prep sharing
  var msg = supportsSecret ? 'I support' : 'I do not support';
  $('.twitter-share').data('message', 'I just emailed Baleka Mbete saying ' + msg + ' a secret ballot. Send an email and make your voice heard. @MbeteBaleka');
  $('.fb-share').data('message', 'I just emailed Baleka Mbete saying ' + msg + ' a secret ballot. Send an email and make your voice heard.');

  $("#secret-ballot-preview-message").hide();
  $("#secret-ballot-sent").show();
}

$(".follow-up-question-box .toggle-select-follow-up").click(function() {
  var $this = $(this);

  $(".follow-up-question-box .toggle-select-follow-up").removeClass("selected");
  $this.addClass("selected");

  var q = $('.follow-up-question').text().trim();
  var a = $this.text().trim();

  $('.follow-up-question p').text('Thanks!');
  $('.follow-up-answer-box').hide();

  // submit to server
  jQuery.ajax('/api/v1/email/' + emailId + '/qa/', {
    type: 'POST',
    data: {
      question: q,
      answer: a,
      sender_secret: senderSecret,
    },
  });

  ga('send', 'event', 'follow-up', 'answered', q);
});

$("#secret-ballot-preview-message").hide();
$("#secret-ballot-sent").hide();

// global for preview and then send
var emailTxt = "";

$("#previewEmail").click(function(e) {
  e.preventDefault();
  var senderName = $(".name-input").val();
  var senderEmail = $(".email-input").val();

  if (senderName === '') {
    alert('Please enter your name');
    $('.name-input').focus();
    return;
  }

  if (senderEmail === '') {
    alert('Please enter your email');
    $('.email-input').focus();
    return;
  }

  if ($("#comment").val() != "") {
    var emailContent = "\n\nOther issues that concern me about the future of South Africa are:\n\n" + ($("#comment").val().replace(/\n/g, '
'))
  } else {
    var emailContent = "";
  };
  if ($(".toggle-select.selected").attr("id") == "no") {
    var emailSubject = "I do not support a secret ballot in the vote of no confidence";
  }
  else if ($(".toggle-select.selected").attr("id") == "yes") {
    var emailSubject = "I support a secret ballot in the vote of no confidence";
  };
  $("#name").text(senderName);
  $("#email").text(senderEmail);
  $("#email-title").text(emailSubject);

  emailTxt = "Dear Madam Speaker,\n\nI am a citizen of South Africa and I want to let you know that " + emailSubject + " in President Jacob Zuma." + emailContent + "\n\nYou represent all South Africans, including me. Please choose in favour of good governance - a governance that is best suited to realising my hopes for our future.\n\nYours sincerely,\n\n" + senderName;
  emailHtml = emailTxt.replace(/\n/g, '
');

  $("#comment-preview").html(emailHtml);
  $("#secret-ballot-build-message").hide();
  $("#secret-ballot-preview-message").show();
  location.hash = "#secret-ballot-preview-message";
});

$("#editEmail").click(function(e) {
  e.preventDefault();
  $("#secret-ballot-build-message").show();
  $("#secret-ballot-preview-message").hide();
  location.hash = "#email-secret";
});

var reCaptchaValid = false;
var gReCaptchaValidated = function() {
  $("input[type=submit]").removeAttr('disabled');
  reCaptchaValid = true;
};

var gReCaptchaExpired = function() {
  $("input[type=submit]").attr('disabled','disabled');
  reCaptchaValid = false;
};

var recaptchaLoaded = function() {
  grecaptcha.render('recaptcha', {
    'sitekey': recaptchaKey,
    'callback': gReCaptchaValidated,
    'expired-callback': gReCaptchaExpired
  });
  if (typeof pymChild !== undefined) {
    pymChild.sendHeight();
  }
};

var reCaptchaValid = false;
var gReCaptchaValidated = function() {
  $("input[type=submit]").removeAttr('disabled');
  reCaptchaValid = true;
};

var gReCaptchaExpired = function() {
  $("input[type=submit]").attr('disabled','disabled');
  reCaptchaValid = false;
};

var recaptchaLoaded = function() {
  grecaptcha.render('recaptcha', {
    'sitekey': recaptchaKey,
    'callback': gReCaptchaValidated,
    'expired-callback': gReCaptchaExpired
  });
  if (typeof pymChild !== undefined) {
    pymChild.sendHeight();
  }
};

function submitForm(e) {
  e.preventDefault();

  var senderName = $(".name-input").val();
  var senderEmail = $(".email-input").val();
  var emailSubject = $("#email-title").text();

  jQuery.ajax('/api/v1/email/', {
    type: 'POST',
    data: {
      person: recipient.id,
      name: senderName,
      email: senderEmail,
      body: emailTxt,
      subject: emailSubject,
      gRecaptchaResponse: grecaptcha.getResponse(),
    },
    success: function(data) {
      console.info("success", data);

      senderSecret = data.sender_secret;
      emailId = data.secure_id;

      emailSent();
    },
    error: function(jqXHR, textStatus, errorThrown) {
      console.error(jqXHR, textStatus, errorThrown, jqXHR.responseText);
    }
  });
}

$('#email-secret').on('submit', submitForm);

// https://stackoverflow.com/a/901144/1305080
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

function getParentUrl() {
  return getParameterByName('parentUrl');
}

$(function() {
  ga('send', {
    hitType: 'event',
    eventCategory: 'environment',
    eventAction: 'loaded-by-parent-url',
    eventLabel: getParentUrl()
  });
});
<|endoftext|>


<commit_before>
var moment = require("moment");
var util = require("util");

var commands = require("../core/commands");
var drivers = require("./standings").drivers;
var events = require("./events").events;

exports.initialize = function(bot) {
  var game = new Game(bot.database);
  game._initDatabase();

//   bot.addCommand("bet", commands.Command.ALLOW_AUTHED, function(user, params) {
  bot.addCommand("bet", function(user, params) {
    return new Promise(function(resolve, reject) {
      if (params.length != 3) {
        return reject("Need three drivers to bet!");
      }

      params.forEach(function(name) {
        if (name.length < 3) {
          throw new Error("Name length has to be at least three characters");
        }
      });

      if (!game.betsAllowed) {
        var datestr = moment.utc(game.betsOpen).format("MMMM D, HH:mm UTC");
        throw new Error(util.format("Bets will be allowed after %s, until qualifying!", datestr));
      }

      game.bet.apply(game, [user].concat(params)).then(function(reply) {
        resolve(reply);
      }, reject);
    });
  });
};

var Game = function(database) {
  this.database = database;
};

Game.prototype = {
  _initDatabase: function() {
    var db = this.database;

    db.serialize(function() {
      db.run("CREATE TABLE IF NOT EXISTS betgame_bets( \
        round INT NOT NULL, \
        user TEXT NOT NULL, \
        d1 TEXT NOT NULL, \
        d2 TEXT NOT NULL, \
        d3 TEXT NOT NULL, \
        time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, \
        PRIMARY KEY(user, round) \
      )");
    });
  },
  bet: function(user, d1, d2, d3) {
    var game = this;

    return new Promise(function(resolve, reject) {
      game.parseDrivers(d1, d2, d3).then(function(names) {
        game.saveBets(user, names).catch(function(error) {
          console.error(error);
        });

        var joined = names.map((n, i) => (i+1) + ". " + n).join("; ");
        resolve(util.format("%s: %s [OK]", user.nick, joined));
      }, reject);
    });
  },
  parseDrivers: function(d1, d2, d3) {
    var keys = Array.prototype.slice.apply(arguments).map(function(name) {
      return name.toLowerCase();
    });

    return new Promise(function(resolve, reject) {
      drivers.get(true).then(function(data) {
        var names = [null, null, null];

        for (var i = 0; i < keys.length; i++) {
          var d = keys[i];

          for (var j = 0; j < data.length; j++) {
            var row = data[j];
            var surname = row.name.split(" ", 2)[1]
              .toLowerCase()
              .replace("ä", "a")
              .replace("ö", "o");

            if (surname.substring(0, d.length) == d) {
              names[i] = row.name;
              break;
            }
          }

          if (!names[i]) {
            return reject(util.format("Could not find driver for '%s'", d));
          }
        }

        resolve(names);
      });
    });
  },
  saveBets: function(user, names) {
    var game = this;
    var db = this.database;
    var event = events.nextQualifying;

    console.log("save");

    return new Promise(function(resolve, reject) {
      user.whois().then(function(info) {
        try {
          if (!("account" in info)) {
            info.account = "DEMO";
          }

          var sql = "INSERT INTO betgame_bets (round, user, d1, d2, d3) \
              VALUES($round, $user, $d1, $d2, $d3)";

          var params = {
            $round: event.round,
            $user: info.account,
            $d1: names[0],
            $d2: names[1],
            $d3: names[2],
          };

          db.serialize(function() {
            db.run(sql, params, function(err) {
              if (!err) {
                return;
              }
              if (err.errno != 19) {
                console.warn("UNKNOWN DATABASE ERROR:", err);
              }

              sql = "UPDATE betgame_bets SET d1 = $d1, d2 = $d2, d3 = $d3, time=CURRENT_TIMESTAMP \
                WHERE round = $round AND user = $user";

              db.run(sql, params);
            });
          });
        } catch (e) {
          console.error("huoh");
          reject(e);
        }
      }).catch(function(e) {
        console.log("another", e);
      });
    });
  },
};

Object.defineProperties(Game.prototype, {
  betsAllowed: {
    get: function() {
      this.betsOpen > new Date;
    }
  },
  betsOpen: {
    get: function() {
      var event = events.nextQualifying;
      if (event) {
        return moment.utc(event.date).subtract(5, "days").hour(0).toDate();
      }
      return new Date(null);
    }
  }
});
<commit_msg>Fix checking for bets deadline<commit_after>
var moment = require("moment");
var util = require("util");

var commands = require("../core/commands");
var drivers = require("./standings").drivers;
var events = require("./events").events;

exports.initialize = function(bot) {
  var game = new Game(bot.database);
  game._initDatabase();

//   bot.addCommand("bet", commands.Command.ALLOW_AUTHED, function(user, params) {
  bot.addCommand("bet", function(user, params) {
    return new Promise(function(resolve, reject) {
      if (params.length != 3) {
        return reject("Need three drivers to bet!");
      }

      params.forEach(function(name) {
        if (name.length < 3) {
          throw new Error("Name length has to be at least three characters");
        }
      });

      if (!game.betsAllowed) {
        var datestr = moment.utc(game.betsOpen).format("MMMM D, HH:mm UTC");
        throw new Error(util.format("Bets will be allowed after %s, until qualifying!", datestr));
      }

      game.bet.apply(game, [user].concat(params)).then(function(reply) {
        resolve(reply);
      }, reject);
    });
  });
};

var Game = function(database) {
  this.database = database;
};

Game.prototype = {
  _initDatabase: function() {
    var db = this.database;

    db.serialize(function() {
      db.run("CREATE TABLE IF NOT EXISTS betgame_bets( \
        round INT NOT NULL, \
        user TEXT NOT NULL, \
        d1 TEXT NOT NULL, \
        d2 TEXT NOT NULL, \
        d3 TEXT NOT NULL, \
        time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, \
        PRIMARY KEY(user, round) \
      )");
    });
  },
  bet: function(user, d1, d2, d3) {
    var game = this;

    return new Promise(function(resolve, reject) {
      game.parseDrivers(d1, d2, d3).then(function(names) {
        game.saveBets(user, names).catch(function(error) {
          console.error(error);
        });

        var joined = names.map((n, i) => (i+1) + ". " + n).join("; ");
        resolve(util.format("%s: %s [OK]", user.nick, joined));
      }, reject);
    });
  },
  parseDrivers: function(d1, d2, d3) {
    var keys = Array.prototype.slice.apply(arguments).map(function(name) {
      return name.toLowerCase();
    });

    return new Promise(function(resolve, reject) {
      drivers.get(true).then(function(data) {
        var names = [null, null, null];

        for (var i = 0; i < keys.length; i++) {
          var d = keys[i];

          for (var j = 0; j < data.length; j++) {
            var row = data[j];
            var surname = row.name.split(" ", 2)[1]
              .toLowerCase()
              .replace("ä", "a")
              .replace("ö", "o");

            if (surname.substring(0, d.length) == d) {
              names[i] = row.name;
              break;
            }
          }

          if (!names[i]) {
            return reject(util.format("Could not find driver for '%s'", d));
          }
        }

        resolve(names);
      });
    });
  },
  saveBets: function(user, names) {
    var game = this;
    var db = this.database;
    var event = events.nextQualifying;

    console.log("save");

    return new Promise(function(resolve, reject) {
      user.whois().then(function(info) {
        try {
          if (!("account" in info)) {
            info.account = "DEMO";
          }

          var sql = "INSERT INTO betgame_bets (round, user, d1, d2, d3) \
              VALUES($round, $user, $d1, $d2, $d3)";

          var params = {
            $round: event.round,
            $user: info.account,
            $d1: names[0],
            $d2: names[1],
            $d3: names[2],
          };

          db.serialize(function() {
            db.run(sql, params, function(err) {
              if (!err) {
                return;
              }
              if (err.errno != 19) {
                console.warn("UNKNOWN DATABASE ERROR:", err);
              }

              sql = "UPDATE betgame_bets SET d1 = $d1, d2 = $d2, d3 = $d3, time=CURRENT_TIMESTAMP \
                WHERE round = $round AND user = $user";

              db.run(sql, params);
            });
          });
        } catch (e) {
          console.error("huoh");
          reject(e);
        }
      }).catch(function(e) {
        console.log("another", e);
      });
    });
  },
};

Object.defineProperties(Game.prototype, {
  betsAllowed: {
    get: function() {
      return this.betsOpen < new Date;
    }
  },
  betsOpen: {
    get: function() {
      var event = events.nextQualifying;
      if (event) {
        return moment.utc(event.date).subtract(5, "days").hour(0).toDate();
      }
      return null;
    }
  }
});
<|endoftext|>


<commit_before>import UAParser from 'ua-parser-js';

const uaParser = new UAParser();
const ua = uaParser.getResult();

export const hasModulesSupport = () => {
    const script = document.createElement('script');
    return 'noModule' in script;
};

export const isFileSaverSupported = () => !!new Blob();

export const textToClipboard = (text) => {
    const dummy = document.createElement('textarea');

    document.body.appendChild(dummy);
    dummy.value = text;
    dummy.select();
    document.execCommand('copy');
    document.body.removeChild(dummy);
};

export const getOS = () => {
    const { name = 'other', version = '' } = ua.os;
    return { name, version };
};

export const isDuckDuckGo = () => navigator.userAgent.includes('DuckDuckGo');
export const isSafari = () => ua.browser.name === 'Safari' || ua.browser.name === 'Mobile Safari';
export const isSafariMobile = () => ua.browser.name === 'Mobile Safari';
export const isIE11 = () => ua.browser.name === 'IE' && ua.browser.major === '11';
export const isEdge = () => ua.browser.name === 'Edge';
export const isFirefox = () => ua.browser.name === 'Firefox';
export const isChrome = () => ua.browser.name === 'Chrome';
export const isMac = () => ua.os.name === 'Mac OS';
export const hasTouch = 'ontouchstart' in document.documentElement;
export const hasCookie = () => navigator.cookieEnabled;
export const getBrowser = () => ua.browser;
export const getDevice = () => ua.device;
export const isMobile = () => {
    const { type } = getDevice();
    return type === 'mobile';
};

export const doNotTrack = () => {
    return (
        navigator.doNotTrack === '1' ||
        navigator.doNotTrack === 'yes' ||
        navigator.msDoNotTrack === '1' ||
        window.doNotTrack === '1'
    );
};

/**
 * Do not support window.open event after user interaction
 * @returns {Boolean}
 */
export const doNotWindowOpen = () => {
    return isDuckDuckGo();
};

export const parseURL = (url = '') => {
    const parser = document.createElement('a');
    const searchObject = {};
    // Let the browser do the work
    parser.href = url;
    // Convert query string to object
    const queries = parser.search.replace(/^\?/, '').split('&');

    for (let i = 0; i < queries.length; i++) {
        const [key, value] = queries[i].split('=');
        searchObject[key] = value;
    }

    return {
        protocol: parser.protocol,
        host: parser.host,
        hostname: parser.hostname,
        port: parser.port,
        pathname: parser.pathname,
        search: parser.search,
        searchObject,
        hash: parser.hash
    };
};

export const getActiveXObject = (name) => {
    try {
        // eslint-disable-next-line no-undef
        return new ActiveXObject(name);
    } catch (error) {
        // eslint-disable-next-line no-console
        console.error(error);
    }
};

export const isIos = () => /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
export const hasAcrobatInstalled = () => getActiveXObject('AcroPDF.PDF') || getActiveXObject('PDF.PdfCtrl');
export const hasPDFSupport = () => navigator.mimeTypes['application/pdf'] || hasAcrobatInstalled() || isIos();
export const redirectTo = (url = '') => document.location.replace(`${document.location.origin}${url}`);

/**
 * Detect browser requiring direct action
 * Like opening a new tab
 * @returns {Boolean}
 */
export const requireDirectAction = () => isSafari() || isFirefox() || isEdge();
<commit_msg>Detect edge chromium browser<commit_after>import UAParser from 'ua-parser-js';

const uaParser = new UAParser();
const ua = uaParser.getResult();

export const hasModulesSupport = () => {
    const script = document.createElement('script');
    return 'noModule' in script;
};

export const isFileSaverSupported = () => !!new Blob();

export const textToClipboard = (text) => {
    const dummy = document.createElement('textarea');

    document.body.appendChild(dummy);
    dummy.value = text;
    dummy.select();
    document.execCommand('copy');
    document.body.removeChild(dummy);
};

export const getOS = () => {
    const { name = 'other', version = '' } = ua.os;
    return { name, version };
};

export const isDuckDuckGo = () => navigator.userAgent.includes('DuckDuckGo');
export const isSafari = () => ua.browser.name === 'Safari' || ua.browser.name === 'Mobile Safari';
export const isSafariMobile = () => ua.browser.name === 'Mobile Safari';
export const isIE11 = () => ua.browser.name === 'IE' && ua.browser.major === '11';
export const isEdge = () => ua.browser.name === 'Edge';
export const isEdgeChromium = () => isEdge() && ua.engine.name === 'Blink';
export const isFirefox = () => ua.browser.name === 'Firefox';
export const isChrome = () => ua.browser.name === 'Chrome';
export const isMac = () => ua.os.name === 'Mac OS';
export const hasTouch = 'ontouchstart' in document.documentElement;
export const hasCookie = () => navigator.cookieEnabled;
export const getBrowser = () => ua.browser;
export const getDevice = () => ua.device;
export const isMobile = () => {
    const { type } = getDevice();
    return type === 'mobile';
};

export const doNotTrack = () => {
    return (
        navigator.doNotTrack === '1' ||
        navigator.doNotTrack === 'yes' ||
        navigator.msDoNotTrack === '1' ||
        window.doNotTrack === '1'
    );
};

/**
 * Do not support window.open event after user interaction
 * @returns {Boolean}
 */
export const doNotWindowOpen = () => {
    return isDuckDuckGo();
};

export const parseURL = (url = '') => {
    const parser = document.createElement('a');
    const searchObject = {};
    // Let the browser do the work
    parser.href = url;
    // Convert query string to object
    const queries = parser.search.replace(/^\?/, '').split('&');

    for (let i = 0; i < queries.length; i++) {
        const [key, value] = queries[i].split('=');
        searchObject[key] = value;
    }

    return {
        protocol: parser.protocol,
        host: parser.host,
        hostname: parser.hostname,
        port: parser.port,
        pathname: parser.pathname,
        search: parser.search,
        searchObject,
        hash: parser.hash
    };
};

export const getActiveXObject = (name) => {
    try {
        // eslint-disable-next-line no-undef
        return new ActiveXObject(name);
    } catch (error) {
        // eslint-disable-next-line no-console
        console.error(error);
    }
};

export const isIos = () => /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
export const hasAcrobatInstalled = () => getActiveXObject('AcroPDF.PDF') || getActiveXObject('PDF.PdfCtrl');
export const hasPDFSupport = () => navigator.mimeTypes['application/pdf'] || hasAcrobatInstalled() || isIos();
export const redirectTo = (url = '') => document.location.replace(`${document.location.origin}${url}`);

/**
 * Detect browser requiring direct action
 * Like opening a new tab
 * @returns {Boolean}
 */
export const requireDirectAction = () => isSafari() || isFirefox() || isEdge();
<|endoftext|>


<commit_before>// displays security suggestion depending on information found in the model
const printMsgHTML = require('../helpers/printMsgHTML.js')

// button to show the ID of the nodes
const showIDBtn = `<button id='id-button' class='menu-btn' style='color: var(--main-tx-color); background-color: var(--main-bg-color); width: 120px; height: 25px;'>show nodes ID</button>`

// contains the attribute/connection patterns and the suggestions
const list = {
  s0: {
    concept: 'device',
    layer: 'perception',
    suggestion: 'Devices in the perception layer require physical security.'
  },
  s1: {
    concept: 'network connection',
    description: 'wireless',
    suggestion:
      'Wireless connections are subject to information disclosure attacks. Use encrypted protocols.'
  },
  s2: {
    concept: 'device',
    update: 'false',
    suggestion: 'Treat devices that cannot be updated as compromised.'
  },
  s3: {
    concept: 'application',
    update: 'false',
    suggestion: 'Treat applications that cannot be updated as compromised.'
  }
}

// find nodes of interest based on the data of the list
// @node: node instance in the graph
// @concept: node concept in the suggestion array
// @graphAttribute: attribute in the graph that will be compared
// @attribute: attribute in the suggestion array
// @nodeArray: array that will store the insecure nodes
const findNodes = (node, concept, graphAttribute, attribute, nodeArray) => {
  // compare the graph nodes will the suggestions
  if (node.data().asto.concept === concept && graphAttribute === attribute) {
    // apply css rules in the graph
    node.removeClass('faded')
    node.addClass('attention')

    // push ID of the insecure nodes in the array
    nodeArray.push(node.data().id)
  }
}

// displays the nodes of interest and the suggestion
const showResults = (nodeArray, suggestion) => {
  // only show the suggestion if the node array is not empty
  if (nodeArray.length !== 0) {
    printMsgHTML(
      `Nodes ID: <strong>${nodeArray}</strong> <br><br>${suggestion}`
    )
  }
}

module.exports = function suggestion (cy) {
  // fade out all the nodes
  cy.elements().addClass('faded')

  // arrays to store the nodes of interest of each suggestion
  let s0nodes = []
  let s1nodes = []
  let s2nodes = []
  let s3nodes = []

  cy.nodes().map(node => {
    let nodeData = node.data().asto

    // s0 suggestion
    findNodes(node, list.s0.concept, nodeData.layer, list.s0.layer, s0nodes)
    // s1 suggestion
    findNodes(
      node,
      list.s1.concept,
      nodeData.description,
      list.s1.description,
      s1nodes
    )
    // s2 suggestion
    findNodes(node, list.s2.concept, nodeData.update, list.s2.update, s2nodes)
    // s3 suggestion
    findNodes(node, list.s3.concept, nodeData.update, list.s3.update, s3nodes)
  })

  // display the suggestions on the message area
  showResults(s0nodes, list.s0.suggestion) // s0 suggestion
  showResults(s1nodes, list.s1.suggestion) // s1 suggestion
  showResults(s2nodes, list.s2.suggestion) // s2 suggestion
  showResults(s3nodes, list.s3.suggestion) // s3 suggestion

  // render the show ID button
  printMsgHTML(showIDBtn)
  const showIdNodeBtn = document.getElementById('id-button')
  showIdNodeBtn.addEventListener('click', () => {
    cy.nodes().removeClass('label-nodes')
    cy.nodes().removeClass('label-dsc')
    cy.nodes().addClass('label-id')
  })
}
<commit_msg>:hammer: refactoring<commit_after>// displays security suggestion depending on information found in the model
const printMsgHTML = require('../helpers/printMsgHTML.js')

// button to show the ID of the nodes
const showIDBtn = `<button id='id-button' class='menu-btn' style='color: var(--main-tx-color); background-color: var(--main-bg-color); width: 120px; height: 25px;'>show nodes ID</button>`

// contains the attribute/connection patterns and the suggestions
const list = {
  s0: {
    concept: 'device',
    layer: 'perception',
    suggestion: 'Devices in the perception layer require physical security.'
  },
  s1: {
    concept: 'device',
    update: 'false',
    suggestion: 'Treat devices that cannot be updated as compromised.'
  },
  s2: {
    concept: 'network connection',
    description: 'wireless',
    suggestion:
      'Wireless connections are subject to information disclosure attacks. Use encrypted protocols.'
  },
  s3: {
    concept: 'application',
    update: 'false',
    suggestion: 'Treat applications that cannot be updated as compromised.'
  }
}

// find nodes of interest based on the data of the list
// @node: node instance in the graph
// @concept: node concept in the suggestion array
// @graphAttribute: attribute in the graph that will be compared
// @attribute: attribute in the suggestion array
// @nodeArray: array that will store the insecure nodes
const findNodes = (node, concept, graphAttribute, attribute, nodeArray) => {
  // compare the graph nodes will the suggestions
  if (node.data().asto.concept === concept && graphAttribute === attribute) {
    // apply css rules in the graph
    node.removeClass('faded')
    node.addClass('attention')

    // push ID of the insecure nodes in the array
    nodeArray.push(node.data().id)
  }
}

// displays the nodes of interest and the suggestion
const showResults = (nodeArray, suggestion) => {
  // only show the suggestion if the node array is not empty
  if (nodeArray.length !== 0) {
    printMsgHTML(
      `Nodes: <strong>${nodeArray}</strong> <br><br>${suggestion}`
    )
  }
}

module.exports = function suggestion (cy) {
  // fade out all the nodes
  cy.elements().addClass('faded')

  // arrays to store the nodes of interest of each suggestion
  let s0nodes = []
  let s1nodes = []
  let s2nodes = []
  let s3nodes = []

  cy.nodes().map(node => {
    let nodeData = node.data().asto

    // s0 suggestion
    findNodes(node, list.s0.concept, nodeData.layer, list.s0.layer, s0nodes)
    // s1 suggestion
    findNodes(
      node,
      list.s1.concept,
      nodeData.update,
      list.s1.update,
      s1nodes
    )
    // s2 suggestion
    findNodes(node, list.s2.concept, nodeData.description, list.s2.description, s2nodes)
    // s3 suggestion
    findNodes(node, list.s3.concept, nodeData.update, list.s3.update, s3nodes)
  })

  // display the suggestions on the message area
  showResults(s0nodes, list.s0.suggestion) // s0 suggestion
  showResults(s1nodes, list.s1.suggestion) // s1 suggestion
  showResults(s2nodes, list.s2.suggestion) // s2 suggestion
  showResults(s3nodes, list.s3.suggestion) // s3 suggestion

  // render the show ID button
  printMsgHTML(showIDBtn)
  const showIdNodeBtn = document.getElementById('id-button')
  showIdNodeBtn.addEventListener('click', () => {
    cy.nodes().removeClass('label-nodes')
    cy.nodes().removeClass('label-dsc')
    cy.nodes().addClass('label-id')
  })
}
<|endoftext|>


<commit_before>import { stringify } from '../config/soyaConfig';

export default {
  presets: [
    require.resolve('next/babel'),
  ],
  plugins: [
    [
      require.resolve('styled-modules/babel'),
      {
        pattern: /\.(css|s(a|c)ss)$/,
      },
    ],
    [
      require.resolve('babel-plugin-transform-define'),
      stringify(),
    ],
  ],
};
<commit_msg>Remove next babel preset<commit_after>import { stringify } from '../config/soyaConfig';

export default {
  plugins: [
    [
      require.resolve('styled-modules/babel'),
      {
        pattern: /\.(css|s(a|c)ss)$/,
      },
    ],
    [
      require.resolve('babel-plugin-transform-define'),
      stringify(),
    ],
  ],
};
<|endoftext|>