<commit_before>import _ from 'lodash';

let DISABLED_REGIONS_KEY = 'disabledRegions';
let DISABLED_TEAM_TYPES_KEY = 'disabledTeamTypes';
let DISABLED_GAMEMODES_KEY = 'disabledGamemodes';
let FAVOURITES_ONLY_KEY = 'showFavouritedHostsOnly';
let SHOW_BLOCKED_KEY = 'showBlockedHosts';

class Posts {
    constructor($rootScope, $interval, Subreddits, DateTime, RedditPostsService, $localForage) {
        this.RedditPostsService = RedditPostsService;
        this.Subreddits = Subreddits;
        this.DateTime = DateTime;
        this.$rootScope = $rootScope;

        this.posts = [];
        this.unparsed = [];

        this.lastUpdated = 0;

        this.disabledRegions = [];
        this.disabledTeamTypes = [];
        this.disabledGamemodes = [];
        this.showFavouritedHostsOnly = false;
        this.showBlockedHosts = false;

        this.initialised = $localForage
            .getItem([
                DISABLED_REGIONS_KEY, DISABLED_TEAM_TYPES_KEY, DISABLED_GAMEMODES_KEY,
                FAVOURITES_ONLY_KEY, SHOW_BLOCKED_KEY
            ])
            .spread((regions, types, gamemodes, favourites, showBlocked) => {
                // Merge saved settings into ourselves
                _.mergeNotNull(this, {
                    disabledRegions: regions,
                    disabledTeamTypes: types,
                    disabledGamemodes: gamemodes,
                    showFavouritedHostsOnly: favourites,
                    showBlockedHosts: showBlocked
                });

                $rootScope.$watchCollection(
                    () => this.disabledRegions,
                    () => $localForage.setItem(DISABLED_REGIONS_KEY, this.disabledRegions)
                );
                $rootScope.$watchCollection(
                    () => this.disabledTeamTypes,
                    () => $localForage.setItem(DISABLED_TEAM_TYPES_KEY, this.disabledTeamTypes)
                );
                $rootScope.$watchCollection(
                    () => this.disabledGamemodes,
                    () => $localForage.setItem(DISABLED_GAMEMODES_KEY, this.disabledGamemodes)
                );
                $rootScope.$watch(
                    () => this.showFavouritedHostsOnly,
                    () => $localForage.setItem(FAVOURITES_ONLY_KEY, this.showFavouritedHostsOnly)
                );
                $rootScope.$watch(
                    () => this.showBlockedHosts,
                    () => $localForage.setItem(SHOW_BLOCKED_KEY, this.showBlockedHosts)
                );
            });

        this.currentRegions = [];
        this.currentTeamTypes = [];
        this.currentGamemodes = [];

        this.errorSubs = [];

        this.updating = false;

        // Watch for subreddit changes
        this.firstQuery = Subreddits.initialised.then(() => {
            $rootScope.$watchCollection(() => Subreddits.subreddits, () => this.update());

            // Update every minute
            $interval(() => this.update(), 1000 * 60);
            return this.update();
        });
    }

    isGamemodeDisabled(gamemeode) {
        return this.disabledGamemodes.indexOf(gamemeode.toLowerCase()) > -1;
    }

    isTeamTypeDisabled(type) {
        return this.disabledTeamTypes.indexOf(type.toLowerCase()) > -1;
    }

    isRegionDisabled(region) {
        return this.disabledRegions.indexOf(region.toLowerCase()) > -1;
    }

    toggleGamemode(gamemode) {
        gamemode = gamemode.toLowerCase();

        let index = this.disabledGamemodes.indexOf(gamemode);

        if (index < 0) {
            this.disabledGamemodes.push(gamemode);
        } else {
            this.disabledGamemodes.splice(index, 1);
        }
    }

    toggleTeamType(type) {
        type = type.toLowerCase();

        let index = this.disabledTeamTypes.indexOf(type);

        if (index < 0) {
            this.disabledTeamTypes.push(type);
        } else {
            this.disabledTeamTypes.splice(index, 1);
        }
    }

    toggleRegion(region) {
        region = region.toLowerCase();

        let index = this.disabledRegions.indexOf(region);

        if (index < 0) {
            this.disabledRegions.push(region);
        } else {
            this.disabledRegions.splice(index, 1);
        }
    }

    update() {
        this.updating = true;

        return this.RedditPostsService
            .query(this.Subreddits.subreddits, 100)
            .then(data => {
                this.posts = data.posts;
                this.unparsed = data.unparsed;
                this.errorSubs = data.errors;

                this.updateRegions();
                this.updateGamemodes();
                this.updateTeamTypes();

                this.lastUpdated = this.DateTime.getTime().unix();
                this.fireRefreshPostsEvent();
            })
            .finally(() => this.updating = false);
    }

    updateRegions() {
        this.currentRegions = _(this.posts).map(post => post.region.toLowerCase()).uniq().value();
    }

    updateTeamTypes() {
        this.currentTeamTypes = _(this.posts).map(post => post.teams.toLowerCase()).uniq().value();
    }

    updateGamemodes() {
        this.currentGamemodes = _(this.posts)
                .map(post => post.gamemodes)
                .flatten()
                .map(gamemode => gamemode.toLowerCase())
                .uniq()
                .value();
    }

    fireRefreshPostsEvent() {
        this.$rootScope.$broadcast('postsUpdated', this.posts);
    }
}
Posts.$inject = ['$rootScope', '$interval', 'Subreddits', 'DateTime', 'RedditPostsService', '$localForage'];

export default Posts;
<commit_msg>fix(Posts): fix initial double reddit query<commit_after>import _ from 'lodash';

let DISABLED_REGIONS_KEY = 'disabledRegions';
let DISABLED_TEAM_TYPES_KEY = 'disabledTeamTypes';
let DISABLED_GAMEMODES_KEY = 'disabledGamemodes';
let FAVOURITES_ONLY_KEY = 'showFavouritedHostsOnly';
let SHOW_BLOCKED_KEY = 'showBlockedHosts';

class Posts {
    constructor($rootScope, $interval, Subreddits, DateTime, RedditPostsService, $localForage) {
        this.RedditPostsService = RedditPostsService;
        this.Subreddits = Subreddits;
        this.DateTime = DateTime;
        this.$rootScope = $rootScope;

        this.posts = [];
        this.unparsed = [];

        this.lastUpdated = 0;

        this.disabledRegions = [];
        this.disabledTeamTypes = [];
        this.disabledGamemodes = [];
        this.showFavouritedHostsOnly = false;
        this.showBlockedHosts = false;

        this.initialised = $localForage
            .getItem([
                DISABLED_REGIONS_KEY, DISABLED_TEAM_TYPES_KEY, DISABLED_GAMEMODES_KEY,
                FAVOURITES_ONLY_KEY, SHOW_BLOCKED_KEY
            ])
            .spread((regions, types, gamemodes, favourites, showBlocked) => {
                // Merge saved settings into ourselves
                _.mergeNotNull(this, {
                    disabledRegions: regions,
                    disabledTeamTypes: types,
                    disabledGamemodes: gamemodes,
                    showFavouritedHostsOnly: favourites,
                    showBlockedHosts: showBlocked
                });

                $rootScope.$watchCollection(
                    () => this.disabledRegions,
                    () => $localForage.setItem(DISABLED_REGIONS_KEY, this.disabledRegions)
                );
                $rootScope.$watchCollection(
                    () => this.disabledTeamTypes,
                    () => $localForage.setItem(DISABLED_TEAM_TYPES_KEY, this.disabledTeamTypes)
                );
                $rootScope.$watchCollection(
                    () => this.disabledGamemodes,
                    () => $localForage.setItem(DISABLED_GAMEMODES_KEY, this.disabledGamemodes)
                );
                $rootScope.$watch(
                    () => this.showFavouritedHostsOnly,
                    () => $localForage.setItem(FAVOURITES_ONLY_KEY, this.showFavouritedHostsOnly)
                );
                $rootScope.$watch(
                    () => this.showBlockedHosts,
                    () => $localForage.setItem(SHOW_BLOCKED_KEY, this.showBlockedHosts)
                );
            });

        this.currentRegions = [];
        this.currentTeamTypes = [];
        this.currentGamemodes = [];

        this.errorSubs = [];

        this.updating = false;

        // Watch for subreddit changes
        this.firstQuery = Subreddits.initialised.then(() => {
            $rootScope.$watchCollection(() => Subreddits.subreddits, (oldSubs, newSubs) => {
                if (oldSubs !== newSubs) {
                    this.update();
                }
            });

            // Update every minute
            $interval(() => this.update(), 1000 * 60);
            return this.update();
        });
    }

    isGamemodeDisabled(gamemeode) {
        return this.disabledGamemodes.indexOf(gamemeode.toLowerCase()) > -1;
    }

    isTeamTypeDisabled(type) {
        return this.disabledTeamTypes.indexOf(type.toLowerCase()) > -1;
    }

    isRegionDisabled(region) {
        return this.disabledRegions.indexOf(region.toLowerCase()) > -1;
    }

    toggleGamemode(gamemode) {
        gamemode = gamemode.toLowerCase();

        let index = this.disabledGamemodes.indexOf(gamemode);

        if (index < 0) {
            this.disabledGamemodes.push(gamemode);
        } else {
            this.disabledGamemodes.splice(index, 1);
        }
    }

    toggleTeamType(type) {
        type = type.toLowerCase();

        let index = this.disabledTeamTypes.indexOf(type);

        if (index < 0) {
            this.disabledTeamTypes.push(type);
        } else {
            this.disabledTeamTypes.splice(index, 1);
        }
    }

    toggleRegion(region) {
        region = region.toLowerCase();

        let index = this.disabledRegions.indexOf(region);

        if (index < 0) {
            this.disabledRegions.push(region);
        } else {
            this.disabledRegions.splice(index, 1);
        }
    }

    update() {
        this.updating = true;

        return this.RedditPostsService
            .query(this.Subreddits.subreddits, 100)
            .then(data => {
                this.posts = data.posts;
                this.unparsed = data.unparsed;
                this.errorSubs = data.errors;

                this.updateRegions();
                this.updateGamemodes();
                this.updateTeamTypes();

                this.lastUpdated = this.DateTime.getTime().unix();
                this.fireRefreshPostsEvent();
            })
            .finally(() => this.updating = false);
    }

    updateRegions() {
        this.currentRegions = _(this.posts).map(post => post.region.toLowerCase()).uniq().value();
    }

    updateTeamTypes() {
        this.currentTeamTypes = _(this.posts).map(post => post.teams.toLowerCase()).uniq().value();
    }

    updateGamemodes() {
        this.currentGamemodes = _(this.posts)
                .map(post => post.gamemodes)
                .flatten()
                .map(gamemode => gamemode.toLowerCase())
                .uniq()
                .value();
    }

    fireRefreshPostsEvent() {
        this.$rootScope.$broadcast('postsUpdated', this.posts);
    }
}
Posts.$inject = ['$rootScope', '$interval', 'Subreddits', 'DateTime', 'RedditPostsService', '$localForage'];

export default Posts;
<|endoftext|>


<commit_before>var db = require("../lib/db");

exports["module exported functions"] = function(test){

	test.notEqual(db.connect, undefined);
	test.notEqual(db.save, undefined);
	test.notEqual(db.select, undefined);
	test.notEqual(db.remove, undefined);
	test.done()
}

exports["module init:db.connect before any operation"] = function(test){

	test.throws(
		function(){
			db.save();
		},
		Error
	);
	test.done();
}

//mock mongodb driver to fake connect

<commit_msg>changed module exported function to include removeById<commit_after>var db = require("../lib/db");

exports["module exported functions"] = function(test){

	test.notEqual(db.connect, undefined);
	test.notEqual(db.save, undefined);
	test.notEqual(db.select, undefined);
	test.notEqual(db.remove, undefined);
	test.notEqual(db.removeById, undefined);
	test.done()
}

exports["module init:db.connect before any operation"] = function(test){

	test.throws(
		function(){
			db.save();
		},
		Error
	);
	test.done();
}

//mock mongodb driver to fake connect

<|endoftext|>


<commit_before>var _ = require('lodash');

var analyze = (function (symbols) {
  var pattern_message = new RegExp('\\b(' + _(symbols).values().flatten().value().join('|') + ') #card-([0-9]+)\\b', 'gi');
  var pattern_symbols = _.transform(symbols, function (object, v, k) {
    object[k] = new RegExp('^(' + v.join('|') + ')$', 'i');
  });
  var pattern_reverts = /^reverts?\b/i;
  return function (commit) {
    var message = commit.message;
    var results = [];
    var match, last_symbol;
    while (match = pattern_message.exec(message)) {
      var symbol = _.findKey(pattern_symbols, function (exp) { return exp.test(match[1]); });
      if (symbol == '_') {
        symbol = last_symbol;
      }
      if (symbol) {
        results.push({
          symbol: symbol,
          cardId: match[2],
          revert: pattern_reverts.test(message),
          commit: commit });
      }
      last_symbol = symbol;
    }
    return results;
  };
})({
  'mention': [ 'see', 'refers? to' ],
  'fulfill': [ 'completes?', 'fulfills?', 'implements?', 'finish(?:es)?' ],
  '_': [ 'and', ', ?' ],
});

module.exports = {
  parse: analyze,
};

<commit_msg>add `fix(es)` support<commit_after>var _ = require('lodash');

var analyze = (function (symbols) {
  var pattern_message = new RegExp('\\b(' + _(symbols).values().flatten().value().join('|') + ') #card-([0-9]+)\\b', 'gi');
  var pattern_symbols = _.transform(symbols, function (object, v, k) {
    object[k] = new RegExp('^(' + v.join('|') + ')$', 'i');
  });
  var pattern_reverts = /^reverts?\b/i;
  return function (commit) {
    var message = commit.message;
    var results = [];
    var match, last_symbol;
    while (match = pattern_message.exec(message)) {
      var symbol = _.findKey(pattern_symbols, function (exp) { return exp.test(match[1]); });
      if (symbol == '_') {
        symbol = last_symbol;
      }
      if (symbol) {
        results.push({
          symbol: symbol,
          cardId: match[2],
          revert: pattern_reverts.test(message),
          commit: commit });
      }
      last_symbol = symbol;
    }
    return results;
  };
})({
  'mention': [ 'see', 'refers? to' ],
  'fulfill': [ 'completes?', 'fulfills?', 'implements?', 'finish(?:es)?', 'fix(?:es)?' ],
  '_': [ 'and', ', ?' ],
});

module.exports = {
  parse: analyze,
};

<|endoftext|>


<commit_before>/**
 * @fileoverview Provides a factory to create a popup in the page.
 * The factory returns a ngeo.Popup object.
 *
 * Example:
 *
 * var popup = ngeoCreatePopup();
 * popup.setTitle("A title");
 * popup.setContent("Some content");
 * popup.show();
 *
 */

goog.provide('ngeo.CreatePopup');
goog.provide('ngeo.Popup');

goog.require('ngeo');
goog.require('ngeo.popupDirective');

/**
 * @typedef {function():!ngeo.Popup}
 */
ngeo.CreatePopup;

/**
 * @constructor
 * @param {angular.$compile} $compile The compile provider.
 * @param {angular.Scope} $rootScope The rootScope provider.
 */
ngeo.Popup = function($compile, $rootScope) {

  /**
   * The scope the element is compiled with.
   * @type {angular.Scope}
   * @private
   */
  this.scope_ = $rootScope.$new();

  /**
   * The element.
   * @type {angular.JQLite}
   * @private
   */
  this.element_ = angular.element('

');

  // Add the element and its content to the document
  angular.element(document.body).append(this.element_);
  $compile(this.element_)(this.scope_);
};

/**
 * Display the popup
 */
ngeo.Popup.prototype.show = function() {
  this.scope_['open'] = true;
};

/**
 * Destroy the popup
 */
ngeo.Popup.prototype.destroy = function() {
  this.scope_.$destroy();
  this.element_.remove();
};

/**
 * Set the popup's title
 * @param {string} title The title
 */
ngeo.Popup.prototype.setTitle = function(title) {
  this.scope_['title'] = title;
};

/**
 * Set the popup's content
 * @param {string} content The content
 */
ngeo.Popup.prototype.setContent = function(content) {
  this.scope_['content'] = content;
};

/**
 * @param {angular.$compile} $compile Angular compile service.
 * @param {angular.Scope} $rootScope Angular rootScope service.
 * @return {ngeo.CreatePopup} The function to create a
 *     popup.
 * @ngInject
 */
ngeo.createPopupServiceFactory = function($compile, $rootScope) {
  return (
      /**
       * @return {!ngeo.Popup} The popup instance.
       */
      function() {
        return new ngeo.Popup($compile, $rootScope);
      });
};
ngeoModule.factory('ngeoCreatePopup', ngeo.createPopupServiceFactory);
<commit_msg>Minor doc reformatting<commit_after>/**
 * @fileoverview Provides a factory to create a popup in the page.
 * The factory returns a ngeo.Popup object.
 *
 * Example:
 *
 * var popup = ngeoCreatePopup();
 * popup.setTitle("A title");
 * popup.setContent("Some content");
 * popup.show();
 *
 */

goog.provide('ngeo.CreatePopup');
goog.provide('ngeo.Popup');

goog.require('ngeo');
goog.require('ngeo.popupDirective');

/**
 * @typedef {function():!ngeo.Popup}
 */
ngeo.CreatePopup;

/**
 * @constructor
 * @param {angular.$compile} $compile The compile provider.
 * @param {angular.Scope} $rootScope The rootScope provider.
 */
ngeo.Popup = function($compile, $rootScope) {

  /**
   * The scope the element is compiled with.
   * @type {angular.Scope}
   * @private
   */
  this.scope_ = $rootScope.$new();

  /**
   * The element.
   * @type {angular.JQLite}
   * @private
   */
  this.element_ = angular.element('

');

  // Add the element and its content to the document
  angular.element(document.body).append(this.element_);
  $compile(this.element_)(this.scope_);
};

/**
 * Display the popup
 */
ngeo.Popup.prototype.show = function() {
  this.scope_['open'] = true;
};

/**
 * Destroy the popup
 */
ngeo.Popup.prototype.destroy = function() {
  this.scope_.$destroy();
  this.element_.remove();
};

/**
 * Set the popup's title
 * @param {string} title The title
 */
ngeo.Popup.prototype.setTitle = function(title) {
  this.scope_['title'] = title;
};

/**
 * Set the popup's content
 * @param {string} content The content
 */
ngeo.Popup.prototype.setContent = function(content) {
  this.scope_['content'] = content;
};

/**
 * @param {angular.$compile} $compile Angular compile service.
 * @param {angular.Scope} $rootScope Angular rootScope service.
 * @return {ngeo.CreatePopup} The function to create a popup.
 * @ngInject
 */
ngeo.createPopupServiceFactory = function($compile, $rootScope) {
  return (
      /**
       * @return {!ngeo.Popup} The popup instance.
       */
      function() {
        return new ngeo.Popup($compile, $rootScope);
      });
};
ngeoModule.factory('ngeoCreatePopup', ngeo.createPopupServiceFactory);
<|endoftext|>


<commit_before>#!/usr/bin/env node
/*
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES, LOSS OF USE, DATA, OR PROFITS, OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

'use strict'

var program = require('commist')();
var runner = require('./runner')();
var shell = require('./shell')();
var util = require('./util')();
var pkg = require('./package.json');

var showVersion = function() {
  console.log('v' + pkg.version);
};

var buildSystem = function(args) {
  console.log('building...');
  util.compile(args, function(err, system, config) {
    runner.buildSystem(system, config, function(err) {
      if (err) { return console.error(err); }
    });
  });
};

var pullSystem = function (args) {
  console.log('pulling...')
  util.compile(args, function (err, system, config) {
    runner.pullSystem(system, config, function (err) {
      if (err) { return console.error(err) }
    })
  })
}

var runSystem = function (args) {
  console.log('compiling...')
  util.compile(args, function (err, system, config) {
    if (err) { return console.error(err) }
    shell.runSingleCommand(system, config, 'start all')
  })
}

var runShell = function (args) {
  console.log('compiling...')
  util.compile(args, function (err, system, config) {
    if (err) { return console.error(err) }
    shell.run(system, config)
  })
}

var previewSystem = function (args) {
  console.log('compiling...')
  util.compile(args, function (err, system, config) {
    if (err) { return console.error(err) }
    runner.previewSystem(system, config)
  })
}

var showHelp = function() {
  console.log('usage: fuge <command> <options>');
  console.log('');
  console.log('fuge build                      build a system by executing the RUN commands in each services Dockerfile');
  console.log('fuge pull                       update a system by attempting a git pull against each service');
  console.log('fuge run <compose-file>         run a system');
  console.log('fuge preview <compose-file>     preview a run command for a system');
  console.log('fuge shell <compose-file>       start an interactive shell for a system');
  console.log('fuge version                    version of fuge');
  console.log('fuge help                       show this help');
};

program.register('build', buildSystem);
program.register('pull', pullSystem);
program.register('run', runSystem);
program.register('preview', previewSystem);
program.register('shell', runShell);
program.register('version', showVersion);
program.register('--version', showVersion);
program.register('help', showHelp);
program.register('--help', showHelp);

function start(argv) {
  var remaining = program.parse(argv)
  if (remaining) { console.error('No matching command.') }
}

module.exports = start
if (require.main === module) {
  start(process.argv.slice(2))
}
<commit_msg>fuge.js linted<commit_after>#!/usr/bin/env node
/*
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES, LOSS OF USE, DATA, OR PROFITS, OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

'use strict'

var program = require('commist')();
var runner = require('./runner')();
var shell = require('./shell')();
var util = require('./util')();
var pkg = require('./package.json');

var showVersion = function() {
  console.log('v' + pkg.version);
};

var buildSystem = function (args) {
  console.log('building...')

  util.compile(args, function (err, system, config) {
    if (err) { return console.error(err) }

    runner.buildSystem(system, config, function (err) {
      if (err) { return console.error(err) }
    })
  })
}

var pullSystem = function (args) {
  console.log('pulling...')
  util.compile(args, function (err, system, config) {
    if (err) { return console.error(err) }

    runner.pullSystem(system, config, function (err) {
      if (err) { return console.error(err) }
    })
  })
}

var runSystem = function (args) {
  console.log('compiling...')
  util.compile(args, function (err, system, config) {
    if (err) { return console.error(err) }
    shell.runSingleCommand(system, config, 'start all')
  })
}

var runShell = function (args) {
  console.log('compiling...')
  util.compile(args, function (err, system, config) {
    if (err) { return console.error(err) }
    shell.run(system, config)
  })
}

var previewSystem = function (args) {
  console.log('compiling...')
  util.compile(args, function (err, system, config) {
    if (err) { return console.error(err) }
    runner.previewSystem(system, config)
  })
}

var showHelp = function() {
  console.log('usage: fuge <command> <options>');
  console.log('');
  console.log('fuge build                      build a system by executing the RUN commands in each services Dockerfile');
  console.log('fuge pull                       update a system by attempting a git pull against each service');
  console.log('fuge run <compose-file>         run a system');
  console.log('fuge preview <compose-file>     preview a run command for a system');
  console.log('fuge shell <compose-file>       start an interactive shell for a system');
  console.log('fuge version                    version of fuge');
  console.log('fuge help                       show this help');
};

program.register('build', buildSystem);
program.register('pull', pullSystem);
program.register('run', runSystem);
program.register('preview', previewSystem);
program.register('shell', runShell);
program.register('version', showVersion);
program.register('--version', showVersion);
program.register('help', showHelp);
program.register('--help', showHelp);

function start (argv) {
  var remaining = program.parse(argv)
  if (remaining) { console.error('No matching command.') }
}

module.exports = start
if (require.main === module) {
  start(process.argv.slice(2))
}
<|endoftext|>


<commit_before>// Shade.constant creates a constant value in the Shade language.
//
// This value can be one of:
// - a single float:
//    Shade.constant(1)
//    Shade.constant(3.0, Shade.Types.float_t)
// - a single integer:
//    Shade.constant(1, Shade.Types.int_t)
// - a boolean:
//    Shade.constant(false);
// - a GLSL vec2, vec3 or vec4 (of floating point values):
//    Shade.constant(2, vec.make([1, 2]));
// - a GLSL matrix of dimensions 2x2, 3x3, 4x4 (Facet currently does not support GLSL rectangular matrices):
//    Shade.constant(2, mat.make([1, 0, 0, 1]));
// - An array of constant values of the same type:
//    Shade.constant([2, 3, 4, 5, 6]);

Shade.constant = function(v, type)
{
    var mat_length_to_dimension = {16: 4, 9: 3, 4: 2, 1: 1};

    var constant_tuple_fun = function(type, args)
    {
        function to_glsl(type, args) {
            // this seems incredibly ugly, but we need something
            // like it, so that numbers are appropriately promoted to floats
            // in GLSL's syntax.

            var string_args = _.map(args, function(arg) {
                var v = String(arg);
                if (facet_typeOf(arg) === "number" && v.indexOf(".") === -1) {
                    return v + ".0";
                } else
                    return v;
            });
            return type + '(' + _.toArray(string_args).join(', ') + ')';
        }

        function matrix_row(i) {
            var sz = type.array_size();
            var result = [];
            for (var j=0; j<sz; ++j) {
                result.push(args[i + j*sz]);
            }
            return result;
        }

        return Shade._create_concrete_exp( {
            evaluate: function(glsl_name) {
                return to_glsl(this.type.repr(), args);
            },
            expression_type: "constant{" + args + "}",
            is_constant: function() { return true; },
            element: Shade.memoize_on_field("_element", function(i) {
                if (this.type.is_pod()) {
                    if (i === 0)
                        return this;
                    else
                        throw "float is an atomic type, got this: " + i;
                } if (this.type.is_vec()) {
                    return Shade.constant(args[i]);
                } else {
                    return Shade.vec.apply(matrix_row(i));
                }
            }),
            element_is_constant: function(i) {
                return true;
            },
            element_constant_value: Shade.memoize_on_field("_element_constant_value", function(i) {
                if (this.type.equals(Shade.Types.float_t)) {
                    if (i === 0)
                        return args[0];
                    else
                        throw "float is an atomic type";
                } if (this.type.is_vec()) {
                    return args[i];
                }
                return vec[this.type.array_size()].make(matrix_row(i));
            }),
            constant_value: Shade.memoize_on_field("_constant_value", function() {
                // FIXME boolean_vector
                if (this.type.is_pod())
                    return args[0];
                if (this.type.equals(Shade.Types.vec2) ||
                    this.type.equals(Shade.Types.vec3) ||
                    this.type.equals(Shade.Types.vec4))
                    return vec[args.length].make(args);
                if (this.type.equals(Shade.Types.mat2) ||
                    this.type.equals(Shade.Types.mat3) ||
                    this.type.equals(Shade.Types.mat4))
                    return mat[mat_length_to_dimension[args.length]].make(args);
                else
                    throw "internal error: constant of unknown type";
            }),
            compile: function(ctx) {},
            parents: [],
            type: type
        });
    };

    var t = facet_constant_type(v);
    if (t === 'other') {
        t = facet_typeOf(v);
        if (t === 'array') {
            var new_v = v.map(Shade.make);
            var array_size = new_v.length;
            if (array_size === 0) {
                throw "array constant must be non-empty";
            }

            var new_types = new_v.map(function(t) { return t.type; });
            var array_type = Shade.array(new_types[0], array_size);
            if (_.any(new_types, function(t) { return !t.equals(new_types[0]); })) {
                throw "array elements must have identical types";
            }
            if (_.any(new_v, function(el) { return !el.is_constant(); })) {
                throw "constant array elements must be constant as well";
            }
            return Shade._create_concrete_exp( {
                parents: new_v,
                type: array_type,
                expression_type: "constant",
                evaluate: function() { return this.glsl_name; },
                compile: function (ctx) {
                    this.array_initializer_glsl_name = ctx.request_fresh_glsl_name();
                    ctx.strings.push(this.type.declare(this.glsl_name), ";\n");
                    ctx.strings.push("void", this.array_initializer_glsl_name, "(void) {\n");
                    for (var i=0; i<this.parents.length; ++i) {
                        ctx.strings.push("    ", this.glsl_name, "[", i, "] =",
                                         this.parents[i].evaluate(), ";\n");
                    }
                    ctx.strings.push("}\n");
                    ctx.add_initialization(this.array_initializer_glsl_name + "()");
                },
                is_constant: function() { return true; },
                element: function(i) {
                    return this.parents[i];
                },
                element_is_constant: function(i) {
                    return this.parents[i].is_constant();
                },
                element_constant_value: function(i) {
                    return this.parents[i].constant_value();
                }
            });
        } else {
            throw "type error: constant should be bool, number, vector, matrix or array. got " + t
            + " instead";
        }
    }
    if (t === 'number') {
        if (type && !(type.equals(Shade.Types.float_t) ||
                      type.equals(Shade.Types.int_t))) {
            throw ("expected specified type for numbers to be float or int," +
                   " got " + type.repr() + " instead.");
        }
        return constant_tuple_fun(type || Shade.Types.float_t, [v]);
    }
    if (t === 'boolean') {
        if (type && !type.equals(Shade.Types.bool_t))
            throw ("boolean constants cannot be interpreted as " +
                   type.repr());
        return constant_tuple_fun(Shade.Types.bool_t, [v]);
    }
    var d, computed_t;
    if (t === 'vector') {
        d = v.length;
        if (d < 2 && d > 4)
            throw "invalid length for constant vector: " + v;
        var el_ts = _.map(v, function(t) { return facet_typeOf(t); });
        if (!_.all(el_ts, function(t) { return t === el_ts[0]; })) {
            throw "not all constant params have the same types";
        }
        if (el_ts[0] === "number") {
            computed_t = Shade.basic('vec' + d);
            if (type && !computed_t.equals(type)) {
                throw "passed constant must have type " + computed_t.repr()
                    + ", but was request to have incompatible type "
                    + type.repr();
            }
            return constant_tuple_fun(computed_t, v);
        }
        else
            throw "bad datatype for constant: " + el_ts[0];
    }
    if (t === 'matrix') {
        d = mat_length_to_dimension[v.length];
        computed_t = Shade.basic('mat' + d);
        if (type && !computed_t.equals(type)) {
            throw "passed constant must have type " + computed_t.repr()
                + ", but was request to have incompatible type "
                + type.repr();
        }
        return constant_tuple_fun(computed_t, v);
    }
    throw "internal error: facet_constant_type returned bogus value";
};

Shade.as_int = function(v) { return Shade.make(v).as_int(); };
Shade.as_bool = function(v) { return Shade.make(v).as_bool(); };
Shade.as_float = function(v) { return Shade.make(v).as_float(); };

<commit_msg>better exception message for constant.element<commit_after>// Shade.constant creates a constant value in the Shade language.
//
// This value can be one of:
// - a single float:
//    Shade.constant(1)
//    Shade.constant(3.0, Shade.Types.float_t)
// - a single integer:
//    Shade.constant(1, Shade.Types.int_t)
// - a boolean:
//    Shade.constant(false);
// - a GLSL vec2, vec3 or vec4 (of floating point values):
//    Shade.constant(2, vec.make([1, 2]));
// - a GLSL matrix of dimensions 2x2, 3x3, 4x4 (Facet currently does not support GLSL rectangular matrices):
//    Shade.constant(2, mat.make([1, 0, 0, 1]));
// - An array of constant values of the same type:
//    Shade.constant([2, 3, 4, 5, 6]);

Shade.constant = function(v, type)
{
    var mat_length_to_dimension = {16: 4, 9: 3, 4: 2, 1: 1};

    var constant_tuple_fun = function(type, args)
    {
        function to_glsl(type, args) {
            // this seems incredibly ugly, but we need something
            // like it, so that numbers are appropriately promoted to floats
            // in GLSL's syntax.

            var string_args = _.map(args, function(arg) {
                var v = String(arg);
                if (facet_typeOf(arg) === "number" && v.indexOf(".") === -1) {
                    return v + ".0";
                } else
                    return v;
            });
            return type + '(' + _.toArray(string_args).join(', ') + ')';
        }

        function matrix_row(i) {
            var sz = type.array_size();
            var result = [];
            for (var j=0; j<sz; ++j) {
                result.push(args[i + j*sz]);
            }
            return result;
        }

        return Shade._create_concrete_exp( {
            evaluate: function(glsl_name) {
                return to_glsl(this.type.repr(), args);
            },
            expression_type: "constant{" + args + "}",
            is_constant: function() { return true; },
            element: Shade.memoize_on_field("_element", function(i) {
                if (this.type.is_pod()) {
                    if (i === 0)
                        return this;
                    else
                        throw this.type.repr() + " is an atomic type, got this: " + i;
                } else if (this.type.is_vec()) {
                    return Shade.constant(args[i]);
                } else {
                    return Shade.vec.apply(matrix_row(i));
                }
            }),
            element_is_constant: function(i) {
                return true;
            },
            element_constant_value: Shade.memoize_on_field("_element_constant_value", function(i) {
                if (this.type.equals(Shade.Types.float_t)) {
                    if (i === 0)
                        return args[0];
                    else
                        throw "float is an atomic type";
                } if (this.type.is_vec()) {
                    return args[i];
                }
                return vec[this.type.array_size()].make(matrix_row(i));
            }),
            constant_value: Shade.memoize_on_field("_constant_value", function() {
                // FIXME boolean_vector
                if (this.type.is_pod())
                    return args[0];
                if (this.type.equals(Shade.Types.vec2) ||
                    this.type.equals(Shade.Types.vec3) ||
                    this.type.equals(Shade.Types.vec4))
                    return vec[args.length].make(args);
                if (this.type.equals(Shade.Types.mat2) ||
                    this.type.equals(Shade.Types.mat3) ||
                    this.type.equals(Shade.Types.mat4))
                    return mat[mat_length_to_dimension[args.length]].make(args);
                else
                    throw "internal error: constant of unknown type";
            }),
            compile: function(ctx) {},
            parents: [],
            type: type
        });
    };

    var t = facet_constant_type(v);
    if (t === 'other') {
        t = facet_typeOf(v);
        if (t === 'array') {
            var new_v = v.map(Shade.make);
            var array_size = new_v.length;
            if (array_size === 0) {
                throw "array constant must be non-empty";
            }

            var new_types = new_v.map(function(t) { return t.type; });
            var array_type = Shade.array(new_types[0], array_size);
            if (_.any(new_types, function(t) { return !t.equals(new_types[0]); })) {
                throw "array elements must have identical types";
            }
            if (_.any(new_v, function(el) { return !el.is_constant(); })) {
                throw "constant array elements must be constant as well";
            }
            return Shade._create_concrete_exp( {
                parents: new_v,
                type: array_type,
                expression_type: "constant",
                evaluate: function() { return this.glsl_name; },
                compile: function (ctx) {
                    this.array_initializer_glsl_name = ctx.request_fresh_glsl_name();
                    ctx.strings.push(this.type.declare(this.glsl_name), ";\n");
                    ctx.strings.push("void", this.array_initializer_glsl_name, "(void) {\n");
                    for (var i=0; i<this.parents.length; ++i) {
                        ctx.strings.push("    ", this.glsl_name, "[", i, "] =",
                                         this.parents[i].evaluate(), ";\n");
                    }
                    ctx.strings.push("}\n");
                    ctx.add_initialization(this.array_initializer_glsl_name + "()");
                },
                is_constant: function() { return true; },
                element: function(i) {
                    return this.parents[i];
                },
                element_is_constant: function(i) {
                    return this.parents[i].is_constant();
                },
                element_constant_value: function(i) {
                    return this.parents[i].constant_value();
                }
            });
        } else {
            throw "type error: constant should be bool, number, vector, matrix or array. got " + t
            + " instead";
        }
    }
    if (t === 'number') {
        if (type && !(type.equals(Shade.Types.float_t) ||
                      type.equals(Shade.Types.int_t))) {
            throw ("expected specified type for numbers to be float or int," +
                   " got " + type.repr() + " instead.");
        }
        return constant_tuple_fun(type || Shade.Types.float_t, [v]);
    }
    if (t === 'boolean') {
        if (type && !type.equals(Shade.Types.bool_t))
            throw ("boolean constants cannot be interpreted as " +
                   type.repr());
        return constant_tuple_fun(Shade.Types.bool_t, [v]);
    }
    var d, computed_t;
    if (t === 'vector') {
        d = v.length;
        if (d < 2 && d > 4)
            throw "invalid length for constant vector: " + v;
        var el_ts = _.map(v, function(t) { return facet_typeOf(t); });
        if (!_.all(el_ts, function(t) { return t === el_ts[0]; })) {
            throw "not all constant params have the same types";
        }
        if (el_ts[0] === "number") {
            computed_t = Shade.basic('vec' + d);
            if (type && !computed_t.equals(type)) {
                throw "passed constant must have type " + computed_t.repr()
                    + ", but was request to have incompatible type "
                    + type.repr();
            }
            return constant_tuple_fun(computed_t, v);
        }
        else
            throw "bad datatype for constant: " + el_ts[0];
    }
    if (t === 'matrix') {
        d = mat_length_to_dimension[v.length];
        computed_t = Shade.basic('mat' + d);
        if (type && !computed_t.equals(type)) {
            throw "passed constant must have type " + computed_t.repr()
                + ", but was request to have incompatible type "
                + type.repr();
        }
        return constant_tuple_fun(computed_t, v);
    }
    throw "internal error: facet_constant_type returned bogus value";
};

Shade.as_int = function(v) { return Shade.make(v).as_int(); };
Shade.as_bool = function(v) { return Shade.make(v).as_bool(); };
Shade.as_float = function(v) { return Shade.make(v).as_float(); };

<|endoftext|>


<commit_before>/** internal
 *  class Context
 *
 *  `Context` provides helper methods to all [[Template]] processors.
 *  They are typically accessed by EJS templates. You can mix in custom
 *  helpers by injecting them into [[Environment#ContextClass]]. Do not
 *  mix them into `Context` directly.
 *
 *      environment.registerHelper('asset_url', function () {
 *        // ...
 *      });
 *
 *      // or in batch-mode
 *      environment.registerHelper({
 *        asset_url: function () {
 *          // ...
 *        },
 *        // ...
 *      });
 *
 *      <%= asset_url("foo.png") %>
 *
 *  The `Context` also collects dependencies declared by assets.
 *  See [[DirectiveProcessor]] for an example of this.
 **/

'use strict';

// stdlib
var fs        = require('fs');
var path      = require('path');
var inherits  = require('util').inherits;

// 3rd-party
var _ = require('underscore');
var async = require('async');

// internal
var getter = require('./common').getter;
var prop   = require('./common').prop;

////////////////////////////////////////////////////////////////////////////////

/**
 *  new Context(environment, logicalPath, pathname)
 *  - environment (Environment)
 *  - logicalPath (String)
 *  - pathname (String)
 **/
var Context = module.exports = function Context(environment, logicalPath, pathname) {
  prop(this, 'environment',           environment);
  prop(this, 'pathname',              pathname);

  prop(this, '__logicalPath__',       logicalPath);

  prop(this, '__requiredPaths__',     []);
  prop(this, '__stubbedAssets__',     []);
  prop(this, '__dependencyPaths__',   []);
  prop(this, '__dependencyAssets__',  [pathname]);

  prop(this, '__LINE__',              null, {writable: true});
};

// Hash of helpers available as locals in the renderers.
// For each helper, a wrpper will be generated to preserve `this` context.
//
// See Context.registerHelper()
prop(Context.prototype, '__helpers__', {asset_data_uri: 'assetDataUri'});

/**
 *  Context#rootPath -> String
 *
 *  Returns the environment path that contains the file.
 *
 *  If `app/javascripts` and `app/stylesheets` are in your path, and
 *  current file is `app/javascripts/foo/bar.js`, `root_path` would
 *  return `app/javascripts`.
 **/
getter(Context.prototype, 'rootPath', function () {
  var pathname = this.pathname;
  return _.find(this.environment.paths, function (path) {
    return pathname.substr(0, path.length) === path;
  }).substr(this.environment.root.length + 1);
});

/**
 * Context#logicalPath -> String
 *
 *  Returns logical path without any file extensions.
 *
 *      'app/javascripts/application.js'
 *      # => 'app/javascripts/application'
 **/
getter(Context.prototype, 'logicalPath', function () {
  var len = this.__logicalPath__.length, ext = path.extname(this.__logicalPath__);
  return this.__logicalPath__.substr(0, len - ext.length);
});

/**
 *  Context#contentType -> String
 *
 *  Returns content type of file
 *
 *      'application/javascript'
 *      'text/css'
 **/
getter(Context.prototype, 'contentType', function () {
  return this.environment.contentTypeOf(this.pathname);
});

/**
 *  Context#resolve(pathname[, options = {}[, fn]]) -> String
 *  - pathname (String)
 *  - options (Object)
 *  - fn (Function)
 *
 *  Given a logical path, `resolve` will find and return the fully
 *  expanded path. Relative paths will also be resolved. An optional
 *  `contentType` restriction can be supplied to restrict the
 *  search.
 *
 *      context.resolve("foo.js")
 *      # => "/path/to/app/javascripts/foo.js"
 *
 *      context.resolve("./bar.js")
 *      # => "/path/to/app/javascripts/bar.js"
 *
 *      context.resolve("foo", {contentType: 'application/javascript'})
 *      # => "/path/to/app/javascripts/foo.js"
 *
 *  You may also provide an iterator function `fn`, that wil be passed to
 *  environments [[Base#resolve]] when needed.
 **/
Context.prototype.resolve = function (pathname, options, fn) {
  var self = this, attributes, content_type, resolved;

  options = options || {};

  if ('/' === pathname[0]) {
    if (fs.existsSync(pathname)) {
      return pathname;
    }

    throw new Error("Couldn't find file '" + pathname + "'");
  }

  content_type = options.contentType;

  if (content_type) {
    if ('self' === options.contentType) {
      content_type = self.contentType;
    }

    attributes = this.environment.attributesFor(pathname);
    if (attributes.formatExtension && content_type !== attributes.contentType) {
      throw new Error(pathname + " is '" + attributes.contentType + "', " +
                      "not '" + content_type + "'");
    }

    resolved = this.resolve(pathname, {}, function (candidate) {
      if (self.contentType === self.environment.contentTypeOf(candidate)) {
        return candidate;
      }
    });

    if (!resolved) {
      throw new Error("Could not find file '" + pathname + "'.");
    }

    return resolved;
  }

  return this.environment.resolve(pathname, _.extend({
    basePath: path.dirname(this.pathname)
  }, options), fn);
};

/**
 *  Context#dependOn(pathname) -> Void
 *
 *  Allows you to state a dependency on a file without including it.
 *
 *  This is used for caching purposes. Any changes made to
 *  the dependency file with invalidate the cache of the
 *  source file.
 **/
Context.prototype.dependOn = function (pathname) {
  this.__dependencyPaths__.push(this.resolve(pathname));
};

/**
 *  Context#dependOnAsset(pathname) -> Void
 *
 *  Allows you to state an asset dependency without including it.
 *
 *  This is used for caching purposes. Any changes that would
 *  invalidate the dependency asset will invalidate the source
 *  file. Unlike [[Context#dependOn]], this will include recursively
 *  the target asset's dependencies.
 **/
Context.prototype.dependOnAsset = function (pathname) {
  this.__dependencyAssets__.push(this.resolve(pathname));
};

/**
 *  Context#requireAsset(pathname) -> Void
 *
 *  `require_asset` declares `path` as a dependency of the file. The
 *  dependency will be inserted before the file and will only be
 *  included once.
 *
 *  If EJS processing is enabled, you can use it to dynamically
 *  require assets.
 *
 *      <%= requireAsset("#{framework}.js") %>
 **/
Context.prototype.requireAsset = function (pathname) {
  pathname = this.resolve(pathname, {contentType: 'self'});
  this.dependOnAsset(pathname);
  this.__requiredPaths__.push(pathname);
};

/**
 *  Context#stubAsset(pathname) -> Void
 *
 *  `stubAsset` blacklists `pathname` from being included in the bundle.
 *  `pathname` must be an asset which may or may not already be included
 *  in the bundle.
 **/
Context.prototype.stubAsset = function (pathname) {
  this.__stubbedAssets__.push(this.resolve(pathname, {contentType: 'self'}));
};

/**
 *  Context#isAssetRequirable(pathname) -> Boolean
 *
 *  Tests if target path is able to be safely required into the
 *  current concatenation.
 **/
Context.prototype.isAssetRequirable = function (pathname) {
  var content_type, stat;

  pathname      = this.resolve(pathname);
  content_type  = this.environment.contentTypeOf(pathname);
  stat          = this.environment.stat(pathname);

  return stat && stat.isFile() &&
         (!this.contentType || this.contentType === content_type);
};

/**
 *  Context#assetDataUri(pathname) -> String
 *
 *  Returns a Base64-encoded `data:` URI with the contents of the
 *  asset at the specified path, and marks that path as a dependency
 *  of the current file.
 *
 *  Use `assetDataUri` from EJS with CSS or JavaScript assets:
 *
 *      #logo { background: url(<%= asset_data_uri('logo.png') %>) }
 *
 *      $('<img>').attr('src', '<%= asset_data_uri('avatar.jpg') %>')
 **/
Context.prototype.assetDataUri = function (pathname) {
  var asset = this.environment.findAsset(pathname),
      buff  = asset.buffer || new Buffer(asset.toString());

  this.dependOn(pathname);
  return "data:" + asset.contentType + ";base64," + buff.toString('base64');
};

/**
 *  Context#evaluate(pathname, options = {}, callback) -> Void
 *  - pathname (String)
 *  - options (Object)
 *  - callback (Function)
 *
 *  Reads `pathname` and runs processors on the file.
 **/
Context.prototype.evaluate = function (pathname, options, callback) {
  var self = this, attributes, processors, result, locals = {};

  options     = options || {};
  pathname    = this.resolve(pathname);
  attributes  = this.environment.attributesFor(pathname);
  processors  = options.processors || attributes.processors;
  result      = !!options.data ? options.data
              : fs.readFileSync(pathname, 'utf8');

  _.each(this.__helpers__, function (func, name) {
    locals[name] = function () {
      return self[func].apply(self, arguments);
    };
  });

  async.forEachSeries(processors, function (ProcessorKlass, next) {
    var template = new ProcessorKlass(pathname, function () {
      return result;
    });

    template.evaluate(self, locals, function (err, data) {
      result = data;
      next(err);
    });
  }, function (err) {
    callback(err, result);
  });
};

// internal helper to define registerHelper() method on destination class
function define_helpers_registrator(Klass) {
  Klass.registerHelper = function (name, func) {
    // Scenario: registerHelper('foo', foo_helper);
    if (_.isString(name)) {
      Klass.prototype[name]             = func;
      Klass.prototype.__helpers__[name] = name;
      return;
    }

    // Scenario: registerHelper({ foo: foo_helper, ... });
    _.each(name, function (func, name) {
      Klass.registerHelper(name, func);
    });
  };
}

/**
 *  Context.registerHelper(name, func) -> Void
 *  Context.registerHelper(helpers) -> Void
 *  - name (String)
 *  - func (Function)
 *  - helpers (Object)
 *
 *  Register a helper that will be available in the engines that supports
 *  local helpers (e.g. EJS or Stylus). You should avoid registering helpers
 *  directly on `Context` class in favour of [[Environment#ContextClass]]
 *  (see [[Environment#registerHelper]] as well).
 *
 *  ##### Example
 *
 *      Context.registerHelper('foo', foo_helper);
 *      Context.registerHelper('bar', bar_helper);
 *
 *      // equals to
 *
 *      Context.registerHelper({
 *        foo: foo_helper,
 *        bar: bar_helper
 *      });
 **/
define_helpers_registrator(Context);

/** internal
 *  Context#subclass -> Function
 *
 *  Returns new subclass of [[Context]].
 **/
getter(Context, 'subclass', function () {
  var Klass = function () { Context.apply(this, arguments); };

  // add class inheritance
  inherits(Klass, Context);

  // clone some own-prototype properties
  prop(Klass.prototype, '__helpers__', _.clone(Context.prototype.__helpers__));

  // Provide helpers registrator
  define_helpers_registrator(Klass);

  return Klass;
});
<commit_msg>Small fix to the context<commit_after>/** internal
 *  class Context
 *
 *  `Context` provides helper methods to all [[Template]] processors.
 *  They are typically accessed by EJS templates. You can mix in custom
 *  helpers by injecting them into [[Environment#ContextClass]]. Do not
 *  mix them into `Context` directly.
 *
 *      environment.registerHelper('asset_url', function () {
 *        // ...
 *      });
 *
 *      // or in batch-mode
 *      environment.registerHelper({
 *        asset_url: function () {
 *          // ...
 *        },
 *        // ...
 *      });
 *
 *      <%= asset_url("foo.png") %>
 *
 *  The `Context` also collects dependencies declared by assets.
 *  See [[DirectiveProcessor]] for an example of this.
 **/

'use strict';

// stdlib
var fs        = require('fs');
var path      = require('path');
var inherits  = require('util').inherits;

// 3rd-party
var _ = require('underscore');
var async = require('async');

// internal
var getter = require('./common').getter;
var prop   = require('./common').prop;

////////////////////////////////////////////////////////////////////////////////

/**
 *  new Context(environment, logicalPath, pathname)
 *  - environment (Environment)
 *  - logicalPath (String)
 *  - pathname (String)
 **/
var Context = module.exports = function Context(environment, logicalPath, pathname) {
  prop(this, 'environment',           environment);
  prop(this, 'pathname',              pathname);

  prop(this, '__logicalPath__',       logicalPath);

  prop(this, '__requiredPaths__',     []);
  prop(this, '__stubbedAssets__',     []);
  prop(this, '__dependencyPaths__',   []);
  prop(this, '__dependencyAssets__',  [pathname]);

  prop(this, '__LINE__',              null, {writable: true});
};

// Hash of helpers available as locals in the renderers.
// For each helper, a wrpper will be generated to preserve `this` context.
//
// See Context.registerHelper()
prop(Context.prototype, '__helpers__', {asset_data_uri: 'assetDataUri'});

/**
 *  Context#rootPath -> String
 *
 *  Returns the environment path that contains the file.
 *
 *  If `app/javascripts` and `app/stylesheets` are in your path, and
 *  current file is `app/javascripts/foo/bar.js`, `root_path` would
 *  return `app/javascripts`.
 **/
getter(Context.prototype, 'rootPath', function () {
  var pathname = this.pathname;
  return _.find(this.environment.paths, function (path) {
    return pathname.substr(0, path.length) === path;
  }).substr(this.environment.root.length + 1);
});

/**
 * Context#logicalPath -> String
 *
 *  Returns logical path without any file extensions.
 *
 *      'app/javascripts/application.js'
 *      # => 'app/javascripts/application'
 **/
getter(Context.prototype, 'logicalPath', function () {
  var len = this.__logicalPath__.length, ext = path.extname(this.__logicalPath__);
  return this.__logicalPath__.substr(0, len - ext.length);
});

/**
 *  Context#contentType -> String
 *
 *  Returns content type of file
 *
 *      'application/javascript'
 *      'text/css'
 **/
getter(Context.prototype, 'contentType', function () {
  return this.environment.contentTypeOf(this.pathname);
});

/**
 *  Context#resolve(pathname[, options = {}[, fn]]) -> String
 *  - pathname (String)
 *  - options (Object)
 *  - fn (Function)
 *
 *  Given a logical path, `resolve` will find and return the fully
 *  expanded path. Relative paths will also be resolved. An optional
 *  `contentType` restriction can be supplied to restrict the
 *  search.
 *
 *      context.resolve("foo.js")
 *      # => "/path/to/app/javascripts/foo.js"
 *
 *      context.resolve("./bar.js")
 *      # => "/path/to/app/javascripts/bar.js"
 *
 *      context.resolve("foo", {contentType: 'application/javascript'})
 *      # => "/path/to/app/javascripts/foo.js"
 *
 *  You may also provide an iterator function `fn`, that wil be passed to
 *  environments [[Base#resolve]] when needed.
 **/
Context.prototype.resolve = function (pathname, options, fn) {
  var self = this, attributes, content_type, resolved;

  options = options || {};

  if ('/' === pathname[0]) {
    if (fs.existsSync(pathname)) {
      return pathname;
    }

    throw new Error("Couldn't find file '" + pathname + "'");
  }

  content_type = options.contentType;

  if (content_type) {
    if ('~self~' === content_type) {
      content_type = self.contentType;
    }

    attributes = this.environment.attributesFor(pathname);
    if (attributes.formatExtension && content_type !== attributes.contentType) {
      throw new Error(pathname + " is '" + attributes.contentType + "', " +
                      "not '" + content_type + "'");
    }

    resolved = this.resolve(pathname, {}, function (candidate) {
      if (self.contentType === self.environment.contentTypeOf(candidate)) {
        return candidate;
      }
    });

    if (!resolved) {
      throw new Error("Could not find file '" + pathname + "'.");
    }

    return resolved;
  }

  return this.environment.resolve(pathname, _.extend({
    basePath: path.dirname(this.pathname)
  }, options), fn);
};

/**
 *  Context#dependOn(pathname) -> Void
 *
 *  Allows you to state a dependency on a file without including it.
 *
 *  This is used for caching purposes. Any changes made to
 *  the dependency file with invalidate the cache of the
 *  source file.
 **/
Context.prototype.dependOn = function (pathname) {
  this.__dependencyPaths__.push(this.resolve(pathname));
};

/**
 *  Context#dependOnAsset(pathname) -> Void
 *
 *  Allows you to state an asset dependency without including it.
 *
 *  This is used for caching purposes. Any changes that would
 *  invalidate the dependency asset will invalidate the source
 *  file. Unlike [[Context#dependOn]], this will include recursively
 *  the target asset's dependencies.
 **/
Context.prototype.dependOnAsset = function (pathname) {
  this.__dependencyAssets__.push(this.resolve(pathname));
};

/**
 *  Context#requireAsset(pathname) -> Void
 *
 *  `requireAsset` declares `path` as a dependency of the file. The
 *  dependency will be inserted before the file and will only be
 *  included once.
 *
 *  If EJS processing is enabled, you can use it to dynamically
 *  require assets.
 *
 *      <%= requireAsset("#{framework}.js") %>
 **/
Context.prototype.requireAsset = function (pathname) {
  pathname = this.resolve(pathname, {contentType: '~self~'});
  this.dependOnAsset(pathname);
  this.__requiredPaths__.push(pathname);
};

/**
 *  Context#stubAsset(pathname) -> Void
 *
 *  `stubAsset` blacklists `pathname` from being included in the bundle.
 *  `pathname` must be an asset which may or may not already be included
 *  in the bundle.
 **/
Context.prototype.stubAsset = function (pathname) {
  this.__stubbedAssets__.push(this.resolve(pathname, {contentType: '~self~'}));
};

/**
 *  Context#isAssetRequirable(pathname) -> Boolean
 *
 *  Tests if target path is able to be safely required into the
 *  current concatenation.
 **/
Context.prototype.isAssetRequirable = function (pathname) {
  var content_type, stat;

  pathname      = this.resolve(pathname);
  content_type  = this.environment.contentTypeOf(pathname);
  stat          = this.environment.stat(pathname);

  return stat && stat.isFile() &&
         (!this.contentType || this.contentType === content_type);
};

/**
 *  Context#assetDataUri(pathname) -> String
 *
 *  Returns a Base64-encoded `data:` URI with the contents of the
 *  asset at the specified path, and marks that path as a dependency
 *  of the current file.
 *
 *  Use `assetDataUri` from EJS with CSS or JavaScript assets:
 *
 *      #logo { background: url(<%= asset_data_uri('logo.png') %>) }
 *
 *      $('<img>').attr('src', '<%= asset_data_uri('avatar.jpg') %>')
 **/
Context.prototype.assetDataUri = function (pathname) {
  var asset = this.environment.findAsset(pathname),
      buff  = asset.buffer || new Buffer(asset.toString());

  this.dependOn(pathname);
  return "data:" + asset.contentType + ";base64," + buff.toString('base64');
};

/**
 *  Context#evaluate(pathname, options = {}, callback) -> Void
 *  - pathname (String)
 *  - options (Object)
 *  - callback (Function)
 *
 *  Reads `pathname` and runs processors on the file.
 **/
Context.prototype.evaluate = function (pathname, options, callback) {
  var self = this, attributes, processors, result, locals = {};

  options     = options || {};
  pathname    = this.resolve(pathname);
  attributes  = this.environment.attributesFor(pathname);
  processors  = options.processors || attributes.processors;
  result      = !!options.data ? options.data
              : fs.readFileSync(pathname, 'utf8');

  _.each(this.__helpers__, function (func, name) {
    locals[name] = function () {
      return self[func].apply(self, arguments);
    };
  });

  async.forEachSeries(processors, function (ProcessorKlass, next) {
    var template = new ProcessorKlass(pathname, function () {
      return result;
    });

    template.evaluate(self, locals, function (err, data) {
      result = data;
      next(err);
    });
  }, function (err) {
    callback(err, result);
  });
};

// internal helper to define registerHelper() method on destination class
function define_helpers_registrator(Klass) {
  Klass.registerHelper = function (name, func) {
    // Scenario: registerHelper('foo', foo_helper);
    if (_.isString(name)) {
      Klass.prototype[name]             = func;
      Klass.prototype.__helpers__[name] = name;
      return;
    }

    // Scenario: registerHelper({ foo: foo_helper, ... });
    _.each(name, function (func, name) {
      Klass.registerHelper(name, func);
    });
  };
}

/**
 *  Context.registerHelper(name, func) -> Void
 *  Context.registerHelper(helpers) -> Void
 *  - name (String)
 *  - func (Function)
 *  - helpers (Object)
 *
 *  Register a helper that will be available in the engines that supports
 *  local helpers (e.g. EJS or Stylus). You should avoid registering helpers
 *  directly on `Context` class in favour of [[Environment#ContextClass]]
 *  (see [[Environment#registerHelper]] as well).
 *
 *  ##### Example
 *
 *      Context.registerHelper('foo', foo_helper);
 *      Context.registerHelper('bar', bar_helper);
 *
 *      // equals to
 *
 *      Context.registerHelper({
 *        foo: foo_helper,
 *        bar: bar_helper
 *      });
 **/
define_helpers_registrator(Context);

/** internal
 *  Context#subclass -> Function
 *
 *  Returns new subclass of [[Context]].
 **/
getter(Context, 'subclass', function () {
  var Klass = function () { Context.apply(this, arguments); };

  // add class inheritance
  inherits(Klass, Context);

  // clone some own-prototype properties
  prop(Klass.prototype, '__helpers__', _.clone(Context.prototype.__helpers__));

  // Provide helpers registrator
  define_helpers_registrator(Klass);

  return Klass;
});
<|endoftext|>


<commit_before>$(function() {
    window.onload = function() {
    console.log("%c  ~~~  Bob v0.2 - Developed by d4rkd0s  ~~~  ", "color: #FFFFFF; font-size: 12px; background: #3F1338;");
    var game = new Phaser.Game(1156, 650, Phaser.AUTO, '', { preload: preload, create: create, update: update });
    function preload() {
        //setting up starting vars
        score = 0;
        console.log("%c   score: 0   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");
        lives = 3;
        console.log("%c   lives: 3   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");

        //game.load.image('bob', 'assets/images/bob.png');
        game.load.spritesheet('bob', 'assets/images/bob.png', 54, 80);
        console.log("%c   loaded: spritesheet   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('background', 'assets/images/background.png');
        console.log("%c   loaded: background   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        //game.load.image('healthbar', 'assets/images/healthbar.png');
        //console.log("%c   loaded: healthbar   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('ocean', 'assets/images/ocean.png');
        console.log("%c   loaded: horse   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('horse', 'assets/images/horse.png');
        console.log("%c   set border: ocean   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        cursors = game.input.keyboard.createCursorKeys();
        console.log("%c   user input: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        //game.load.audio('jumpsound', 'assets/sounds/jump.wav');

        //walking case switch
        function coroutine(f) {
           var o = f(); // instantiate the coroutine
           o.next(); // execute until the first yield
           return function(x) {
                o.next(x);
            }
        }
        var clock = coroutine(function*(_) {
            while (true) {
                yield _;
                foot = 0;
                yield _;
                foot = 1;
            }
        });

        //walk step speed in ms
        setInterval(clock, 100);
        //notify user (console)
        console.log("%c   walking: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
    }//preload

    function create() {

        //  A simple background for our game
        game.add.sprite(0, 0, 'background');
        console.log("%c   spawned: background   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        //Game Objects
        player = game.add.sprite(775, game.world.height - 150, 'bob');
        console.log("%c   spawned: player   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");

        //var healthbar = game.add.sprite(0,0,'healthbar');
        //healthbar.cropEnabled = true;
        //healthbar.crop.width = (character.health / character.maxHealth) * healthbar.width

        //text = "Score: " . score;
        //style = { font: "32px Arial", fill: "#3D4185", align: "center" };
        //game.add.text(game.world.centerX-300, 0, text, style);
        //sound
        //jumpsound = game.add.audio('jumpsound');
        //jumpsound.allowMultiple = false;

        ocean = game.add.sprite(0, game.world.height - 484, 'ocean');
        console.log("%c   spawned: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");

        //add horse
        horse = game.add.sprite(450, game.world.height - 300, 'horse');

        //ocean
        game.physics.enable(ocean, Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        ocean.body.immovable = true;
        console.log("%c   locked: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #A40E38;");

        //start physics
        game.physics.startSystem(Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(player);
        game.physics.arcade.enableBody(player);
        console.log("%c   physics: bounds(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(horse);
        game.physics.arcade.enableBody(horse);
        player.body.collideWorldBounds = true;
        horse.body.collideWorldBounds = true;
        console.log("%c   collideWorldBounds: enabled   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
    }//create()

    function update() {

        //ocean collision
        game.physics.arcade.collide(player, ocean);
        game.physics.arcade.collide(player, horse);

        //horse.body.accelerateToObject(horse, player, 600, 250, 250);

        //  Reset the players velocity (movement)
        player.body.velocity.x = 0;
        player.body.velocity.y = 0;

        horse.velocity = game.physics.arcade.accelerateToObject(horse, player, 50, 50, 50);

        if ( apple.alive() == true){
            console.log("Apple is alive");
        }
        else{
            console.log("Apple is not alive");
        }

        if (cursors.left.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the left+up
                player.body.velocity.x = -100;
                player.body.velocity.y = -100;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the left+down
                player.body.velocity.x = -100;
                player.body.velocity.y = 100;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else
            {
                //  Move to the left
                player.body.velocity.x = -180;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }

        }

        else if (cursors.right.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the right+up
                player.body.velocity.x = 100;
                player.body.velocity.y = -100;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the right+down
                player.body.velocity.x = 100;
                player.body.velocity.y = 100;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else
            {
                //  Move to the right
                player.body.velocity.x = 180;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }

        }
        else if (cursors.up.isDown)
        {
            //  Move to the up
            player.body.velocity.y = -180;
            if ( foot == 0 ){
               player.frame = 2;
            }
            if ( foot == 1 ){
               player.frame = 3;
            }
        }
        else if (cursors.down.isDown)
        {
            //  Move to the down
            player.body.velocity.y = 180;
            if ( foot == 0 ){
               player.frame = 0;
            }
            if ( foot == 1 ){
               player.frame = 1;
            }

        }

        } //update

};
});<commit_msg>Red Apple<commit_after>$(function() {
    window.onload = function() {
    console.log("%c  ~~~  Bob v0.2 - Developed by d4rkd0s  ~~~  ", "color: #FFFFFF; font-size: 12px; background: #3F1338;");
    var game = new Phaser.Game(1156, 650, Phaser.AUTO, '', { preload: preload, create: create, update: update });
    function preload() {
        //setting up starting vars
        score = 0;
        console.log("%c   score: 0   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");
        lives = 3;
        console.log("%c   lives: 3   ", "color: #FFFFFF; font-size: 12px; background: #FD8223;");

        //game.load.image('bob', 'assets/images/bob.png');
        game.load.spritesheet('bob', 'assets/images/bob.png', 54, 80);
        console.log("%c   loaded: spritesheet   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('apple', 'assets/images/apple_red.png');
        game.load.image('background', 'assets/images/background.png');
        console.log("%c   loaded: background   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        //game.load.image('healthbar', 'assets/images/healthbar.png');
        //console.log("%c   loaded: healthbar   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('ocean', 'assets/images/ocean.png');
        console.log("%c   loaded: horse   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        game.load.image('horse', 'assets/images/horse.png');
        console.log("%c   set border: ocean   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        cursors = game.input.keyboard.createCursorKeys();
        console.log("%c   user input: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
        //game.load.audio('jumpsound', 'assets/sounds/jump.wav');

        //walking case switch
        function coroutine(f) {
           var o = f(); // instantiate the coroutine
           o.next(); // execute until the first yield
           return function(x) {
                o.next(x);
            }
        }
        var clock = coroutine(function*(_) {
            while (true) {
                yield _;
                foot = 0;
                yield _;
                foot = 1;
            }
        });

        //walk step speed in ms
        setInterval(clock, 100);
        //notify user (console)
        console.log("%c   walking: enabled   ", "color: #FFFFFF; font-size: 10px; background: #5CA6FF;");
    }//preload

    function create() {

        //  A simple background for our game
        game.add.sprite(0, 0, 'background');
        console.log("%c   spawned: background   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        //Game Objects
        player = game.add.sprite(775, game.world.height - 150, 'bob');
        console.log("%c   spawned: player   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");
        applee = game.add.sprite(500, 200, 'apple');

        //var healthbar = game.add.sprite(0,0,'healthbar');
        //healthbar.cropEnabled = true;
        //healthbar.crop.width = (character.health / character.maxHealth) * healthbar.width

        //text = "Score: " . score;
        //style = { font: "32px Arial", fill: "#3D4185", align: "center" };
        //game.add.text(game.world.centerX-300, 0, text, style);
        //sound
        //jumpsound = game.add.audio('jumpsound');
        //jumpsound.allowMultiple = false;

        ocean = game.add.sprite(0, game.world.height - 484, 'ocean');
        console.log("%c   spawned: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #FCD22F;");

        //add horse
        horse = game.add.sprite(450, game.world.height - 300, 'horse');

        //ocean
        game.physics.enable(ocean, Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        ocean.body.immovable = true;
        console.log("%c   locked: border(ocean)   ", "color: #FFFFFF; font-size: 10px; background: #A40E38;");

        //start physics
        game.physics.startSystem(Phaser.Physics.ARCADE);
        console.log("%c   physics: enabled(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(player);
        game.physics.arcade.enableBody(player);
        console.log("%c   physics: bounds(player)   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
        game.physics.arcade.enable(horse);
        game.physics.arcade.enableBody(horse);
        player.body.collideWorldBounds = true;
        horse.body.collideWorldBounds = true;
        console.log("%c   collideWorldBounds: enabled   ", "color: #FFFFFF; font-size: 10px; background: #83CB53;");
    }//create()

    function update() {

        //ocean collision
        game.physics.arcade.collide(player, ocean);
        game.physics.arcade.collide(player, horse);

        //horse.body.accelerateToObject(horse, player, 600, 250, 250);

        //  Reset the players velocity (movement)
        player.body.velocity.x = 0;
        player.body.velocity.y = 0;

        horse.velocity = game.physics.arcade.accelerateToObject(horse, player, 50, 50, 50);

        if ( apple.alive() == true){
            console.log("Apple is alive");
        }
        else{
            console.log("Apple is not alive");
        }

        if (cursors.left.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the left+up
                player.body.velocity.x = -100;
                player.body.velocity.y = -100;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the left+down
                player.body.velocity.x = -100;
                player.body.velocity.y = 100;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }
            else
            {
                //  Move to the left
                player.body.velocity.x = -180;
                if ( foot == 0 ){
                    player.frame = 4;
                }
                if ( foot == 1 ){
                   player.frame = 5;
                }
            }

        }

        else if (cursors.right.isDown)
        {
            if (cursors.up.isDown)
            {
                //  Move to the right+up
                player.body.velocity.x = 100;
                player.body.velocity.y = -100;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else if (cursors.down.isDown)
            {
                //  Move to the right+down
                player.body.velocity.x = 100;
                player.body.velocity.y = 100;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }
            else
            {
                //  Move to the right
                player.body.velocity.x = 180;
                if ( foot == 0 ){
                    player.frame = 6;
                }
                if ( foot == 1 ){
                   player.frame = 7;
                }
            }

        }
        else if (cursors.up.isDown)
        {
            //  Move to the up
            player.body.velocity.y = -180;
            if ( foot == 0 ){
               player.frame = 2;
            }
            if ( foot == 1 ){
               player.frame = 3;
            }
        }
        else if (cursors.down.isDown)
        {
            //  Move to the down
            player.body.velocity.y = 180;
            if ( foot == 0 ){
               player.frame = 0;
            }
            if ( foot == 1 ){
               player.frame = 1;
            }

        }

        } //update

};
});<|endoftext|>


<commit_before>var assert = require('assert');
var TileMap = require('../src/tilemap');
describe('TileMap', function() {
  var tileMap;
  beforeEach(function() {
    tileMap = new TileMap(3, 4);
  });
  describe('#clear()', function() {
    it('should set map size correctly', function() {
      tileMap.clear();
      assert.equal(4, tileMap.map.length);
      assert.equal(3, tileMap.map[0].length);
    });
    it('should clear the array', function() {
      tileMap.clear();
      var empty = [null, null, null];
      assert.deepEqual([empty, empty, empty, empty], tileMap.map);
    });
  });
  describe('#expand()', function() {
    it('should set map size correctly', function() {
      tileMap.expand(4, 5);
      assert.equal(5, tileMap.map.length);
      assert.equal(4, tileMap.map[0].length);
    });
    it('should not become smaller than its original size', function() {
      tileMap.expand(2, 5);
      assert.equal(5, tileMap.map.length);
      assert.equal(3, tileMap.map[0].length);
    });
    it('should retain its contents', function() {
      tileMap.map = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]];
      tileMap.expand(4, 5);
      for(var y = 0; y < 4; ++y) {
        for(var x = 0; x < 3; ++x) {
          assert.equal(1, tileMap.map[y][x]);
        }
      }
    });
  });
  describe('#get()', function() {
    it('should return its content correctly', function() {
      tileMap.map = [[1,2,3],[4,5,6],[7,8,9],[0,1,2]];
      assert.equal(2, tileMap.get(1, 0));
      assert.equal(9, tileMap.get(2, 2));
    });
    it('should return null if out of bounds', function() {
      assert.equal(null, tileMap.get(-1, 0));
      assert.equal(null, tileMap.get(0, -1));
      assert.equal(null, tileMap.get(3, 0));
      assert.equal(null, tileMap.get(0, 4));
    });
  });
  describe('#set()', function() {
    it('should set its content correctly', function() {
      tileMap.set(1, 0, 2);
      tileMap.set(2, 2, 9);
      assert.equal(2, tileMap.get(1, 0));
      assert.equal(9, tileMap.get(2, 2));
    });
  });
});
<commit_msg>Fix tests<commit_after>var assert = require('assert');
var TileMap = require('../src/tilemap');
describe('TileMap', function() {
  var tileMap;
  beforeEach(function() {
    tileMap = new TileMap(3, 4);
  });
  describe('#clear()', function() {
    it('should set map size correctly', function() {
      tileMap.clear();
      assert.equal(4, tileMap.height);
      assert.equal(3, tileMap.width);
    });
    it('should clear the array', function() {
      tileMap.clear();
      var empty = [];
      assert.deepEqual([empty, empty, empty, empty], tileMap.map);
    });
  });
  describe('#expand()', function() {
    it('should set map size correctly', function() {
      tileMap.expand(4, 5);
      assert.equal(5, tileMap.height);
      assert.equal(4, tileMap.width);
    });
    it('should not become smaller than its original size', function() {
      tileMap.expand(2, 5);
      assert.equal(5, tileMap.height);
      assert.equal(3, tileMap.width);
    });
    it('should retain its contents', function() {
      tileMap.map = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]];
      tileMap.expand(4, 5);
      for(var y = 0; y < 4; ++y) {
        for(var x = 0; x < 3; ++x) {
          assert.equal(1, tileMap.map[y][x]);
        }
      }
    });
  });
  describe('#get()', function() {
    it('should return its content correctly', function() {
      tileMap.map = [[1,2,3],[4,5,6],[7,8,9],[0,1,2]];
      assert.equal(2, tileMap.get(1, 0));
      assert.equal(9, tileMap.get(2, 2));
    });
    it('should return null if out of bounds', function() {
      assert.equal(null, tileMap.get(-1, 0));
      assert.equal(null, tileMap.get(0, -1));
      assert.equal(null, tileMap.get(3, 0));
      assert.equal(null, tileMap.get(0, 4));
    });
  });
  describe('#set()', function() {
    it('should set its content correctly', function() {
      tileMap.set(1, 0, 2);
      tileMap.set(2, 2, 9);
      assert.equal(2, tileMap.get(1, 0));
      assert.equal(9, tileMap.get(2, 2));
    });
  });
});
<|endoftext|>