<commit_before>//The store is an event emitter.
var EventEmitter = require('events').EventEmitter;
var assign = require('object-assign');
var {isArray, isEmpty, isObject, isFunction} = require('lodash/lang');
var {defer} = require('lodash/function');
var getEntityInformations = require('../definition/entity/builder').getEntityInformations;
var capitalize = require('lodash/string/capitalize');
var Immutable = require('immutable');
var AppDispatcher = require('../dispatcher');
/**
 * @class CoreStore
 */
class CoreStore extends EventEmitter {

  /**
   * Contructor of the store class.
   */
  constructor(config) {
    assign(this, {
      config
    });
    //Initialize the data as immutable map.
    this.data = Immutable.Map({});
    this.status = Immutable.Map({});
    this.error = Immutable.Map({});
    this.callerId = undefined;
    this.pendingEvents = [];
    this.customHandler = assign({}, config.customHandler);
    //Register all gernerated methods.
    this.buildDefinition();
    this.buildEachNodeChangeEventListener();
    this.registerDispatcher();
  }

  /**
   * Initialize the store configuration.
   * @param {object} storeConfiguration - The store configuration for the initialization.
   */
  buildDefinition() {
      /**
       * Build the definitions for the entity (may be a subject.)
       * @type {object}
       */
      this.definition = this.config.definition || getEntityInformations(
        this.config.definitionPath,
        this.config.customDefinition
      );
      return this.definition;
  }
  /** Return the status of a definition.
   * @returns {string} - The status of a definition.
   */
  getStatus(def){
    if (this.status.has(def)){
      return this.status.get(def);
    }
    return undefined;
  }
  /**
   * Emit all events pending in the pendingEvents map.
   */
  emitPendingEvents(){
    this.pendingEvents.map((evtToEmit)=>{
      this.emit(evtToEmit.name, evtToEmit.data);
    });
  }

  /**
   * Replace the emit function with a willEmit in otder to store the changing event but send it afterwards.
   * @param eventName {string} - The event name.
   * @param  data {object} - The event's associated data.
   */
  willEmit(eventName, data){
    this.pendingEvents.push({name: eventName, data: data});
  }

  /**
   * Clear all pending events.
   */
  clearPendingEvents(){
    this.pendingEvents = [];
  }
  /**
  * Build a change listener for each property in the definition. (should be macro entities);
  */
  buildEachNodeChangeEventListener() {
    var currentStore = this;
      //Loop through each store properties.
      for (var definition in this.definition) {
        var capitalizeDefinition = capitalize(definition);
        //Creates the change listener
        currentStore[`add${capitalizeDefinition}ChangeListener`] = function(def){
          return function (cb) {
            currentStore.addListener(`${def}:change`, cb);
        }}(definition);
        //Remove the change listener
        currentStore[`remove${capitalizeDefinition}ChangeListener`] = function(def){
          return function (cb) {
            currentStore.removeListener(`${def}:change`, cb);
        }}(definition);
        //Create an update method.
        if(currentStore[`update${capitalizeDefinition}`] === undefined){
          currentStore[`update${capitalizeDefinition}`] = function(def){
            return function (dataNode, status, informations) {
              var immutableNode = isFunction(dataNode) ? dataNode : Immutable.fromJS(dataNode);
              currentStore.data = currentStore.data.set(def, immutableNode);
              //Update the status on the data.
              currentStore.status = currentStore.status.set(def, status);

              currentStore.willEmit(`${def}:change`, {property: def, status: status, informations: informations});
          }}(definition);
        }

        //Create a get method.
        if(currentStore[`get${capitalizeDefinition}`] === undefined){
          currentStore[`get${capitalizeDefinition}`] = function(def){
            return function () {
              var hasData = currentStore.data.has(def);
              if(hasData){
                var rawData = currentStore.data.get(def);
                //If the store node isn't an object, immutable solution are non sens.
                if(isFunction(rawData) || !isObject(rawData)){
                  return rawData;
                }
                else {
                  var data = rawData.toJS();
                  if(!isEmpty(data)){
                    return data;
                  }
                }
              }
              return undefined;
            };
          }(definition);
        }
        //Creates the error change listener
        currentStore[`add${capitalizeDefinition}ErrorListener`] = function(def){
            return function (cb) {
              currentStore.addListener(`${def}:error`, cb);
        }}(definition);
        //Remove the change listener
        currentStore[`remove${capitalizeDefinition}ErrorListener`] = function(def){
            return function (cb) {
              currentStore.removeListener(`${def}:error`, cb);
        }}(definition);
        //Create an update method.
        currentStore[`updateError${capitalizeDefinition}`] = function(def){
            return function (dataNode) {
              //CheckIsObject
              var immutableNode = Immutable[isArray(dataNode) ? "List" : "Map"](dataNode);
              currentStore.error = currentStore.error.set(def, immutableNode);
              currentStore.willEmit(`${def}:error`);
        }}(definition);
        //Create a get method.
        currentStore[`getError${capitalizeDefinition}`] = function(def){
            return function(){
              var hasData = currentStore.error.has(def);
              return hasData ? currentStore.error.get(def).toJS() : undefined;
            };
        }(definition);
      }
    }

  delayPendingEvents(context){
    //Delay all the change emit by the store to be sure it is done after the internal store propagation and to go out of the dispatch function.
    defer(()=>{
      context.emitPendingEvents();
      context.clearPendingEvents();
    });
  }
  _buildInformations(incomingInfos){
    return {
      callerId : incomingInfos.action.callerId
    }
  }
  /**
   * The store registrer itself on the dispatcher.
   */
  registerDispatcher(){
    var currentStore = this;
    this.dispatch = AppDispatcher.register(function(transferInfo) {

      //currentStore.clearPendingEvents();
      if(currentStore.globalCustomHandler){
        return currentStore.globalCustomHandler.call(currentStore, transferInfo);
      }

      //Read data from the action transfer information.
      var rawData = transferInfo.action.data;
      var status = transferInfo.action.status || {};
      var type = transferInfo.action.type;
      var otherInformations = this._buildInformations(transferInfo);

      //Call each node handler for the matching definition's node.
      for(var node in rawData){
        if(currentStore.definition[node]){
          //Call a custom handler if this exists.
          if(currentStore.customHandler && currentStore.customHandler[node] && currentStore.customHandler[node][type]){
            currentStore.customHandler[node][type].call(currentStore, rawData[node], status[node], otherInformations);
          }else {
            //Update the data for the given node. and emit the change/.
            currentStore[`${type}${capitalize(node)}`](rawData[node], status[node], );
          }
        }
      }
      currentStore.delayPendingEvents(currentStore);
    });
  }
    /**
     * Add a listener on a store event.
     * @param {string}   eventName - Event name.
     * @param {Function} cb - CallBack to call on the event change name.
     */
  addListener(eventName, cb) {
    this.on(eventName, cb);
  }

}
module.exports = CoreStore;
<commit_msg>[core-store] Add the intormation in both customUpdate and UpdateData<commit_after>//The store is an event emitter.
var EventEmitter = require('events').EventEmitter;
var assign = require('object-assign');
var {isArray, isEmpty, isObject, isFunction} = require('lodash/lang');
var {defer} = require('lodash/function');
var getEntityInformations = require('../definition/entity/builder').getEntityInformations;
var capitalize = require('lodash/string/capitalize');
var Immutable = require('immutable');
var AppDispatcher = require('../dispatcher');
/**
 * @class CoreStore
 */
class CoreStore extends EventEmitter {

  /**
   * Contructor of the store class.
   */
  constructor(config) {
    assign(this, {
      config
    });
    //Initialize the data as immutable map.
    this.data = Immutable.Map({});
    this.status = Immutable.Map({});
    this.error = Immutable.Map({});
    this.callerId = undefined;
    this.pendingEvents = [];
    this.customHandler = assign({}, config.customHandler);
    //Register all gernerated methods.
    this.buildDefinition();
    this.buildEachNodeChangeEventListener();
    this.registerDispatcher();
  }

  /**
   * Initialize the store configuration.
   * @param {object} storeConfiguration - The store configuration for the initialization.
   */
  buildDefinition() {
      /**
       * Build the definitions for the entity (may be a subject.)
       * @type {object}
       */
      this.definition = this.config.definition || getEntityInformations(
        this.config.definitionPath,
        this.config.customDefinition
      );
      return this.definition;
  }
  /** Return the status of a definition.
   * @returns {string} - The status of a definition.
   */
  getStatus(def){
    if (this.status.has(def)){
      return this.status.get(def);
    }
    return undefined;
  }
  /**
   * Emit all events pending in the pendingEvents map.
   */
  emitPendingEvents(){
    this.pendingEvents.map((evtToEmit)=>{
      this.emit(evtToEmit.name, evtToEmit.data);
    });
  }

  /**
   * Replace the emit function with a willEmit in otder to store the changing event but send it afterwards.
   * @param eventName {string} - The event name.
   * @param  data {object} - The event's associated data.
   */
  willEmit(eventName, data){
    this.pendingEvents.push({name: eventName, data: data});
  }

  /**
   * Clear all pending events.
   */
  clearPendingEvents(){
    this.pendingEvents = [];
  }
  /**
  * Build a change listener for each property in the definition. (should be macro entities);
  */
  buildEachNodeChangeEventListener() {
    var currentStore = this;
      //Loop through each store properties.
      for (var definition in this.definition) {
        var capitalizeDefinition = capitalize(definition);
        //Creates the change listener
        currentStore[`add${capitalizeDefinition}ChangeListener`] = function(def){
          return function (cb) {
            currentStore.addListener(`${def}:change`, cb);
        }}(definition);
        //Remove the change listener
        currentStore[`remove${capitalizeDefinition}ChangeListener`] = function(def){
          return function (cb) {
            currentStore.removeListener(`${def}:change`, cb);
        }}(definition);
        //Create an update method.
        if(currentStore[`update${capitalizeDefinition}`] === undefined){
          currentStore[`update${capitalizeDefinition}`] = function(def){
            return function (dataNode, status, informations) {
              var immutableNode = isFunction(dataNode) ? dataNode : Immutable.fromJS(dataNode);
              currentStore.data = currentStore.data.set(def, immutableNode);
              //Update the status on the data.
              currentStore.status = currentStore.status.set(def, status);

              currentStore.willEmit(`${def}:change`, {property: def, status: status, informations: informations});
          }}(definition);
        }

        //Create a get method.
        if(currentStore[`get${capitalizeDefinition}`] === undefined){
          currentStore[`get${capitalizeDefinition}`] = function(def){
            return function () {
              var hasData = currentStore.data.has(def);
              if(hasData){
                var rawData = currentStore.data.get(def);
                //If the store node isn't an object, immutable solution are non sens.
                if(isFunction(rawData) || !isObject(rawData)){
                  return rawData;
                }
                else {
                  var data = rawData.toJS();
                  if(!isEmpty(data)){
                    return data;
                  }
                }
              }
              return undefined;
            };
          }(definition);
        }
        //Creates the error change listener
        currentStore[`add${capitalizeDefinition}ErrorListener`] = function(def){
            return function (cb) {
              currentStore.addListener(`${def}:error`, cb);
        }}(definition);
        //Remove the change listener
        currentStore[`remove${capitalizeDefinition}ErrorListener`] = function(def){
            return function (cb) {
              currentStore.removeListener(`${def}:error`, cb);
        }}(definition);
        //Create an update method.
        currentStore[`updateError${capitalizeDefinition}`] = function(def){
            return function (dataNode) {
              //CheckIsObject
              var immutableNode = Immutable[isArray(dataNode) ? "List" : "Map"](dataNode);
              currentStore.error = currentStore.error.set(def, immutableNode);
              currentStore.willEmit(`${def}:error`);
        }}(definition);
        //Create a get method.
        currentStore[`getError${capitalizeDefinition}`] = function(def){
            return function(){
              var hasData = currentStore.error.has(def);
              return hasData ? currentStore.error.get(def).toJS() : undefined;
            };
        }(definition);
      }
    }

  delayPendingEvents(context){
    //Delay all the change emit by the store to be sure it is done after the internal store propagation and to go out of the dispatch function.
    defer(()=>{
      context.emitPendingEvents();
      context.clearPendingEvents();
    });
  }
  _buildInformations(incomingInfos){
    return {
      callerId : incomingInfos.action.callerId
    }
  }
  /**
   * The store registrer itself on the dispatcher.
   */
  registerDispatcher(){
    var currentStore = this;
    this.dispatch = AppDispatcher.register(function(transferInfo) {

      //currentStore.clearPendingEvents();
      if(currentStore.globalCustomHandler){
        return currentStore.globalCustomHandler.call(currentStore, transferInfo);
      }

      //Read data from the action transfer information.
      var rawData = transferInfo.action.data;
      var status = transferInfo.action.status || {};
      var type = transferInfo.action.type;
      var otherInformations = this._buildInformations(transferInfo);

      //Call each node handler for the matching definition's node.
      for(var node in rawData){
        if(currentStore.definition[node]){
          //Call a custom handler if this exists.
          if(currentStore.customHandler && currentStore.customHandler[node] && currentStore.customHandler[node][type]){
            currentStore.customHandler[node][type].call(currentStore, rawData[node], status[node], otherInformations);
          }else {
            //Update the data for the given node. and emit the change/.
            currentStore[`${type}${capitalize(node)}`](rawData[node], status[node], otherInformations);
          }
        }
      }
      currentStore.delayPendingEvents(currentStore);
    });
  }
    /**
     * Add a listener on a store event.
     * @param {string}   eventName - Event name.
     * @param {Function} cb - CallBack to call on the event change name.
     */
  addListener(eventName, cb) {
    this.on(eventName, cb);
  }

}
module.exports = CoreStore;
<|endoftext|>


<commit_before>var gulp = require('gulp'),
  sass = require('gulp-ruby-sass');

// Styles
require('gulp/tasks/styles')(gulp);
require('gulp/tasks/sass')(gulp);

// Scripts
require('gulp/tasks/copyScriptsToAssets')(gulp);
require('gulp/tasks/rjs')(gulp);
require('gulp/tasks/react')(gulp);

// Images
require('gulp/tasks/images')(gulp);

// Misc
require('gulp/tasks/clean')(gulp);
require('gulp/tasks/watch')(gulp);

gulp.task('default', ['clean'], function () {
  gulp.start('sass', 'copyScriptsToAssets', 'react', 'images');
});
<commit_msg>Relative urls in gulpfile<commit_after>var gulp = require('gulp'),
  sass = require('gulp-ruby-sass');

// Styles
require('./gulp/tasks/styles')(gulp);
require('./gulp/tasks/sass')(gulp);

// Scripts
require('./gulp/tasks/copyScriptsToAssets')(gulp);
require('./gulp/tasks/rjs')(gulp);
require('./gulp/tasks/react')(gulp);

// Images
require('./gulp/tasks/images')(gulp);

// Misc
require('./gulp/tasks/clean')(gulp);
require('./gulp/tasks/watch')(gulp);

gulp.task('default', ['clean'], function () {
  gulp.start('sass', 'copyScriptsToAssets', 'react', 'images');
});
<|endoftext|>


<commit_before>// Gulp Tasks
'use strict';

var gulp = require('gulp'),
    merge = require('merge-stream'),
    sass = require('gulp-ruby-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    cssnano = require('gulp-cssnano'),
    jshint = require('gulp-jshint'),
    uglify = require('gulp-uglify'),
    imagemin = require('gulp-imagemin'),
    rename = require('gulp-rename'),
    concat = require('gulp-concat'),
    notify = require('gulp-notify'),
    cache = require('gulp-cache'),
    livereload = require('gulp-livereload'),
    del = require('del'),
    connect = require('gulp-connect'),
    htmlmin = require('gulp-html-minifier'),
    fs = require('fs'),
    connectModRewrite = require('connect-modrewrite'),
    ngConfig = require('gulp-ng-config'),
    prettyError = require('gulp-prettyerror'),
    // path = require('gulp-path'),
    // conf = require('./conf')(gulp),
    _ = require('lodash');

var scripts = require('./frontend/app.scripts.json');
var styles = require('./frontend/app.styles.json');

//include all bower scripts files
gulp.task('vendorjs', function() {

    _.forIn(scripts.chunks, function(chunkScripts, chunkName) {
        var paths = [];
        chunkScripts.forEach(function(script) {
            var scriptFileName = scripts.paths[script];

            if (!fs.existsSync(__dirname + '/' + scriptFileName)) {

                throw console.error('Required path doesn\'t exist: ' + __dirname + '/' + scriptFileName, script)
            }
            paths.push(scriptFileName);
        });
        gulp.src(paths)
            .pipe(concat(chunkName + '.js'))
            //.on('error', swallowError)
            .pipe(gulp.dest("frontend/dist/vendors"))
    })

});

//include all bower  styles files
gulp.task('vendorcss', function() {

    _.forIn(styles.chunks, function(chunkStyles, chunkName) {
        var paths = [];
        chunkStyles.forEach(function(style) {
            var styleFileName = styles.paths[style];

            if (!fs.existsSync(__dirname + '/' + styleFileName)) {

                throw console.error('Required path doesn\'t exist: ' + __dirname + '/' + styleFileName, style)
            }
            paths.push(styleFileName);
        });
        gulp.src(paths)
            .pipe(concat(chunkName + '.css'))
            //.on('error', swallowError)
            .pipe(gulp.dest("frontend/dist/vendors"))
    })

});

// config for dev server
gulp.task('configDev', function() {
    gulp.src('frontend/src/js/config.json')
        .pipe(ngConfig('evalai-config', {
            environment: 'local'
        }))
        .pipe(gulp.dest('frontend/dist/js'))
});

// config for prod server
gulp.task('configProd', function() {
    gulp.src('frontend/src/js/config.json')
        .pipe(ngConfig('evalai-config', {
            environment: 'production'
        }))
        .pipe(gulp.dest('frontend/dist/js'))
});

// minify and compress CSS files
gulp.task('css', function() {
    return sass('frontend/src/css/main.scss', { style: 'expanded' })
        .pipe(prettyError())
        .pipe(autoprefixer('last 2 version'))
        .pipe(gulp.dest('frontend/dist/css'))
        .pipe(rename({ suffix: '.min' }))
        .pipe(cssnano())
        .pipe(gulp.dest('frontend/dist/css'));
})

// minify angular scripts
gulp.task('js', function() {

    var app = gulp.src('frontend/src/js/app.js')
        .pipe(prettyError())
        .pipe(jshint.reporter('default'))
        .pipe(concat('app.js'))
        .pipe(gulp.dest('frontend/dist/js'))
        .pipe(rename({ suffix: '.min' }))
        .pipe(uglify())
        .pipe(gulp.dest('frontend/dist/js'));

    var configs = gulp.src('frontend/src/js/route-config/*.js')
        .pipe(prettyError())
        .pipe(jshint.reporter('default'))
        .pipe(concat('route-config.js'))
        .pipe(gulp.dest('frontend/dist/js'))
        .pipe(rename({ suffix: '.min' }))
        .pipe(uglify())
        .pipe(gulp.dest('frontend/dist/js'));

    var controllers = gulp.src('frontend/src/js/controllers/*.js')
        .pipe(prettyError())
        .pipe(jshint.reporter('default'))
        .pipe(concat('controllers.js'))
        .pipe(gulp.dest('frontend/dist/js'))
        .pipe(rename({ suffix: '.min' }))
        .pipe(uglify())
        .pipe(gulp.dest('frontend/dist/js'));

    var directives = gulp.src('frontend/src/js/directives/*.js')
        .pipe(prettyError())
        .pipe(jshint.reporter('default'))
        .pipe(concat('directives.js'))
        .pipe(gulp.dest('frontend/dist/js'))
        .pipe(rename({ suffix: '.min' }))
        .pipe(uglify())
        .pipe(gulp.dest('frontend/dist/js'));

    var filters = gulp.src('frontend/src/js/filters/*.js')
        .pipe(prettyError())
        .pipe(jshint.reporter('default'))
        .pipe(concat('filters.js'))
        .pipe(gulp.dest('frontend/dist/js'))
        .pipe(rename({ suffix: '.min' }))
        .pipe(uglify())
        .pipe(gulp.dest('frontend/dist/js'));

    var services = gulp.src('frontend/src/js/services/*.js')
        .pipe(prettyError())
        .pipe(jshint.reporter('default'))
        .pipe(concat('services.js'))
        .pipe(gulp.dest('frontend/dist/js'))
        .pipe(rename({ suffix: '.min' }))
        .pipe(uglify())
        .pipe(gulp.dest('frontend/dist/js'));

    return merge(app, configs, controllers, directives, filters, services)
});

// minify and compress html files
gulp.task('html', function() {

    var webViews = gulp.src('frontend/src/views/web/*.html')
        .pipe(htmlmin({ collapseWhitespace: true }))
        .pipe(gulp.dest('frontend/dist/views/web'));

    var webPartials = gulp.src('frontend/src/views/web/partials/*.html')
        .pipe(htmlmin({ collapseWhitespace: true }))
        .pipe(gulp.dest('frontend/dist/views/web/partials'));

    var challengePartials = gulp.src('frontend/src/views/web/challenge/*.html')
        .pipe(htmlmin({ collapseWhitespace: true }))
        .pipe(gulp.dest('frontend/dist/views/web/challenge'));

    var webErrors = gulp.src('frontend/src/views/web/error-pages/*.html')
        .pipe(htmlmin({ collapseWhitespace: true }))
        .pipe(gulp.dest('frontend/dist/views/web/error-pages'));

    return merge(webViews, webPartials, challengePartials, webErrors);
});

// for image compression
gulp.task('images', function() {
    return gulp.src('frontend/src/images/**/*')
        .pipe(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true }))
        .pipe(gulp.dest('frontend/dist/images'));
});

// Fonts
gulp.task('fonts', function() {
    var font = gulp.src([
            'frontend/bower_components/font-awesome/fonts/fontawesome-webfont.*', 'bower_components/materialize/fonts/**/*'
        ])
        .pipe(gulp.dest('frontend/dist/fonts/'));

    var fontCss = gulp.src([
            'frontend/bower_components/font-awesome/css/font-awesome.css'
        ])
        .pipe(gulp.dest('frontend/dist/css/'));

    return merge(font, fontCss);
});

// cleaning build process- run clean before deploy and rebuild files again
gulp.task('clean', function() {
    return del(['frontend/dist/css', 'frontend/dist/js', 'frontend/dist/images', '../frontend/dist/vendors', 'frontend/dist/views'], { force: true });
});

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

    // Watch .scss files
    gulp.watch('frontend/src/css/**/*.scss', ['css']);

    // Watch .js files
    gulp.watch('frontend/src/js/**/*.js', ['js']);

    // Watch html files
    gulp.watch('frontend/src/views/**/*.html', ['html']);

    // Watch image files
    gulp.watch('frontend/src/images/**/*', ['images']);

    // Create LiveReload server
    livereload.listen();

    // Watch any files in dist/, reload on change
    gulp.watch(['frontend/dist/**']).on('change', livereload.changed);

});

// connect to server
gulp.task('connect', function() {
    connect.server({
        root: 'frontend/',
        port: 8888,
        middleware: function(connect) {
            return [
                connectModRewrite([
                    '!\\.html|\\.js|\\.css|\\.ico|\\.png|\\.gif|\\.jpg|\\.woff|.\\.ttf|.\\otf|\\.jpeg|\\.swf.*$ /index.html [NC,L]'
                ])
            ];
        }
    });
})

// development task
gulp.task('dev', ['clean'], function() {
    gulp.start('css', 'js', 'html', 'images', 'vendorjs', 'vendorcss', 'fonts', 'configDev');
});

// production task
gulp.task('prod', ['clean'], function() {
    gulp.start('css', 'js', 'html', 'images', 'vendorjs', 'vendorcss', 'fonts', 'configProd');
});
<commit_msg>Frontend: Fixed loading of fonts (#335)<commit_after>// Gulp Tasks
'use strict';

var gulp = require('gulp'),
    merge = require('merge-stream'),
    sass = require('gulp-ruby-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    cssnano = require('gulp-cssnano'),
    jshint = require('gulp-jshint'),
    uglify = require('gulp-uglify'),
    imagemin = require('gulp-imagemin'),
    rename = require('gulp-rename'),
    concat = require('gulp-concat'),
    notify = require('gulp-notify'),
    cache = require('gulp-cache'),
    livereload = require('gulp-livereload'),
    del = require('del'),
    connect = require('gulp-connect'),
    htmlmin = require('gulp-html-minifier'),
    fs = require('fs'),
    connectModRewrite = require('connect-modrewrite'),
    ngConfig = require('gulp-ng-config'),
    prettyError = require('gulp-prettyerror'),
    // path = require('gulp-path'),
    // conf = require('./conf')(gulp),
    _ = require('lodash');

var scripts = require('./frontend/app.scripts.json');
var styles = require('./frontend/app.styles.json');

//include all bower scripts files
gulp.task('vendorjs', function() {

    _.forIn(scripts.chunks, function(chunkScripts, chunkName) {
        var paths = [];
        chunkScripts.forEach(function(script) {
            var scriptFileName = scripts.paths[script];

            if (!fs.existsSync(__dirname + '/' + scriptFileName)) {

                throw console.error('Required path doesn\'t exist: ' + __dirname + '/' + scriptFileName, script)
            }
            paths.push(scriptFileName);
        });
        gulp.src(paths)
            .pipe(concat(chunkName + '.js'))
            //.on('error', swallowError)
            .pipe(gulp.dest("frontend/dist/vendors"))
    })

});

//include all bower  styles files
gulp.task('vendorcss', function() {

    _.forIn(styles.chunks, function(chunkStyles, chunkName) {
        var paths = [];
        chunkStyles.forEach(function(style) {
            var styleFileName = styles.paths[style];

            if (!fs.existsSync(__dirname + '/' + styleFileName)) {

                throw console.error('Required path doesn\'t exist: ' + __dirname + '/' + styleFileName, style)
            }
            paths.push(styleFileName);
        });
        gulp.src(paths)
            .pipe(concat(chunkName + '.css'))
            //.on('error', swallowError)
            .pipe(gulp.dest("frontend/dist/vendors"))
    })

});

// config for dev server
gulp.task('configDev', function() {
    gulp.src('frontend/src/js/config.json')
        .pipe(ngConfig('evalai-config', {
            environment: 'local'
        }))
        .pipe(gulp.dest('frontend/dist/js'))
});

// config for prod server
gulp.task('configProd', function() {
    gulp.src('frontend/src/js/config.json')
        .pipe(ngConfig('evalai-config', {
            environment: 'production'
        }))
        .pipe(gulp.dest('frontend/dist/js'))
});

// minify and compress CSS files
gulp.task('css', function() {
    return sass('frontend/src/css/main.scss', { style: 'expanded' })
        .pipe(prettyError())
        .pipe(autoprefixer('last 2 version'))
        .pipe(gulp.dest('frontend/dist/css'))
        .pipe(rename({ suffix: '.min' }))
        .pipe(cssnano())
        .pipe(gulp.dest('frontend/dist/css'));
})

// minify angular scripts
gulp.task('js', function() {

    var app = gulp.src('frontend/src/js/app.js')
        .pipe(prettyError())
        .pipe(jshint.reporter('default'))
        .pipe(concat('app.js'))
        .pipe(gulp.dest('frontend/dist/js'))
        .pipe(rename({ suffix: '.min' }))
        .pipe(uglify())
        .pipe(gulp.dest('frontend/dist/js'));

    var configs = gulp.src('frontend/src/js/route-config/*.js')
        .pipe(prettyError())
        .pipe(jshint.reporter('default'))
        .pipe(concat('route-config.js'))
        .pipe(gulp.dest('frontend/dist/js'))
        .pipe(rename({ suffix: '.min' }))
        .pipe(uglify())
        .pipe(gulp.dest('frontend/dist/js'));

    var controllers = gulp.src('frontend/src/js/controllers/*.js')
        .pipe(prettyError())
        .pipe(jshint.reporter('default'))
        .pipe(concat('controllers.js'))
        .pipe(gulp.dest('frontend/dist/js'))
        .pipe(rename({ suffix: '.min' }))
        .pipe(uglify())
        .pipe(gulp.dest('frontend/dist/js'));

    var directives = gulp.src('frontend/src/js/directives/*.js')
        .pipe(prettyError())
        .pipe(jshint.reporter('default'))
        .pipe(concat('directives.js'))
        .pipe(gulp.dest('frontend/dist/js'))
        .pipe(rename({ suffix: '.min' }))
        .pipe(uglify())
        .pipe(gulp.dest('frontend/dist/js'));

    var filters = gulp.src('frontend/src/js/filters/*.js')
        .pipe(prettyError())
        .pipe(jshint.reporter('default'))
        .pipe(concat('filters.js'))
        .pipe(gulp.dest('frontend/dist/js'))
        .pipe(rename({ suffix: '.min' }))
        .pipe(uglify())
        .pipe(gulp.dest('frontend/dist/js'));

    var services = gulp.src('frontend/src/js/services/*.js')
        .pipe(prettyError())
        .pipe(jshint.reporter('default'))
        .pipe(concat('services.js'))
        .pipe(gulp.dest('frontend/dist/js'))
        .pipe(rename({ suffix: '.min' }))
        .pipe(uglify())
        .pipe(gulp.dest('frontend/dist/js'));

    return merge(app, configs, controllers, directives, filters, services)
});

// minify and compress html files
gulp.task('html', function() {

    var webViews = gulp.src('frontend/src/views/web/*.html')
        .pipe(htmlmin({ collapseWhitespace: true }))
        .pipe(gulp.dest('frontend/dist/views/web'));

    var webPartials = gulp.src('frontend/src/views/web/partials/*.html')
        .pipe(htmlmin({ collapseWhitespace: true }))
        .pipe(gulp.dest('frontend/dist/views/web/partials'));

    var challengePartials = gulp.src('frontend/src/views/web/challenge/*.html')
        .pipe(htmlmin({ collapseWhitespace: true }))
        .pipe(gulp.dest('frontend/dist/views/web/challenge'));

    var webErrors = gulp.src('frontend/src/views/web/error-pages/*.html')
        .pipe(htmlmin({ collapseWhitespace: true }))
        .pipe(gulp.dest('frontend/dist/views/web/error-pages'));

    return merge(webViews, webPartials, challengePartials, webErrors);
});

// for image compression
gulp.task('images', function() {
    return gulp.src('frontend/src/images/**/*')
        .pipe(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true }))
        .pipe(gulp.dest('frontend/dist/images'));
});

// Fonts
gulp.task('fonts', function() {
    var font = gulp.src([
            'bower_components/font-awesome/fonts/fontawesome-webfont.*', 'bower_components/materialize/fonts/**/*'
        ])
        .pipe(gulp.dest('frontend/dist/fonts/'));

    var fontCss = gulp.src([
            'bower_components/font-awesome/css/font-awesome.css'
        ])
        .pipe(gulp.dest('frontend/dist/css/'));

    return merge(font, fontCss);
});

// cleaning build process- run clean before deploy and rebuild files again
gulp.task('clean', function() {
    return del(['frontend/dist/css', 'frontend/dist/js', 'frontend/dist/images', '../frontend/dist/vendors', 'frontend/dist/views'], { force: true });
});

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

    // Watch .scss files
    gulp.watch('frontend/src/css/**/*.scss', ['css']);

    // Watch .js files
    gulp.watch('frontend/src/js/**/*.js', ['js']);

    // Watch html files
    gulp.watch('frontend/src/views/**/*.html', ['html']);

    // Watch image files
    gulp.watch('frontend/src/images/**/*', ['images']);

    // Create LiveReload server
    livereload.listen();

    // Watch any files in dist/, reload on change
    gulp.watch(['frontend/dist/**']).on('change', livereload.changed);

});

// connect to server
gulp.task('connect', function() {
    connect.server({
        root: 'frontend/',
        port: 8888,
        middleware: function(connect) {
            return [
                connectModRewrite([
                    '!\\.html|\\.js|\\.css|\\.ico|\\.png|\\.gif|\\.jpg|\\.woff|.\\.ttf|.\\otf|\\.jpeg|\\.swf.*$ /index.html [NC,L]'
                ])
            ];
        }
    });
})

// development task
gulp.task('dev', ['clean'], function() {
    gulp.start('css', 'js', 'html', 'images', 'vendorjs', 'vendorcss', 'fonts', 'configDev');
});

// production task
gulp.task('prod', ['clean'], function() {
    gulp.start('css', 'js', 'html', 'images', 'vendorjs', 'vendorcss', 'fonts', 'configProd');
});
<|endoftext|>


<commit_before>require('es6-promise').polyfill();
var gulp = require('gulp');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var cleanCSS = require('gulp-clean-css');
var del = require('del');
var sourcemaps = require('gulp-sourcemaps');
var runSequence = require('run-sequence');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var gcmq = require('gulp-group-css-media-queries');
var merge = require('merge-stream');

var srcThemesPath = './resources/themes/';
var destThemesPath = './public/assets/';

gulp.task('sass-dev', function() {
  var bs = gulp.src([srcThemesPath + 'bs/scss/**/*.scss'])
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(destThemesPath + 'bs'));

  var mdl = gulp.src([
      srcThemesPath + 'mdl/scss/*.scss',
      './node_modules/material-design-lite/dist/material.deep_purple-blue.min.css',
      './node_modules/mdl-selectfield/dist/mdl-selectfield.css'
    ])
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(concat('main.css'))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(destThemesPath + 'mdl'));

  return merge(bs, mdl);
});

gulp.task('sass-prod', function() {
  var bs = gulp.src([srcThemesPath + 'bs/scss/*.scss'])
    .pipe(sass().on('error', sass.logError))
    .pipe(autoprefixer({
      browsers: ['last 2 versions'],
      cascade: false
    }))
    .pipe(gcmq())
    .pipe(cleanCSS({debug: true}, function(details) {
      console.log(details.name + ' before: ' + details.stats.originalSize);
      console.log(details.name + ' after: ' + details.stats.minifiedSize);
    }))
    .pipe(concat('main.css'))
    .pipe(gulp.dest(destThemesPath + 'bs'));

  var mdl = gulp.src([
      srcThemesPath + 'mdl/scss/*.scss',
      './node_modules/material-design-lite/dist/material.deep_purple-blue.min.css',
      './node_modules/mdl-selectfield/dist/mdl-selectfield.css'
    ])
    .pipe(sass().on('error', sass.logError))
    .pipe(concat('main.css'))
    .pipe(autoprefixer({
      browsers: ['last 2 versions'],
      cascade: false
    }))
    .pipe(gcmq())
    .pipe(cleanCSS({debug: true}, function(details) {
      console.log(details.name + ' before: ' + details.stats.originalSize);
      console.log(details.name + ' after: ' + details.stats.minifiedSize);
    }))
    .pipe(gulp.dest(destThemesPath + 'mdl'));

  return merge(bs, mdl);
});

gulp.task('js', function() {
  var bs = gulp.src([srcThemesPath + 'bs/js/*.js'])
    .pipe(concat('main.js'))
    .pipe(uglify())
    .pipe(gulp.dest(destThemesPath + 'bs/js'));

  var mdl = gulp.src([
      './node_modules/material-design-lite/material.js',
      './node_modules/mdl-selectfield/dist/mdl-selectfield.js',
      srcThemesPath + 'mdl/js/*.js'
    ])
    .pipe(concat('main.js'))
    .pipe(uglify())
    .pipe(gulp.dest(destThemesPath + 'mdl'));

  return merge(bs, mdl);
});

gulp.task('clean', function() {
  return del.sync('./public/assets');
})

gulp.task('watch', function(){
  gulp.watch('./web/themes/**/scss/**/*.scss', ['sass-dev']);
  gulp.watch('./web/themes/**/js/**/*', ['js']);
})

// Build Sequences
// ---------------

gulp.task('default', ['watch']);

gulp.task('build', function(callback) {
  runSequence(
    'clean',
    ['sass-prod', 'js'],
    callback
  )
})
<commit_msg>Fix watch task<commit_after>require('es6-promise').polyfill();
var gulp = require('gulp');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var cleanCSS = require('gulp-clean-css');
var del = require('del');
var sourcemaps = require('gulp-sourcemaps');
var runSequence = require('run-sequence');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var gcmq = require('gulp-group-css-media-queries');
var merge = require('merge-stream');

var srcThemesPath = './resources/themes/';
var destThemesPath = './public/assets/';

gulp.task('sass-dev', function() {
  var bs = gulp.src([srcThemesPath + 'bs/scss/**/*.scss'])
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(destThemesPath + 'bs'));

  var mdl = gulp.src([
      srcThemesPath + 'mdl/scss/*.scss',
      './node_modules/material-design-lite/dist/material.deep_purple-blue.min.css',
      './node_modules/mdl-selectfield/dist/mdl-selectfield.css'
    ])
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(concat('main.css'))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(destThemesPath + 'mdl'));

  return merge(bs, mdl);
});

gulp.task('sass-prod', function() {
  var bs = gulp.src([srcThemesPath + 'bs/scss/*.scss'])
    .pipe(sass().on('error', sass.logError))
    .pipe(autoprefixer({
      browsers: ['last 2 versions'],
      cascade: false
    }))
    .pipe(gcmq())
    .pipe(cleanCSS({debug: true}, function(details) {
      console.log(details.name + ' before: ' + details.stats.originalSize);
      console.log(details.name + ' after: ' + details.stats.minifiedSize);
    }))
    .pipe(concat('main.css'))
    .pipe(gulp.dest(destThemesPath + 'bs'));

  var mdl = gulp.src([
      srcThemesPath + 'mdl/scss/*.scss',
      './node_modules/material-design-lite/dist/material.deep_purple-blue.min.css',
      './node_modules/mdl-selectfield/dist/mdl-selectfield.css'
    ])
    .pipe(sass().on('error', sass.logError))
    .pipe(concat('main.css'))
    .pipe(autoprefixer({
      browsers: ['last 2 versions'],
      cascade: false
    }))
    .pipe(gcmq())
    .pipe(cleanCSS({debug: true}, function(details) {
      console.log(details.name + ' before: ' + details.stats.originalSize);
      console.log(details.name + ' after: ' + details.stats.minifiedSize);
    }))
    .pipe(gulp.dest(destThemesPath + 'mdl'));

  return merge(bs, mdl);
});

gulp.task('js', function() {
  var bs = gulp.src([srcThemesPath + 'bs/js/*.js'])
    .pipe(concat('main.js'))
    .pipe(uglify())
    .pipe(gulp.dest(destThemesPath + 'bs/js'));

  var mdl = gulp.src([
      './node_modules/material-design-lite/material.js',
      './node_modules/mdl-selectfield/dist/mdl-selectfield.js',
      srcThemesPath + 'mdl/js/*.js'
    ])
    .pipe(concat('main.js'))
    .pipe(uglify())
    .pipe(gulp.dest(destThemesPath + 'mdl'));

  return merge(bs, mdl);
});

gulp.task('clean', function() {
  return del.sync('./public/assets');
})

gulp.task('watch', function(){
  gulp.watch(srcThemesPath + '**/scss/**/*.scss', ['sass-dev']);
  gulp.watch(srcThemesPath + '**/js/**/*', ['js']);
})

// Build Sequences
// ---------------

gulp.task('default', ['watch']);

gulp.task('build', function(callback) {
  runSequence(
    'clean',
    ['sass-prod', 'js'],
    callback
  )
})
<|endoftext|>


<commit_before>var exec = require('child_process').exec;
var zip = require('gulp-zip');
var del = require('del');
var gulp = require('gulp');
var rename = require('gulp-rename');
var sequence = require('run-sequence');
var packager = require('electron-packager');
var vulcanize = require('gulp-vulcanize');
var winInstaller = require('electron-windows-installer');

var VERSION = require('./src/package.json').version;
var TEMP_BUILD_DIR = 'vulcanized';
var BUILD_DIR = 'build';
var DIST_DIR = 'dist';

gulp.task('make-installer', function() {
	return winInstaller({
		appDirectory: BUILD_DIR + '/Auto-Shutdown-win32-ia32',
		outputDirectory: DIST_DIR,
		iconUrl: __dirname + '/build-assets/logo-gray.ico',
		exe: 'Auto-Shutdown.exe',
		setupExe: 'Auto Shutdown Setup.exe',
		authors: 'Mccxiv Software',
		title: 'Auto Shutdown',
		setupIcon: __dirname + '/build-assets/logo-gray.ico'
	});
});

gulp.task('run-development', function(cb) {
	exec('"src/node_modules/.bin/electron" ./src', cb);
});

gulp.task('run-vulcanized', function(cb) {
	exec('"src/node_modules/.bin/electron" '+TEMP_BUILD_DIR, cb);
});

gulp.task('vulcanize', function() {
	return gulp.src('src/index.html')
		.pipe(vulcanize({
			excludes: [],
			inlineScripts: true,
			inlineCss: true,
			stripExcludes: false
		}))
		.pipe(gulp.dest(TEMP_BUILD_DIR));
});

gulp.task('copy-files', function() {
	return gulp.src(['src/main.js', 'src/package.json'])
		.pipe(gulp.dest(TEMP_BUILD_DIR));
});

gulp.task('copy-modules', function() {
	return gulp.src(['src/modules/**'])
		.pipe(gulp.dest(TEMP_BUILD_DIR+'/modules'));
});

gulp.task('copy-assets', function() {
	return gulp.src(['src/assets/**'])
		.pipe(gulp.dest(TEMP_BUILD_DIR+'/assets'));
});

gulp.task('clean-up-before', function(cb) {
	del([TEMP_BUILD_DIR, BUILD_DIR, DIST_DIR], cb);
});

gulp.task('clean-up-after', function(cb) {
	del([TEMP_BUILD_DIR, BUILD_DIR, 'dist/RELEASES', 'dist/**/*.nupkg'], cb);
});

gulp.task('package', function(cb) {
	var opts = {
		dir: 'vulcanized',
		name: 'Auto-Shutdown',
		platform: 'all',
		arch: 'ia32',
		version: '0.30.2',
		'app-version': VERSION,
		icon: 'build-assets/logo-gray.ico',
		'version-string': {
			CompanyName: 'Mccxiv Software',
			LegalCopyright: 'Copyright 2015 Andrea Stella. All rights reserved',
			ProductVersion: VERSION,
			FileVersion: VERSION,
			OriginalFilename: 'auto-shutdown.exe',
			FileDescription: 'Auto Shutdown',
			ProductName: 'Auto Shutdown'
		},
		out: BUILD_DIR
	};
	packager(opts, cb);
});

gulp.task('make-zip-windows', function() {
	return gulp.src('build/Auto-Shutdown-win32-ia32/**/*')
		.pipe(rename(function(path) {
			path.dirname = path.dirname === '.'? 'AutoShutdown' : 'AutoShutdown/'+path.dirname;
		}))
		.pipe(zip('autoshutdown-windows-'+VERSION+'.zip'))
		.pipe(gulp.dest('dist/'));
});

gulp.task('build', function(cb) {
	sequence('clean-up-before',
		['vulcanize', 'copy-files', 'copy-modules', 'copy-assets'],
		'package',
		['make-installer', 'make-zip-windows'],
		'clean-up-after', cb);
});

gulp.task('default', ['build']);<commit_msg>Make file names consistent: no spaces, no dash<commit_after>var exec = require('child_process').exec;
var zip = require('gulp-zip');
var del = require('del');
var gulp = require('gulp');
var rename = require('gulp-rename');
var sequence = require('run-sequence');
var packager = require('electron-packager');
var vulcanize = require('gulp-vulcanize');
var winInstaller = require('electron-windows-installer');

var VERSION = require('./src/package.json').version;
var TEMP_BUILD_DIR = 'vulcanized';
var BUILD_DIR = 'build';
var DIST_DIR = 'dist';

gulp.task('make-installer', function() {
	return winInstaller({
		appDirectory: BUILD_DIR + '/AutoShutdown-win32-ia32',
		outputDirectory: DIST_DIR,
		iconUrl: __dirname + '/build-assets/logo-gray.ico',
		exe: 'AutoShutdown.exe',
		setupExe: 'AutoShutdown-Setup-'+VERSION+'.exe',
		authors: 'Mccxiv Software',
		title: 'Auto Shutdown',
		setupIcon: __dirname + '/build-assets/logo-gray.ico'
	});
});

gulp.task('run-development', function(cb) {
	exec('"src/node_modules/.bin/electron" ./src', cb);
});

gulp.task('run-vulcanized', function(cb) {
	exec('"src/node_modules/.bin/electron" '+TEMP_BUILD_DIR, cb);
});

gulp.task('vulcanize', function() {
	return gulp.src('src/index.html')
		.pipe(vulcanize({
			excludes: [],
			inlineScripts: true,
			inlineCss: true,
			stripExcludes: false
		}))
		.pipe(gulp.dest(TEMP_BUILD_DIR));
});

gulp.task('copy-files', function() {
	return gulp.src(['src/main.js', 'src/package.json'])
		.pipe(gulp.dest(TEMP_BUILD_DIR));
});

gulp.task('copy-modules', function() {
	return gulp.src(['src/modules/**'])
		.pipe(gulp.dest(TEMP_BUILD_DIR+'/modules'));
});

gulp.task('copy-assets', function() {
	return gulp.src(['src/assets/**'])
		.pipe(gulp.dest(TEMP_BUILD_DIR+'/assets'));
});

gulp.task('clean-up-before', function(cb) {
	del([TEMP_BUILD_DIR, BUILD_DIR, DIST_DIR], cb);
});

gulp.task('clean-up-after', function(cb) {
	del([TEMP_BUILD_DIR, BUILD_DIR, 'dist/RELEASES', 'dist/**/*.nupkg'], cb);
});

gulp.task('package', function(cb) {
	var opts = {
		dir: 'vulcanized',
		name: 'AutoShutdown',
		platform: 'all',
		arch: 'ia32',
		version: '0.30.2',
		'app-version': VERSION,
		icon: 'build-assets/logo-gray.ico',
		'version-string': {
			CompanyName: 'Mccxiv Software',
			LegalCopyright: 'Copyright 2015 Andrea Stella. All rights reserved',
			ProductVersion: VERSION,
			FileVersion: VERSION,
			FileDescription: 'Auto Shutdown',
			ProductName: 'Auto Shutdown'
		},
		out: BUILD_DIR
	};
	packager(opts, cb);
});

gulp.task('make-zip-windows', function() {
	return gulp.src('build/AutoShutdown-win32-ia32/**/*')
		.pipe(rename(function(path) {
			path.dirname = path.dirname === '.'? 'AutoShutdown' : 'AutoShutdown/'+path.dirname;
		}))
		.pipe(zip('AutoShutdown-win32-'+VERSION+'.zip'))
		.pipe(gulp.dest('dist/'));
});

gulp.task('build', function(cb) {
	sequence('clean-up-before',
		['vulcanize', 'copy-files', 'copy-modules', 'copy-assets'],
		'package',
		['make-installer', 'make-zip-windows'],
		'clean-up-after', cb);
});

gulp.task('default', ['build']);<|endoftext|>


<commit_before>var GameController = function(args) {
  this.pelletCount = 0;
  this.lives = 2;
  this.keyStates = {
    up: false,
    down: false,
    left: false,
    right: false
  }
  this.pacMoveInterval = false;

  this.pacCanvas = args.pacCanvas;
  this.blinkyCanvas = args.blinkyCanvas;
  this.inkyCanvas = args.inkyCanvas;
  this.pinkyCanvas = args.pinkyCanvas;
  this.clydeCanvas = args.clydeCanvas;
  this.boardCanvas = args.boardCanvas;
  this.pelletCanvas = args.pelletCanvas;

  this.pac = new Actor(ACTOR_ARGS.pac);
  this.blinky = new Ghost(ACTOR_ARGS.blinky);
  this.inky = new Ghost(ACTOR_ARGS.inky);
  this.pinky = new Ghost(ACTOR_ARGS.pinky);
  this.clyde = new Ghost(ACTOR_ARGS.clyde);

  this.gameBoard = args.gameBoard;
  this.actorBoard = args.actorBoard;

  this.drawPellets();

  this.pacCanvas.renderPac(this.pac);
  this.updateGameBoard();

  addEventListener("keydown", this.handleKeyDown.bind(this));
  addEventListener("keyup", this.handleKeyUp.bind(this));

  setInterval(function() {
    this.moveGhost("b");
    this.moveGhost("i");
    this.moveGhost("p");
    this.moveGhost("c");
  }.bind(this), GHOST_MOVE_DELAY);
}
GameController.prototype.drawPellets = function() {
  this.pelletCanvas.clearRect({
    x: 0,
    y: 0,
    w: BOARD_WIDTH,
    h: BOARD_HEIGHT
  });
  this.gameBoard.board.matrix.forEach(function(row, rIndex) {
    row.forEach(function(col, cIndex) {
      if(col == ".") {
        this.pelletCanvas.drawRect({
          color: PELLET_COLOR,
          x: (8 * cIndex) + 3,
          y: (8 * rIndex) + 27,
          w: 2,
          h: 2
        });
      }
      else if(col == "o") {
        this.pelletCanvas.drawCircle({
          x: (8 * cIndex) + 4,
          y: (8 * rIndex) + 28,
          rad: 4
        });
      }
      else if(col == "-") {
        this.pelletCanvas.drawRect({
          color: PELLET_COLOR,
          x: 8 * cIndex,
          y: (8 * rIndex) + 29,
          w: 8,
          h: 2
        });
      }
    }.bind(this));
  }.bind(this));

  var score = this.pelletCount.toString();
  if(score.length == 1) {
    score = "0" + score;
  }
  this.boardCanvas.drawText({
    text: score,
    col: 4 - score.length,
    row: 2
  });
};
GameController.prototype.moveActor = function() {
  this.pacCanvas.clearRect(this.pac.getClearDimensions());
  var coords = {
    x: this.pac.x,
    y: this.pac.y
  }

  var newDirection = false;
  for(var prop in this.keyStates) {
    if(this.keyStates.hasOwnProperty(prop) && this.keyStates[prop]) {
      newDirection = prop;
      break;
    }
  }

  var collision;
  if(this.keyStates[this.pac.direction] === false && newDirection) {
    collision = this.gameBoard.predictCollision(coords, newDirection);
    if(collision != "door" && collision != "wall") {
      this.pac.direction = newDirection;
    }
  }

  collision = this.gameBoard.predictCollision(coords, this.pac.direction);
  if(collision == "wall" || collision == "door") {
    clearInterval(this.pacMoveInterval);
    this.pacMoveInterval = false;
  }
  else {
    var coords = this.actorBoard.find("m");

    this.pac.move();
    if(this.pac.x < 0) {
      this.pac.x = BOARD_WIDTH;
    }
    else if(this.pac.x > BOARD_WIDTH) {
      this.pac.x = 0;
    }

    var newCoords = Board.convertToTile({
      x: this.pac.x,
      y: this.pac.y
    });

    this.updateActorBoard({
      coords: coords,
      newCoords: newCoords,
      name: "m",
      actor: "pac"
    });
  }
  this.pac.moveTowardCenter();
  this.updateGameBoard();

  this.pacCanvas.renderPac(this.pac);
};
GameController.prototype.moveGhost = function(name) {
  var ghost;
  switch(name) {
    case "b": ghost = "blinky"; break;
    case "i": ghost = "inky"; break;
    case "p": ghost = "pinky"; break;
    case "c": ghost = "clyde"; break;
  }
  this[ghost + "Canvas"].clearRect(this[ghost].getClearDimensions());

  switch(this[ghost].movementMode) {
    case "house":
      if(this[ghost].y + 8 >= HOUSE_BOTTOM || this[ghost].y - 5 <= HOUSE_TOP) {
        this[ghost].direction = oppositeDirection(this[ghost].direction);
      }
    break;
    case "exitting":
      this[ghost].exitHouse();
      if(this[ghost].movementMode == "scatter") {
        this.setNextDirection(ghost);
      }
    break;
    case "scatter":
      if(this[ghost].isCentered()) {
        this.setNextDirection(ghost);
      }
    break;
    case "chase":
      var coords = Board.convertToTile({
        x: this.pac.x,
        y: this.pac.y
      });
      var ghostCoords = Board.convertToTile({
        x: this[ghost].x,
        y: this[ghost].y
      });
      var blinkyCoords = Board.convertToTile({
        x: this.blinky.x,
        y: this.blinky.y
      });
      this[ghost].targetTile = Ghost[ghost + "Target"]({
        coords: coords,
        direction: this.pac.direction,
        ghost: ghostCoords,
        blinky: blinkyCoords
      });
      if(this[ghost].isCentered()) {
        this.setNextDirection(ghost);
      }
    break;
  }

  this[ghost].move();
  if(this[ghost].x < 0) {
    this[ghost].x = BOARD_WIDTH;
  }
  else if(this[ghost].x > BOARD_WIDTH) {
    this[ghost].x = 0;
  }
  this[ghost + "Canvas"].renderGhost(this[ghost]);
};
GameController.prototype.handleKeyDown = function(event) {
  var keyPressed = keyCodes[event.keyCode];
  if(keyPressed) {
    event.preventDefault();
    if(this.keyStates[keyPressed] === false) {
      this.keyStates[keyPressed] = true;
      if(this.pacMoveInterval === false) {
        this.pacMoveInterval = setInterval(this.moveActor.bind(this), this.pac.speed);
      }
    }
  }
};
GameController.prototype.handleKeyUp = function(event) {
  var keyPressed = keyCodes[event.keyCode];
  if(keyPressed) {
    event.preventDefault();
    this.keyStates[keyPressed] = false;
  }
};
GameController.prototype.setNextDirection = function(ghost) {
  var currentTile = Board.convertToTile({
    x: this[ghost].x,
    y: this[ghost].y
  });
  var adjacentTiles = this.gameBoard.getAdjacentTiles({
    x: this[ghost].x,
    y: this[ghost].y
  });
  adjacentTiles[oppositeDirection(this[ghost].direction)] = undefined;

  var emptyTiles = this.gameBoard.getEmptyTiles(adjacentTiles);
  var nextTile = this.gameBoard.getClosestTile({
    tiles: emptyTiles,
    target: this[ghost].targetTile
  });

  if(nextTile) {
    if(nextTile.x < currentTile.x) {
      this[ghost].direction = "left";
    }
    else if(nextTile.x > currentTile.x) {
      this[ghost].direction = "right";
    }
    else if(nextTile.y < currentTile.y) {
      this[ghost].direction = "up";
    }
    else if(nextTile.y > currentTile.y) {
      this[ghost].direction = "down";
    }
  }
};

GameController.prototype.updateActorBoard = function(args) {
  if(args.coords.x != args.newCoords.x || args.coords.y != args.newCoords.y) {
    this.actorBoard.setCell({
      x: args.coords.x,
      y: args.coords.y,
      value: " "
    });
    this.actorBoard.setCell({
      x: args.newCoords.x,
      y: args.newCoords.y,
      value: args.name
    });
  }
};
GameController.prototype.updateGameBoard = function() {
  this.updatePellets();
  drawBorders(this.boardCanvas.context);
  this.updateLivesDisplay();
};
GameController.prototype.updateLivesDisplay = function() {
  for(var i = 0; i < 2; i++) {
    this.boardCanvas.clearRect({
      x: (24 + (16 * i)) - this.pac.radius,
      y: BOARD_HEIGHT - (8 + this.pac.radius),
      w: 2 * this.pac.radius,
      h: 2 * this.pac.radius
    })
  }
  for(var i = 0; i < this.lives; i++) {
    this.boardCanvas.renderPac({
      color: nameToColor["m"],
      mouthPos: 0.2,
      direction: "left",
      x: 24 + (16 * i),
      y: BOARD_HEIGHT - 8,
      radius: this.pac.radius
    });
  }
};
GameController.prototype.updatePellets = function() {
  var coords = Board.convertToTile({
    x: this.pac.x,
    y: this.pac.y
  });
  var tile = this.gameBoard.getCell(coords);

  if(tile == "." || tile == "o") {
    this.gameBoard.setCell({
      x: coords.x,
      y: coords.y,
      value: " "
    });
    this.pelletCount++;
    if(this.inky.movementMode == "house") {
      this.inky.handlePelletCount(this.pelletCount);
    }
    if(this.clyde.movementMode == "house") {
      this.clyde.handlePelletCount(this.pelletCount);
    }
    this.drawPellets();

    var score = this.pelletCount.toString();
    if(score.length == 1) {
      score = "0" + score;
    }
    this.boardCanvas.drawText({
      text: score,
      col: 4 - score.length,
      row: 2
    });
  }
};
<commit_msg>Move score rendering outside of conditional so it renders every time<commit_after>var GameController = function(args) {
  this.pelletCount = 0;
  this.lives = 2;
  this.keyStates = {
    up: false,
    down: false,
    left: false,
    right: false
  }
  this.pacMoveInterval = false;

  this.pacCanvas = args.pacCanvas;
  this.blinkyCanvas = args.blinkyCanvas;
  this.inkyCanvas = args.inkyCanvas;
  this.pinkyCanvas = args.pinkyCanvas;
  this.clydeCanvas = args.clydeCanvas;
  this.boardCanvas = args.boardCanvas;
  this.pelletCanvas = args.pelletCanvas;

  this.pac = new Actor(ACTOR_ARGS.pac);
  this.blinky = new Ghost(ACTOR_ARGS.blinky);
  this.inky = new Ghost(ACTOR_ARGS.inky);
  this.pinky = new Ghost(ACTOR_ARGS.pinky);
  this.clyde = new Ghost(ACTOR_ARGS.clyde);

  this.gameBoard = args.gameBoard;
  this.actorBoard = args.actorBoard;

  this.drawPellets();

  this.pacCanvas.renderPac(this.pac);
  this.updateGameBoard();

  addEventListener("keydown", this.handleKeyDown.bind(this));
  addEventListener("keyup", this.handleKeyUp.bind(this));

  setInterval(function() {
    this.moveGhost("b");
    this.moveGhost("i");
    this.moveGhost("p");
    this.moveGhost("c");
  }.bind(this), GHOST_MOVE_DELAY);
}
GameController.prototype.drawPellets = function() {
  this.pelletCanvas.clearRect({
    x: 0,
    y: 0,
    w: BOARD_WIDTH,
    h: BOARD_HEIGHT
  });
  this.gameBoard.board.matrix.forEach(function(row, rIndex) {
    row.forEach(function(col, cIndex) {
      if(col == ".") {
        this.pelletCanvas.drawRect({
          color: PELLET_COLOR,
          x: (8 * cIndex) + 3,
          y: (8 * rIndex) + 27,
          w: 2,
          h: 2
        });
      }
      else if(col == "o") {
        this.pelletCanvas.drawCircle({
          x: (8 * cIndex) + 4,
          y: (8 * rIndex) + 28,
          rad: 4
        });
      }
      else if(col == "-") {
        this.pelletCanvas.drawRect({
          color: PELLET_COLOR,
          x: 8 * cIndex,
          y: (8 * rIndex) + 29,
          w: 8,
          h: 2
        });
      }
    }.bind(this));
  }.bind(this));
};
GameController.prototype.moveActor = function() {
  this.pacCanvas.clearRect(this.pac.getClearDimensions());
  var coords = {
    x: this.pac.x,
    y: this.pac.y
  }

  var newDirection = false;
  for(var prop in this.keyStates) {
    if(this.keyStates.hasOwnProperty(prop) && this.keyStates[prop]) {
      newDirection = prop;
      break;
    }
  }

  var collision;
  if(this.keyStates[this.pac.direction] === false && newDirection) {
    collision = this.gameBoard.predictCollision(coords, newDirection);
    if(collision != "door" && collision != "wall") {
      this.pac.direction = newDirection;
    }
  }

  collision = this.gameBoard.predictCollision(coords, this.pac.direction);
  if(collision == "wall" || collision == "door") {
    clearInterval(this.pacMoveInterval);
    this.pacMoveInterval = false;
  }
  else {
    var coords = this.actorBoard.find("m");

    this.pac.move();
    if(this.pac.x < 0) {
      this.pac.x = BOARD_WIDTH;
    }
    else if(this.pac.x > BOARD_WIDTH) {
      this.pac.x = 0;
    }

    var newCoords = Board.convertToTile({
      x: this.pac.x,
      y: this.pac.y
    });

    this.updateActorBoard({
      coords: coords,
      newCoords: newCoords,
      name: "m",
      actor: "pac"
    });
  }
  this.pac.moveTowardCenter();
  this.updateGameBoard();

  this.pacCanvas.renderPac(this.pac);
};
GameController.prototype.moveGhost = function(name) {
  var ghost;
  switch(name) {
    case "b": ghost = "blinky"; break;
    case "i": ghost = "inky"; break;
    case "p": ghost = "pinky"; break;
    case "c": ghost = "clyde"; break;
  }
  this[ghost + "Canvas"].clearRect(this[ghost].getClearDimensions());

  switch(this[ghost].movementMode) {
    case "house":
      if(this[ghost].y + 8 >= HOUSE_BOTTOM || this[ghost].y - 5 <= HOUSE_TOP) {
        this[ghost].direction = oppositeDirection(this[ghost].direction);
      }
    break;
    case "exitting":
      this[ghost].exitHouse();
      if(this[ghost].movementMode == "scatter") {
        this.setNextDirection(ghost);
      }
    break;
    case "scatter":
      if(this[ghost].isCentered()) {
        this.setNextDirection(ghost);
      }
    break;
    case "chase":
      var coords = Board.convertToTile({
        x: this.pac.x,
        y: this.pac.y
      });
      var ghostCoords = Board.convertToTile({
        x: this[ghost].x,
        y: this[ghost].y
      });
      var blinkyCoords = Board.convertToTile({
        x: this.blinky.x,
        y: this.blinky.y
      });
      this[ghost].targetTile = Ghost[ghost + "Target"]({
        coords: coords,
        direction: this.pac.direction,
        ghost: ghostCoords,
        blinky: blinkyCoords
      });
      if(this[ghost].isCentered()) {
        this.setNextDirection(ghost);
      }
    break;
  }

  this[ghost].move();
  if(this[ghost].x < 0) {
    this[ghost].x = BOARD_WIDTH;
  }
  else if(this[ghost].x > BOARD_WIDTH) {
    this[ghost].x = 0;
  }
  this[ghost + "Canvas"].renderGhost(this[ghost]);
};
GameController.prototype.handleKeyDown = function(event) {
  var keyPressed = keyCodes[event.keyCode];
  if(keyPressed) {
    event.preventDefault();
    if(this.keyStates[keyPressed] === false) {
      this.keyStates[keyPressed] = true;
      if(this.pacMoveInterval === false) {
        this.pacMoveInterval = setInterval(this.moveActor.bind(this), this.pac.speed);
      }
    }
  }
};
GameController.prototype.handleKeyUp = function(event) {
  var keyPressed = keyCodes[event.keyCode];
  if(keyPressed) {
    event.preventDefault();
    this.keyStates[keyPressed] = false;
  }
};
GameController.prototype.setNextDirection = function(ghost) {
  var currentTile = Board.convertToTile({
    x: this[ghost].x,
    y: this[ghost].y
  });
  var adjacentTiles = this.gameBoard.getAdjacentTiles({
    x: this[ghost].x,
    y: this[ghost].y
  });
  adjacentTiles[oppositeDirection(this[ghost].direction)] = undefined;

  var emptyTiles = this.gameBoard.getEmptyTiles(adjacentTiles);
  var nextTile = this.gameBoard.getClosestTile({
    tiles: emptyTiles,
    target: this[ghost].targetTile
  });

  if(nextTile) {
    if(nextTile.x < currentTile.x) {
      this[ghost].direction = "left";
    }
    else if(nextTile.x > currentTile.x) {
      this[ghost].direction = "right";
    }
    else if(nextTile.y < currentTile.y) {
      this[ghost].direction = "up";
    }
    else if(nextTile.y > currentTile.y) {
      this[ghost].direction = "down";
    }
  }
};

GameController.prototype.updateActorBoard = function(args) {
  if(args.coords.x != args.newCoords.x || args.coords.y != args.newCoords.y) {
    this.actorBoard.setCell({
      x: args.coords.x,
      y: args.coords.y,
      value: " "
    });
    this.actorBoard.setCell({
      x: args.newCoords.x,
      y: args.newCoords.y,
      value: args.name
    });
  }
};
GameController.prototype.updateGameBoard = function() {
  this.updatePellets();
  drawBorders(this.boardCanvas.context);
  this.updateLivesDisplay();
};
GameController.prototype.updateLivesDisplay = function() {
  for(var i = 0; i < 2; i++) {
    this.boardCanvas.clearRect({
      x: (24 + (16 * i)) - this.pac.radius,
      y: BOARD_HEIGHT - (8 + this.pac.radius),
      w: 2 * this.pac.radius,
      h: 2 * this.pac.radius
    })
  }
  for(var i = 0; i < this.lives; i++) {
    this.boardCanvas.renderPac({
      color: nameToColor["m"],
      mouthPos: 0.2,
      direction: "left",
      x: 24 + (16 * i),
      y: BOARD_HEIGHT - 8,
      radius: this.pac.radius
    });
  }
};
GameController.prototype.updatePellets = function() {
  var coords = Board.convertToTile({
    x: this.pac.x,
    y: this.pac.y
  });
  var tile = this.gameBoard.getCell(coords);

  if(tile == "." || tile == "o") {
    this.gameBoard.setCell({
      x: coords.x,
      y: coords.y,
      value: " "
    });
    this.pelletCount++;
    if(this.inky.movementMode == "house") {
      this.inky.handlePelletCount(this.pelletCount);
    }
    if(this.clyde.movementMode == "house") {
      this.clyde.handlePelletCount(this.pelletCount);
    }
    this.drawPellets();
  }

  var score = this.pelletCount.toString();
  if(score.length == 1) {
    score = "0" + score;
  }
  this.boardCanvas.drawText({
    text: score,
    col: 4 - score.length,
    row: 1
  });
};
<|endoftext|>


<commit_before>import { range } from 'ramda';

/**
 * Get list of nulls
 * @param {Number} nFrames number of frames
 * @return {[null]} array of nulls
 */
const getNulls = (nFrames) => range(0, nFrames).map(_ => null);

/**
 * Add nFrames delay to the end of each line
 * @param {*} nFrames number of frames
 * @return {Function} concat lineChunks and range of nulls
 */
const addDelay = (nFrames) => lines => lines.concat(getNulls(nFrames));

export default addDelay;
<commit_msg>Add Hindley-Milner signatures<commit_after>import { range } from 'ramda';

/**
 * Get list of nulls
 * @sig Number -> [Null]
 * @param {Number} nFrames number of frames
 * @return {[null]} array of nulls
 */
const getNulls = (nFrames) => range(0, nFrames).map(_ => null);

/**
 * Add nFrames delay to the end of each line
 * @sig Number -> [a] -> [a]
 * @param {*} nFrames number of frames
 * @return {Function} concat lineChunks and range of nulls
 */
const addDelay = (nFrames) => lines => lines.concat(getNulls(nFrames));

export default addDelay;
<|endoftext|>


<commit_before>const gulp = require('gulp');
const del = require('del');
const typescript = require('gulp-typescript');
const tscConfig = require('./tsconfig.json');
const sourcemaps = require('gulp-sourcemaps');
const tslint = require('gulp-tslint');
const browserSync = require('browser-sync').create();
const fs = require('fs');
const runSequence = require('run-sequence');
const rename = require('gulp-rename');
const historyApiFallback = require('connect-history-api-fallback');
const gulpremote = require('gulp-remote-src');

// Command `clean`
// clean the contents of the distribution directory
gulp.task('clean', function () {
    return del('dist/**/*');
});
// clean only the app directory (containing compiled .ts app files)
gulp.task('clean:app', function () {
    return del('dist/app/*');
});

// Command `copy:assets`
// copy static assets - i.e. non TypeScript compiled source
gulp.task('copy:assets', function() {
    return gulp.src([
        'src/app/**/*',
        'src/index.html',
        'src/.htaccess',
        'src/assets/**',
        'src/deezer-channel-jsonp.html',
        '!src/app/**/*.ts'], {base: "src"})
        .pipe(gulp.dest('dist'))
});

// Command `copy:libs`
// copy dependencies
gulp.task('copy:libs', function() {
    // download from URL the Deezer JS SDK
    gulpremote(['dz.js'], {base: 'http://e-cdn-files.deezer.com/js/min/'})
        .pipe(gulp.dest('dist/lib'));
    /* nested-property module special load & requirements */
    gulp.src(['node_modules/util/**/*.js'])
        .pipe(gulp.dest('dist/lib/util')); // for nested-property (Unix MAX OS loading)
    gulp.src(['node_modules/assert/node_modules/util/**/*.js'])
        .pipe(gulp.dest('dist/lib/util')); // for nested-property (Windows loading)

    gulp.src(['node_modules/nested-property/index.js'])
        .pipe(rename('nested-property.js'))
        .pipe(gulp.dest('dist/lib'));
    /* end of nested-property module load */

    return gulp.src([
            'node_modules/es6-shim/es6-shim.min.js',
            'node_modules/es6-shim/es6-shim.map', // required since upgrade to angular2-beta7
            'node_modules/systemjs/dist/system-polyfills.js',
            'node_modules/systemjs/dist/system-polyfills.js.map', // required since upgrade to angular2-beta7
            'node_modules/angular2/bundles/angular2-polyfills.js',
            'node_modules/systemjs/dist/system.src.js',
            'node_modules/rxjs/bundles/Rx.js',
            'node_modules/angular2/bundles/angular2.dev.js',
            'node_modules/angular2/bundles/router.dev.js',
            'node_modules/angular2/bundles/http.dev.js',
            'node_modules/moment/moment.js',
            'node_modules/ng2-bootstrap/bundles/ng2-bootstrap.js',
            'node_modules/assert/assert.js', // for nested-property
            'node_modules/inherits/inherits_browser.js', // for nested-property UNIX MAC OS loading
            'node_modules/assert/node_modules/util/node_modules/inherits/inherits_browser.js' // for nested-property Windows loading
        ])
        .pipe(gulp.dest('dist/lib'))
});

// Command `compile`
// TypeScript compile app/ directory files
gulp.task('compile', function () {
    // prepare and write the app configuration file (per environment)
    var configJson = fs.readFileSync('src/config/local.json');
    fs.writeFileSync('dist/config.js',
        'exports = ' +
        configJson +
        ';'
    );

    return gulp.src('**/*.ts', {cwd: 'src'},{base : '.'})
        .pipe(sourcemaps.init())
        .pipe(typescript(tscConfig.compilerOptions))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('build'))
});

// copy content in build/ directory to the dist/ directory
gulp.task('deploy',function(){
    return gulp.src('build/src/**/*')
        .pipe(gulp.dest('dist'));
});

// Command `tslint`
// linting code within app/ directory
gulp.task('tslint', function() {
    return gulp.src('src/app/**/*.ts')
        .pipe(tslint())
        .pipe(tslint.report('verbose'));
});

gulp.task('browsersync', function() {
    return browserSync.init({
        server: "./dist",
        middleware: [ historyApiFallback() ]
        // proxy: "deezer-dl.local" // proxify to the deezer-dl.local URL instead of serving static server
    });
});

gulp.task('watch', function() {
    gulp.watch(['src/index.html', "src/app/**/*.{html,htm,css,js}"], function() {
        browserSync.active ? runSequence('copy:assets', browserSync.reload) : gulp.run('copy:assets');
    });
    return gulp.watch(['src/**/*.ts'], function() {
        browserSync.active ?
            runSequence('compile', 'clean:app', 'deploy', 'copy:assets', browserSync.reload) :
            runSequence('compile', 'clean:app', 'deploy', 'copy:assets');
    });
});

gulp.task('build', function(callback) {
    runSequence('compile', 'deploy', 'copy:assets', callback);
});

gulp.task('fullbuild', ['clean', 'tslint'], function(callback) {
    runSequence('copy:libs', 'build', callback);
});

gulp.task('serve', function(callback) {
    runSequence('fullbuild', 'browsersync', 'watch', callback);
});

gulp.task('prod', function(callback) {
    runSequence('fullbuild', 'browsersync',  callback);
});

gulp.task('default', function(callback) {
    runSequence('fullbuild', 'watch', callback);
});
<commit_msg>Gulp prod task (DIRTY)<commit_after>const gulp = require('gulp');
const del = require('del');
const typescript = require('gulp-typescript');
const tscConfig = require('./tsconfig.json');
const sourcemaps = require('gulp-sourcemaps');
const tslint = require('gulp-tslint');
const browserSync = require('browser-sync').create();
const fs = require('fs');
const runSequence = require('run-sequence');
const rename = require('gulp-rename');
const historyApiFallback = require('connect-history-api-fallback');
const gulpremote = require('gulp-remote-src');

// Command `clean`
// clean the contents of the distribution directory
gulp.task('clean', function () {
    return del('dist/**/*');
});
// clean only the app directory (containing compiled .ts app files)
gulp.task('clean:app', function () {
    return del('dist/app/*');
});

// Command `copy:assets`
// copy static assets - i.e. non TypeScript compiled source
gulp.task('copy:assets', function() {
    return gulp.src([
        'src/app/**/*',
        'src/index.html',
        'src/.htaccess',
        'src/assets/**',
        'src/deezer-channel-jsonp.html',
        '!src/app/**/*.ts'], {base: "src"})
        .pipe(gulp.dest('dist'))
});

// Command `copy:libs`
// copy dependencies
gulp.task('copy:libs', function() {
    // download from URL the Deezer JS SDK
    gulpremote(['dz.js'], {base: 'http://e-cdn-files.deezer.com/js/min/'})
        .pipe(gulp.dest('dist/lib'));
    /* nested-property module special load & requirements */
    gulp.src(['node_modules/util/**/*.js'])
        .pipe(gulp.dest('dist/lib/util')); // for nested-property (Unix MAX OS loading)
    gulp.src(['node_modules/assert/node_modules/util/**/*.js'])
        .pipe(gulp.dest('dist/lib/util')); // for nested-property (Windows loading)

    gulp.src(['node_modules/nested-property/index.js'])
        .pipe(rename('nested-property.js'))
        .pipe(gulp.dest('dist/lib'));
    /* end of nested-property module load */

    return gulp.src([
            'node_modules/es6-shim/es6-shim.min.js',
            'node_modules/es6-shim/es6-shim.map', // required since upgrade to angular2-beta7
            'node_modules/systemjs/dist/system-polyfills.js',
            'node_modules/systemjs/dist/system-polyfills.js.map', // required since upgrade to angular2-beta7
            'node_modules/angular2/bundles/angular2-polyfills.js',
            'node_modules/systemjs/dist/system.src.js',
            'node_modules/rxjs/bundles/Rx.js',
            'node_modules/angular2/bundles/angular2.dev.js',
            'node_modules/angular2/bundles/router.dev.js',
            'node_modules/angular2/bundles/http.dev.js',
            'node_modules/moment/moment.js',
            'node_modules/ng2-bootstrap/bundles/ng2-bootstrap.js',
            'node_modules/assert/assert.js', // for nested-property
            'node_modules/inherits/inherits_browser.js', // for nested-property UNIX MAC OS loading
            'node_modules/assert/node_modules/util/node_modules/inherits/inherits_browser.js' // for nested-property Windows loading
        ])
        .pipe(gulp.dest('dist/lib'))
});

// Command `compile`
// TypeScript compile app/ directory files
gulp.task('compile', function () {
    // prepare and write the app configuration file (per environment)
    var configJson = fs.readFileSync('src/config/local.json');
    fs.writeFileSync('dist/config.js',
        'exports = ' +
        configJson +
        ';'
    );

    return gulp.src('**/*.ts', {cwd: 'src'},{base : '.'})
        .pipe(sourcemaps.init())
        .pipe(typescript(tscConfig.compilerOptions))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('build'))
});

// copy content in build/ directory to the dist/ directory
gulp.task('deploy',function(){
    return gulp.src('build/src/**/*')
        .pipe(gulp.dest('dist'));
});

// Command `tslint`
// linting code within app/ directory
gulp.task('tslint', function() {
    return gulp.src('src/app/**/*.ts')
        .pipe(tslint())
        .pipe(tslint.report('verbose'));
});

gulp.task('browsersync', function() {
    return browserSync.init({
        server: "./dist",
        middleware: [ historyApiFallback() ]
        // proxy: "deezer-dl.local" // proxify to the deezer-dl.local URL instead of serving static server
    });
});

gulp.task('watch', function() {
    gulp.watch(['src/index.html', "src/app/**/*.{html,htm,css,js}"], function() {
        browserSync.active ? runSequence('copy:assets', browserSync.reload) : gulp.run('copy:assets');
    });
    return gulp.watch(['src/**/*.ts'], function() {
        browserSync.active ?
            runSequence('compile', 'clean:app', 'deploy', 'copy:assets', browserSync.reload) :
            runSequence('compile', 'clean:app', 'deploy', 'copy:assets');
    });
});

gulp.task('build', function(callback) {
    runSequence('compile', 'deploy', 'copy:assets', callback);
});

gulp.task('fullbuild', ['clean', 'tslint'], function(callback) {
    runSequence('copy:libs', 'build', callback);
});

gulp.task('serve', function(callback) {
    runSequence('fullbuild', 'browsersync', 'watch', callback);
});

gulp.task('default', function(callback) {
    runSequence('fullbuild', 'watch', callback);
});
<|endoftext|>


<commit_before>import React from 'react'
import NavMenu from 'redux/containers/NavMenuContainer'
import { desktopNavMenuWidth, tabletBreakpoint } from 'constants/design'
import '../../styles/core.scss'

class CoreLayout extends React.Component {

  constructor () {
    super()
    this.handleResize = this.handleResize.bind(this)
    this.state = {width: window.innerWidth}
  }

  static propTypes = {
    children: React.PropTypes.element.isRequired
  }

  componentDidMount () {
    window.addEventListener('resize', this.handleResize)
  }

  componentWillUnmount () {
    window.removeEventListener('resize', this.handleResize)
  }

  handleResize () {
    this.setState({width: window.innerWidth})
  }

  navMenuDisplay () {
    return window.location.href.includes('/login') ? 'none' : 'block'
  }

  mainContainerPadding () {
    return window.location.href.includes('/login') || this.state.width <= tabletBreakpoint
      ? '0px' : `${desktopNavMenuWidth}%`
  }

  render () {
    return (

          <NavMenu />

          {this.props.children}

    )
  }

}

export default CoreLayout
<commit_msg>Fix nav menu appear (#30)<commit_after>import React from 'react'
import NavMenu from 'redux/containers/NavMenuContainer'
import { desktopNavMenuWidth, tabletBreakpoint } from 'constants/design'
import '../../styles/core.scss'

class CoreLayout extends React.Component {

  constructor () {
    super()
    this.handleResize = this.handleResize.bind(this)
    this.state = {width: window.innerWidth}
  }

  static propTypes = {
    children: React.PropTypes.element.isRequired
  }

  componentDidMount () {
    window.addEventListener('resize', this.handleResize)
  }

  componentWillUnmount () {
    window.removeEventListener('resize', this.handleResize)
  }

  handleResize () {
    this.setState({width: window.innerWidth})
  }

  hasLoggedIn () {
    return window.location.href.includes('/dashboard') || window.location.href.includes('/application')
  }

  navMenuDisplay () {
    return this.hasLoggedIn() ? 'block' : 'none'
  }

  mainContainerPadding () {
    return !this.hasLoggedIn() || this.state.width <= tabletBreakpoint ? '0px' : `${desktopNavMenuWidth}%`
  }

  render () {
    return (

          <NavMenu />

          {this.props.children}

    )
  }

}

export default CoreLayout
<|endoftext|>


<commit_before>var gulp = require('gulp');
var jshint = require('gulp-jshint');
var concat = require('gulp-concat');
var babel = require('gulp-babel');
var minifyCSS = require('gulp-minify-css');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var header = require('gulp-header');
var sass = require('gulp-sass');
var livereload = require('gulp-livereload');
var webpack = require('gulp-webpack');
var wait = require('gulp-wait');
var protractor = require('gulp-protractor').protractor;
var del = require('del');
var runSequence = require('run-sequence');
var stylish = require('jshint-stylish');
var http = require('http');
var st = require('st');
var path = require('path');
var karma = require('karma').server;
var pkg = require('./package');
var jshintConfig = pkg.jshintConfig;

var BANNER = [
  '/**',
  ' * <%= pkg.name %> v<%= pkg.version %> (<%= pkg.homepage %>)',
  ' * Copyright <%= new Date().getFullYear() %> - <%= pkg.author %>',
  ' * Licensed under <%= pkg.license %>',
  ' */',
  ''
].join('\n');

var PATH = {
  SOURCE: './src/',
  TEST: './test/',
  DEMO: './demo/',
  DIST: './dist/'
};

var SOURCE = {
  SCRIPTS: PATH.SOURCE + 'scripts/',
  STYLES: PATH.SOURCE + 'styles/',
};

var handleErr = function(err) {
  console.error('ERROR' + (err.fileName ? ' in ' + err.fileName : ':'));
  console.error(err.message);
  this.end();
};

gulp.task('clean', function(cb) {
  del([PATH.DIST], cb);
});

jshintConfig.lookup = false;
gulp.task('jshint', function() {
  return gulp.src(SOURCE.SCRIPTS + '*.js')
    .pipe(jshint(jshintConfig))
    .pipe(jshint.reporter(stylish))
    .pipe(wait(1000))
    .pipe(livereload());
});

gulp.task('sass', function() {
  return gulp.src(SOURCE.STYLES + '*.scss')
    .pipe(sass()).on('error', handleErr)
    .pipe(gulp.dest(PATH.DIST))
    .pipe(wait(500))
    .pipe(livereload());
});

gulp.task('convert-and-concat', function() {
  return gulp.src([
      SOURCE.SCRIPTS + '*.js'
    ])
    .pipe(babel())
    .pipe(concat(pkg.name + '.js'))
    .pipe(gulp.dest(PATH.DIST));
});

gulp.task('uglify', function() {
  return gulp.src(PATH.DIST + pkg.name + '.js')
    .pipe(uglify()).on('error', handleErr)
    .pipe(rename({
      basename: pkg.name,
      suffix: '.min'
    }))
    .pipe(gulp.dest(PATH.DIST));
});

gulp.task('minify', function() {
  return gulp.src(PATH.DIST + pkg.name + '.css')
    .pipe(minifyCSS())
    .pipe(rename({
      basename: pkg.name,
      suffix: '.min'
    }))
    .pipe(gulp.dest(PATH.DIST));
});

gulp.task('banner', function() {
  return gulp.src(PATH.DIST + '*')
    .pipe(header(BANNER, {
      pkg: pkg
    }))
    .pipe(gulp.dest(PATH.DIST));
});

gulp.task('webpack', function() {
  return gulp.src(SOURCE.SCRIPTS + '*.js')
    .pipe(webpack({
      output: {
        path: __dirname + PATH.DEMO.substr(1),
        filename: 'bundle.js'
      },
      module: {
        loaders: [{
          loader: 'babel-loader'
        }]
      }
    }))
    .pipe(gulp.dest(PATH.DEMO));
});

gulp.task('reloadDemo', function() {
  return gulp.src(PATH.DEMO + '*.*')
    .pipe(livereload());
});

gulp.task('watch', ['server', 'webpack'], function() {
  livereload.listen({
    basePath: './',
    reloadPage: 'demo/index.html'
  });
  gulp.watch(SOURCE.SCRIPTS + '*.js', ['jshint', 'webpack']);
  gulp.watch(SOURCE.STYLES + '*.scss', ['sass']);
  gulp.watch(PATH.DEMO + '*.*', ['reloadDemo']);
});

var server;
gulp.task('server', function(cb) {
  server = http.createServer(
    st({
      path: __dirname,
      index: 'index.html',
      cache: false
    })
  ).listen(8080, cb);
});

gulp.task('test-unit', function(cb) {
  var config = {
    configFile: path.join(__dirname, '/test/karma.conf.js')
  };

  karma.start(config, function() {
    cb();
  });
});

gulp.task('test-e2e', ['server'], function() {
  return gulp.src([PATH.TEST + 'specs/e2e/*.js'])
    .pipe(protractor({
      configFile: path.join(__dirname, (process.env.TRAVIS) ?
        '/test/e2e.travis.conf.js' : '/test/e2e.conf.js'),
      args: ['--baseUrl', 'http://127.0.0.1:8000']
    })).on('error', function(e) {
      server.close();
      throw e;
    }).on('end', function() {
      server.close();
    });
});

gulp.task('build', ['clean'], function(cb) {
  runSequence(
    'sass',
    'convert-and-concat',
    'uglify',
    'minify',
    'banner',
    'test-unit',
    'test-e2e',
    cb);
});

gulp.task('default', ['build']);
<commit_msg>fixed e2e testing gulp-task<commit_after>var gulp = require('gulp');
var jshint = require('gulp-jshint');
var concat = require('gulp-concat');
var babel = require('gulp-babel');
var minifyCSS = require('gulp-minify-css');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var header = require('gulp-header');
var sass = require('gulp-sass');
var livereload = require('gulp-livereload');
var webpack = require('gulp-webpack');
var wait = require('gulp-wait');
var protractor = require('gulp-protractor').protractor;
var del = require('del');
var runSequence = require('run-sequence');
var stylish = require('jshint-stylish');
var http = require('http');
var st = require('st');
var path = require('path');
var karma = require('karma').server;
var pkg = require('./package');
var jshintConfig = pkg.jshintConfig;

var BANNER = [
  '/**',
  ' * <%= pkg.name %> v<%= pkg.version %> (<%= pkg.homepage %>)',
  ' * Copyright <%= new Date().getFullYear() %> - <%= pkg.author %>',
  ' * Licensed under <%= pkg.license %>',
  ' */',
  ''
].join('\n');

var PATH = {
  SOURCE: './src/',
  TEST: './test/',
  DEMO: './demo/',
  DIST: './dist/'
};

var SOURCE = {
  SCRIPTS: PATH.SOURCE + 'scripts/',
  STYLES: PATH.SOURCE + 'styles/',
};

var handleErr = function(err) {
  console.error('ERROR' + (err.fileName ? ' in ' + err.fileName : ':'));
  console.error(err.message);
  this.end();
};

gulp.task('clean', function(cb) {
  del([PATH.DIST], cb);
});

jshintConfig.lookup = false;
gulp.task('jshint', function() {
  return gulp.src(SOURCE.SCRIPTS + '*.js')
    .pipe(jshint(jshintConfig))
    .pipe(jshint.reporter(stylish))
    .pipe(wait(1000))
    .pipe(livereload());
});

gulp.task('sass', function() {
  return gulp.src(SOURCE.STYLES + '*.scss')
    .pipe(sass()).on('error', handleErr)
    .pipe(gulp.dest(PATH.DIST))
    .pipe(wait(500))
    .pipe(livereload());
});

gulp.task('convert-and-concat', function() {
  return gulp.src([
      SOURCE.SCRIPTS + '*.js'
    ])
    .pipe(babel())
    .pipe(concat(pkg.name + '.js'))
    .pipe(gulp.dest(PATH.DIST));
});

gulp.task('uglify', function() {
  return gulp.src(PATH.DIST + pkg.name + '.js')
    .pipe(uglify()).on('error', handleErr)
    .pipe(rename({
      basename: pkg.name,
      suffix: '.min'
    }))
    .pipe(gulp.dest(PATH.DIST));
});

gulp.task('minify', function() {
  return gulp.src(PATH.DIST + pkg.name + '.css')
    .pipe(minifyCSS())
    .pipe(rename({
      basename: pkg.name,
      suffix: '.min'
    }))
    .pipe(gulp.dest(PATH.DIST));
});

gulp.task('banner', function() {
  return gulp.src(PATH.DIST + '*')
    .pipe(header(BANNER, {
      pkg: pkg
    }))
    .pipe(gulp.dest(PATH.DIST));
});

gulp.task('webpack', function() {
  return gulp.src(SOURCE.SCRIPTS + '*.js')
    .pipe(webpack({
      output: {
        path: __dirname + PATH.DEMO.substr(1),
        filename: 'bundle.js'
      },
      module: {
        loaders: [{
          loader: 'babel-loader'
        }]
      }
    }))
    .pipe(gulp.dest(PATH.DEMO));
});

gulp.task('reloadDemo', function() {
  return gulp.src(PATH.DEMO + '*.*')
    .pipe(livereload());
});

gulp.task('watch', ['server', 'webpack'], function() {
  livereload.listen({
    basePath: './',
    reloadPage: 'demo/index.html'
  });
  gulp.watch(SOURCE.SCRIPTS + '*.js', ['jshint', 'webpack']);
  gulp.watch(SOURCE.STYLES + '*.scss', ['sass']);
  gulp.watch(PATH.DEMO + '*.*', ['reloadDemo']);
});

var server;
gulp.task('server', function(cb) {
  server = http.createServer(
    st({
      path: __dirname,
      index: 'index.html',
      cache: false
    })
  ).listen(8080, cb);
});

gulp.task('test-unit', function(cb) {
  var config = {
    configFile: path.join(__dirname, '/test/karma.conf.js')
  };

  karma.start(config, function() {
    cb();
  });
});

gulp.task('test-e2e', ['server', 'webpack'], function() {
  return gulp.src([PATH.TEST + 'specs/e2e/*.js'])
    .pipe(protractor({
      configFile: path.join(__dirname, (process.env.TRAVIS) ?
        '/test/e2e.travis.conf.js' : '/test/e2e.conf.js'),
      args: ['--baseUrl', 'http://127.0.0.1:8000']
    })).on('error', function(e) {
      server.close();
      throw e;
    }).on('end', function() {
      server.close();
    });
});

gulp.task('build', ['clean'], function(cb) {
  runSequence(
    'sass',
    'convert-and-concat',
    'uglify',
    'minify',
    'banner',
    'test-unit',
    'test-e2e',
    cb);
});

gulp.task('default', ['build']);
<|endoftext|>


<commit_before>import React from 'react'
import { IndexLink, Link } from 'react-router'
import PropTypes from 'prop-types'
import './PageLayout.scss'

export const PageLayout = ({ children }) => (

                    <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                        Toggle navigation

                    </button>

Shotio

                            <IndexLink to='/' activeClassName='page-layout__nav-item--active'>Home</IndexLink>

                            <Link to='/counter' activeClassName='page-layout__nav-item--active'>Counter</Link>

                {children}

)
PageLayout.propTypes = {
  children: PropTypes.node,
}

export default PageLayout
<commit_msg>Small PageLayout clean commenting out original template for now<commit_after>import React from 'react'
import { IndexLink, Link } from 'react-router'
import PropTypes from 'prop-types'
import './PageLayout.scss'

export const PageLayout = ({ children }) => (

                    <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                        Toggle navigation

                    </button>

Shotio

                            <IndexLink to='/' activeClassName='page-layout__nav-item--active'>Home</IndexLink>

                        {/*
*/}
                            {/*<Link to='/counter' activeClassName='page-layout__nav-item--active'>Counter</Link>*/}
                        {/*
*/}

                {children}

)
PageLayout.propTypes = {
  children: PropTypes.node,
}

export default PageLayout
<|endoftext|>


<commit_before>var jsp = require("uglify-js").parser;
var pro = require("uglify-js").uglify,
	BufferedStream = require('./BufferedStream'),
	gzip = require('gzip');

var processorList = {};

function StreamProcessor(inType, outType, processFunction) {
  this.inputType = inType;
  this.outputTye = outType;
  this.name = 'unknown';
  this.fun = processFunction;
}

StreamProcessor.prototype = {
  validate: function(type) {
    return type === this.inputType;
  },
  init: function(stream) {
/*
    if (stream.type !== this.inputType) {
      throw "mismatched types in " + this.name;
    } */
    return this.fun(stream);
  }
}

function createProcessor(inType, outType, name, fun) {
  var proc = new StreamProcessor(inType, outType, fun);
  proc.name = name;
  processorList[name] = proc;
}

exports.listProcessors = processorList;

// Define processors.
//
var cat = {
  name : "cat",
  inputType : 'js',
  outputType : 'js',
  validate : function(type) {
    return type === cat.inputType;
  },
  init: function(stream1, stream2) {
    var out = new BufferedStream();
	stream1.resume();
	stream1.on('data', function(chunk) {
      	out.write(chunk);
    });
	stream1.on('end', function(){
		stream2.resume();
		stream2.on('data', function(chunk) {
	        out.write(chunk);
	     });

		stream2.on('end', function(chunk) {
			out.end();
	     });
	});
	return out;
  }
}
processorList['cat'] = cat;

createProcessor('js', 'js', 'min', function(stream) {

  var out = new BufferedStream();
  var orig_code = "";

  console.log(stream);
  // stream.setEncoding('utf8');
  stream.resume();
  stream.on('data', function(chunk) {
    orig_code += chunk;
  });
  stream.on('end', function() {
    var ast = jsp.parse(orig_code); // parse code and get the initial AST
    ast = pro.ast_mangle(ast); // get a new AST with mangled names
    ast = pro.ast_squeeze(ast); // get an AST with compression optimizations
    var final_code = pro.gen_code(ast); // compressed code here
    out.write(final_code);
    out.end();
  });
  return out;
});

createProcessor('js', 'js', 'nocache', function(stream) {
  stream.headers = stream.headers || {};
  stream.headers["Cache-Control"] = "no-cache, must-revalidate";
  stream.headers["Expires"] = "Sat, 26 Jul 1997 05:00:00 GMT";
  return stream;
});

createProcessor('js', 'js', 'gzip', function(stream) {
	var out = new BufferedStream();
	var orig_code = "";

	stream.headers = stream.headers || {};
	stream.headers["Content-Encoding"] = "gzip";
	stream.resume();
	stream.setEncoding('utf8');
	stream.on('data', function(chunk) {
	    orig_code += chunk;
	});
	stream.on('end', function() {
	   	gzip(orig_code, function(err, data){
		  // By default:
		  //   compression = 8
		  //   encoding = utf8
			if(err){
				throw err;
			}
		  	out.write(data);
	    	out.end();
		});

	  });
	  return out;
});

createProcessor('js', 'js', 'js', function(stream) {
  stream.headers = stream.headers || {};
  stream.headers['Content-Type'] = "application/javascript";
  return stream;
});
<commit_msg>Don't set encoding.<commit_after>var jsp = require("uglify-js").parser;
var pro = require("uglify-js").uglify,
	BufferedStream = require('./BufferedStream'),
	gzip = require('gzip');

var processorList = {};

function StreamProcessor(inType, outType, processFunction) {
  this.inputType = inType;
  this.outputTye = outType;
  this.name = 'unknown';
  this.fun = processFunction;
}

StreamProcessor.prototype = {
  validate: function(type) {
    return type === this.inputType;
  },
  init: function(stream) {
/*
    if (stream.type !== this.inputType) {
      throw "mismatched types in " + this.name;
    } */
    return this.fun(stream);
  }
}

function createProcessor(inType, outType, name, fun) {
  var proc = new StreamProcessor(inType, outType, fun);
  proc.name = name;
  processorList[name] = proc;
}

exports.listProcessors = processorList;

// Define processors.
//
var cat = {
  name : "cat",
  inputType : 'js',
  outputType : 'js',
  validate : function(type) {
    return type === cat.inputType;
  },
  init: function(stream1, stream2) {
    var out = new BufferedStream();
	stream1.resume();
	stream1.on('data', function(chunk) {
      	out.write(chunk);
    });
	stream1.on('end', function(){
		stream2.resume();
		stream2.on('data', function(chunk) {
	        out.write(chunk);
	     });

		stream2.on('end', function(chunk) {
			out.end();
	     });
	});
	return out;
  }
}
processorList['cat'] = cat;

createProcessor('js', 'js', 'min', function(stream) {

  var out = new BufferedStream();
  var orig_code = "";

  // stream.setEncoding('utf8');
  stream.resume();
  stream.on('data', function(chunk) {
    orig_code += chunk;
  });
  stream.on('end', function() {
    var ast = jsp.parse(orig_code); // parse code and get the initial AST
    ast = pro.ast_mangle(ast); // get a new AST with mangled names
    ast = pro.ast_squeeze(ast); // get an AST with compression optimizations
    var final_code = pro.gen_code(ast); // compressed code here
    out.write(final_code);
    out.end();
  });
  return out;
});

createProcessor('js', 'js', 'nocache', function(stream) {
  stream.headers = stream.headers || {};
  stream.headers["Cache-Control"] = "no-cache, must-revalidate";
  stream.headers["Expires"] = "Sat, 26 Jul 1997 05:00:00 GMT";
  return stream;
});

createProcessor('js', 'js', 'gzip', function(stream) {
	var out = new BufferedStream();
	var orig_code = "";

	stream.headers = stream.headers || {};
	stream.headers["Content-Encoding"] = "gzip";
	stream.resume();
	// stream.setEncoding('utf8');
	stream.on('data', function(chunk) {
	    orig_code += chunk;
	});
	stream.on('end', function() {
	   	gzip(orig_code, function(err, data){
		  // By default:
		  //   compression = 8
		  //   encoding = utf8
			if(err){
				throw err;
			}
		  	out.write(data);
	    	out.end();
		});

	  });
	  return out;
});

createProcessor('js', 'js', 'js', function(stream) {
  stream.headers = stream.headers || {};
  stream.headers['Content-Type'] = "application/javascript";
  return stream;
});
<|endoftext|>