<commit_before>'use strict';
var util = require('util'),
	path = require('path'),
	yeoman = require('yeoman-generator'),
	chalk = require('chalk');

var SeanGenerator = yeoman.generators.Base.extend({
	init: function() {
		// read the local package file
		this.pkg = yeoman.file.readJSON(path.join(__dirname, '../package.json'));

		// invoke npm install on finish
		this.on('end', function() {
			if (!this.options['skip-install']) {
				this.npmInstall();
			}
		});

		// have Yeoman greet the user
		console.log(this.yeoman);

		// replace it with a short and sweet description of your generator
		console.log(chalk.magenta('You\'re using the official SEAN generator.'));
	},

	askForApplicationDetails: function() {
		var done = this.async();

		var prompts = [{
			name: 'appName',
			message: 'What would you like to call your application?',
			default: 'SEAN'
		}, {
			name: 'appDescription',
			message: 'How would you describe your application?',
			default: 'Full-Stack JavaScript with MongoDB, Express, AngularJS, and Node.js'
		}, {
			name: 'appKeywords',
			message: 'How would you describe your application in comma seperated key words?',
			default: 'MongoDB, Express, AngularJS, Node.js'
		}, {
			name: 'appAuthor',
			message: 'What is your company/author name?'
		}, {
			type: 'confirm',
			name: 'addArticleExample',
			message: 'Would you like to generate the article example CRUD module?',
			default: true
		}];

		this.prompt(prompts, function(props) {
			this.appName = props.appName;
			this.appDescription = props.appDescription;
			this.appKeywords = props.appKeywords;
			this.appAuthor = props.appAuthor;
			this.addArticleExample = props.addArticleExample;

			this.slugifiedAppName = this._.slugify(this.appName);
			this.humanizedAppName = this._.humanize(this.appName);
			this.capitalizedAppAuthor = this._.capitalize(this.appAuthor);

			done();
		}.bind(this));
	},

	askForAngularApplicationModules: function() {
		var done = this.async();

		var prompts = [{
			type: 'checkbox',
			name: 'modules',
			message: 'Which AngularJS modules would you like to include?',
			choices: [{
				value: 'angularCookies',
				name: 'ngCookies',
				checked: true
			}, {
				value: 'angularAnimate',
				name: 'ngAnimate',
				checked: true
			}, {
				value: 'angularTouch',
				name: 'ngTouch',
				checked: true
			}, {
				value: 'angularSanitize',
				name: 'ngSanitize',
				checked: true
			}]
		}];

		this.prompt(prompts, function(props) {
			this.angularCookies = this._.contains(props.modules, 'angularCookies');
			this.angularAnimate = this._.contains(props.modules, 'angularAnimate');
			this.angularTouch = this._.contains(props.modules, 'angularTouch');
			this.angularSanitize = this._.contains(props.modules, 'angularSanitize');

			done();
		}.bind(this));
	},

	copyApplicationFolder: function() {
		// Copy application folder
		this.mkdir('app');
		this.mkdir('app/controllers');
		this.mkdir('app/models');
		this.mkdir('app/routes');
		this.mkdir('app/tests');
		this.directory('app/views');

		// Copy base files
		this.copy('app/controllers/core.server.controller.js');
		this.copy('app/controllers/users.server.controller.js');
		this.copy('app/controllers/errors.server.controller.js');
		this.directory('app/controllers/users');
		this.copy('app/models/user.server.model.js');
		this.copy('app/routes/core.server.routes.js');
		this.copy('app/routes/users.server.routes.js');
    this.copy('app/services/token.server.service.js');
    this.copy('app/tests/user.server.model.test.js');

		// Create public folders
		this.mkdir('public');
		this.mkdir('public/modules');

		// Copy public folder content
		this.copy('public/application.js');
		this.copy('public/humans.txt');
		this.copy('public/robots.txt');
    this.copy('public/roleManager.js');

		// Copy public folder modules
		this.directory('public/modules/users');

		// Copy core module files
		this.directory('public/modules/core/config');
		this.directory('public/modules/core/controllers');
		this.directory('public/modules/core/css');
		this.directory('public/modules/core/img');
		this.directory('public/modules/core/services');
		this.directory('public/modules/core/tests');
		this.copy('public/modules/core/views/home.client.view.html');
		this.copy('public/modules/core/core.client.module.js');

		// Copy config folder
		this.mkdir('config');
		this.mkdir('config/env');

		// Copy config folder content
		this.directory('config/strategies')
		this.copy('config/config.js');
		this.copy('config/init.js');
		this.copy('config/express.js');
		this.copy('config/passport.js');
    this.copy('config/logger.js');
    this.copy('config/roleManager.js');
    this.copy('config/sequelize.js');

		// Copy project files
		this.copy('karma.conf.js');
		this.copy('gruntfile.js');
		this.copy('server.js');
		this.copy('Procfile');
		this.copy('fig.yml');
		this.copy('Dockerfile');
		this.copy('README.md');
		this.copy('LICENSE.md');

		// Copy project hidden files
		this.copy('bowerrc', '.bowerrc');
		this.copy('csslintrc', '.csslintrc');
		this.copy('editorconfig', '.editorconfig');
		this.copy('jshintrc', '.jshintrc');
		this.copy('gitignore', '.gitignore');
		this.copy('slugignore', '.slugignore');
		this.copy('travis.yml', '.travis.yml');
	},

	renderArticleExample: function() {
		// Copy example files if desired
		if (this.addArticleExample) {
			// Copy Express files
			this.copy('app/controllers/articles.server.controller.js');
			this.copy('app/models/article.server.model.js');
			this.copy('app/routes/articles.server.routes.js');
			this.copy('app/tests/article.server.model.test.js');

			// Copy AngularJS files
			this.directory('public/modules/articles');
		}
	},

	renderApplicationEnvironmentConfigFiles: function() {
		this.template('config/env/_all.js', 'config/env/all.js');
		this.template('config/env/_development.js', 'config/env/development.js');
		this.template('config/env/_production.js', 'config/env/production.js');
		this.template('config/env/_test.js', 'config/env/test.js');
	},

	renderAngularApplicationConfigFile: function() {
		this.template('public/_config.js', 'public/config.js');
	},

	renderCoreModuleFiles: function() {
		this.template('public/modules/core/views/_header.client.view.html', 'public/modules/core/views/header.client.view.html');
	},

	renderApplicationDependenciesFiles: function() {
		this.template('_package.json', 'package.json');
		this.template('_bower.json', 'bower.json');
	}
});

module.exports = SeanGenerator;
<commit_msg>generator update<commit_after>'use strict';
var util = require('util'),
	path = require('path'),
	yeoman = require('yeoman-generator'),
	chalk = require('chalk');

var SeanGenerator = yeoman.generators.Base.extend({
	init: function() {
		// read the local package file
		this.pkg = yeoman.file.readJSON(path.join(__dirname, '../package.json'));

		// invoke npm install on finish
		this.on('end', function() {
			if (!this.options['skip-install']) {
				this.npmInstall();
			}
		});

		// have Yeoman greet the user
		console.log(this.yeoman);

		// replace it with a short and sweet description of your generator
		console.log(chalk.magenta('You\'re using the official SEAN generator.'));
	},

	askForApplicationDetails: function() {
		var done = this.async();

		var prompts = [{
			name: 'appName',
			message: 'What would you like to call your application?',
			default: 'SEAN'
		}, {
			name: 'appDescription',
			message: 'How would you describe your application?',
			default: 'Full-Stack JavaScript with SQL, Express, AngularJS, and Node.js'
		}, {
			name: 'appKeywords',
			message: 'How would you describe your application in comma seperated key words?',
			default: 'SQL, Express, AngularJS, Node.js'
		}, {
			name: 'appAuthor',
			message: 'What is your company/author name?'
		}, {
			type: 'confirm',
			name: 'addArticleExample',
			message: 'Would you like to generate the article example CRUD module?',
			default: true
		}];

		this.prompt(prompts, function(props) {
			this.appName = props.appName;
			this.appDescription = props.appDescription;
			this.appKeywords = props.appKeywords;
			this.appAuthor = props.appAuthor;
			this.addArticleExample = props.addArticleExample;

			this.slugifiedAppName = this._.slugify(this.appName);
			this.humanizedAppName = this._.humanize(this.appName);
			this.capitalizedAppAuthor = this._.capitalize(this.appAuthor);

			done();
		}.bind(this));
	},

	askForAngularApplicationModules: function() {
		var done = this.async();

		var prompts = [{
			type: 'checkbox',
			name: 'modules',
			message: 'Which AngularJS modules would you like to include?',
			choices: [{
				value: 'angularCookies',
				name: 'ngCookies',
				checked: true
			}, {
				value: 'angularAnimate',
				name: 'ngAnimate',
				checked: true
			}, {
				value: 'angularTouch',
				name: 'ngTouch',
				checked: true
			}, {
				value: 'angularSanitize',
				name: 'ngSanitize',
				checked: true
			}]
		}];

		this.prompt(prompts, function(props) {
			this.angularCookies = this._.contains(props.modules, 'angularCookies');
			this.angularAnimate = this._.contains(props.modules, 'angularAnimate');
			this.angularTouch = this._.contains(props.modules, 'angularTouch');
			this.angularSanitize = this._.contains(props.modules, 'angularSanitize');

			done();
		}.bind(this));
	},

	copyApplicationFolder: function() {
		// Copy application folder
		this.mkdir('app');
		this.mkdir('app/controllers');
		this.mkdir('app/models');
		this.mkdir('app/routes');
		this.mkdir('app/tests');
		this.directory('app/views');

		// Copy base files
		this.copy('app/controllers/core.server.controller.js');
		this.copy('app/controllers/users.server.controller.js');
		this.copy('app/controllers/errors.server.controller.js');
		this.directory('app/controllers/users');
		this.copy('app/models/user.server.model.js');
		this.copy('app/routes/core.server.routes.js');
		this.copy('app/routes/users.server.routes.js');
    this.copy('app/services/token.server.service.js');
    this.copy('app/tests/user.server.model.test.js');

		// Create public folders
		this.mkdir('public');
		this.mkdir('public/modules');

		// Copy public folder content
		this.copy('public/application.js');
		this.copy('public/humans.txt');
		this.copy('public/robots.txt');
    this.copy('public/roleManager.js');

		// Copy public folder modules
		this.directory('public/modules/users');

		// Copy core module files
		this.directory('public/modules/core/config');
		this.directory('public/modules/core/controllers');
		this.directory('public/modules/core/css');
		this.directory('public/modules/core/img');
		this.directory('public/modules/core/services');
		this.directory('public/modules/core/tests');
		this.copy('public/modules/core/views/home.client.view.html');
		this.copy('public/modules/core/core.client.module.js');

		// Copy config folder
		this.mkdir('config');
		this.mkdir('config/env');

		// Copy config folder content
		this.directory('config/strategies')
		this.copy('config/config.js');
		this.copy('config/init.js');
		this.copy('config/express.js');
		this.copy('config/passport.js');
    this.copy('config/logger.js');
    this.copy('config/roleManager.js');
    this.copy('config/sequelize.js');

		// Copy project files
		this.copy('karma.conf.js');
		this.copy('gruntfile.js');
		this.copy('server.js');
		this.copy('Procfile');
		this.copy('fig.yml');
		this.copy('Dockerfile');
		this.copy('README.md');
		this.copy('LICENSE.md');

		// Copy project hidden files
		this.copy('bowerrc', '.bowerrc');
		this.copy('csslintrc', '.csslintrc');
		this.copy('editorconfig', '.editorconfig');
		this.copy('jshintrc', '.jshintrc');
		this.copy('gitignore', '.gitignore');
		this.copy('slugignore', '.slugignore');
		this.copy('travis.yml', '.travis.yml');
	},

	renderArticleExample: function() {
		// Copy example files if desired
		if (this.addArticleExample) {
			// Copy Express files
			this.copy('app/controllers/articles.server.controller.js');
			this.copy('app/models/article.server.model.js');
			this.copy('app/routes/articles.server.routes.js');
			this.copy('app/tests/article.server.model.test.js');

			// Copy AngularJS files
			this.directory('public/modules/articles');
		}
	},

	renderApplicationEnvironmentConfigFiles: function() {
		this.template('config/env/_all.js', 'config/env/all.js');
		this.template('config/env/_development.js', 'config/env/development.js');
		this.template('config/env/_production.js', 'config/env/production.js');
		this.template('config/env/_test.js', 'config/env/test.js');
	},

	renderAngularApplicationConfigFile: function() {
		this.template('public/_config.js', 'public/config.js');
	},

	renderCoreModuleFiles: function() {
		this.template('public/modules/core/views/_header.client.view.html', 'public/modules/core/views/header.client.view.html');
	},

	renderApplicationDependenciesFiles: function() {
		this.template('_package.json', 'package.json');
		this.template('_bower.json', 'bower.json');
	}
});

module.exports = SeanGenerator;
<|endoftext|>


<commit_before>(function($) {
$.fn.lifestream.feeds.reddit = function( config, callback ) {

  var template = $.extend({},
    {
      commented: 'commented '
        + '(${score}) in ${item.data.subreddit}',
      created: ''
        + 'created new thread (${score}) in '
        + ''
        + '${item.data.subreddit}'
    },
    config.template);

  /**
   * Parsed one item from the Reddit API.
   * item.kind == t1 is a reply, t2 is a new thread
   */
  var parseRedditItem = function( item ) {

    var score = item.data.ups - item.data.downs,
        pass = {
          item: item,
          score: (score > 0) ? "+" + score : score
        };

    // t1 = reply, t3 = new thread
    if (item.kind === "t1") {
      return $.tmpl( template.commented, pass );
    }
    else if (item.kind === "t3") {
      return $.tmpl( template.created, pass );
    }

  },
  /**
   * Reddit date's are simple epochs.
   * seconds*1000 = milliseconds
   */
  convertDate = function( date ) {
    return new Date(date * 1000);
  };

  $.ajax({
    url: "http://www.reddit.com/user/" + config.user + ".json",
    dataType: "jsonp",
    jsonp:"jsonp",
    success: function( data ) {
      var output = [], i = 0, j;

      if(data && data.data && data.data.children
          && data.data.children.length > 0) {
        j = data.data.children.length;
        for( ; i<j; i++) {
          var item = data.data.children[i];
          output.push({
            date: convertDate(item.data.created),
            config: config,
            html: parseRedditItem(item)
          });
        }
      }

      callback(output);
    }
  });

  // Expose the template.
  // We use this to check which templates are available
  return {
    "template" : template
  };

};
})(jQuery);<commit_msg>Date constructor should take a UTC timestamp.<commit_after>(function($) {
$.fn.lifestream.feeds.reddit = function( config, callback ) {

  var template = $.extend({},
    {
      commented: 'commented '
        + '(${score}) in ${item.data.subreddit}',
      created: ''
        + 'created new thread (${score}) in '
        + ''
        + '${item.data.subreddit}'
    },
    config.template);

  /**
   * Parsed one item from the Reddit API.
   * item.kind == t1 is a reply, t2 is a new thread
   */
  var parseRedditItem = function( item ) {

    var score = item.data.ups - item.data.downs,
        pass = {
          item: item,
          score: (score > 0) ? "+" + score : score
        };

    // t1 = reply, t3 = new thread
    if (item.kind === "t1") {
      return $.tmpl( template.commented, pass );
    }
    else if (item.kind === "t3") {
      return $.tmpl( template.created, pass );
    }

  },
  /**
   * Reddit date's are simple epochs.
   * seconds*1000 = milliseconds
   */
  convertDate = function( date ) {
    return new Date(date * 1000);
  };

  $.ajax({
    url: "http://www.reddit.com/user/" + config.user + ".json",
    dataType: "jsonp",
    jsonp:"jsonp",
    success: function( data ) {
      var output = [], i = 0, j;

      if(data && data.data && data.data.children
          && data.data.children.length > 0) {
        j = data.data.children.length;
        for( ; i<j; i++) {
          var item = data.data.children[i];
          output.push({
            date: convertDate(item.data.created_utc),
            config: config,
            html: parseRedditItem(item)
          });
        }
      }

      callback(output);
    }
  });

  // Expose the template.
  // We use this to check which templates are available
  return {
    "template" : template
  };

};
})(jQuery);
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 */

CLASS({
  package: 'com.google.sweeper',
  name: 'Cell',
  extends: 'foam.u2.Element',

  imports: [ 'board', 'dynamic' ],

  constants: {
    COUNT_COLOURS: [ '', 'green', 'blue', 'orange', 'red', 'red', 'red', 'red' ],
  },

  properties: [
    'x', 'y',
    {
      type: 'Int',
      name: 'mineCount',
      lazyFactory: function() { return this.board.getMineCount(this); }
    },
    {
      type: 'Boolean',
      name: 'covered',
      defaultValue: true
    },
    {
      type: 'Boolean',
      name: 'marked'
    },
    {
      type: 'Boolean',
      name: 'mined',
      factory: function() { return Math.random() < 0.18; }
    }
  ],

  methods: [
    function markedClass() {
      return this.dynamic(
        function(marked) { return marked ? 'marked' : ''; },
        this.marked$);
    },
    function coveredClass() {
      return this.dynamic(
        function(covered, marked) { return covered && ! marked ? 'covered' : ''; },
        this.covered$,
        this.marked$);
    }
  ],

  templates: [
    function CSS() {/*
      $ {
        border: 1px solid gray;
        display: table-cell;
        font-size: 18px;
        font-weight: bold;
        height: 26px;
        text-align: center;
        vertical-align: middle;
        width: 26px;
      }
      $.covered {
        background: #ccc;
        box-shadow: -2px -2px 10px rgba(0,0,0,.25) inset, 2px 2px 10px white inset;
      }
      $.covered font { display: none; }
      $.marked font { display: none; }
      $-flag { display: none; }
      $.marked $-flag {
        display: block;
        color: #BD1616;
      }
      $.marked { background-color: #ccc; }
    */},
    function initE() {/*#U2

        &#x2691
        &#x2699
        {{this.mineCount}}

    */}
  ],

  listeners: [
    function mark(e) {
      this.marked = ! this.marked;
      e.preventDefault();
    },
    function sweep(e) {
      this.covered = false;
    }
  ]
});
<commit_msg>Sweeper: Cell improvments.<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 */

CLASS({
  package: 'com.google.sweeper',
  name: 'Cell',
  extends: 'foam.u2.Element',

  imports: [ 'board', 'dynamic' ],

  constants: {
    COUNT_COLOURS: [ '', 'green', 'blue', 'orange', 'red', 'red', 'red', 'red' ],
  },

  properties: [
    'x',
    'y',
    {
      type: 'Int',
      name: 'mineCount',
      lazyFactory: function() { return this.board.getMineCount(this); }
    },
    {
      type: 'Boolean',
      name: 'covered',
      defaultValue: true
    },
    {
      type: 'Boolean',
      name: 'marked'
    },
    {
      type: 'Boolean',
      name: 'mined',
      factory: function() { return Math.random() < 0.18; }
    }
  ],

  methods: [
    function markedClass() {
      return this.dynamic(
        function(marked) { return marked ? 'marked' : ''; },
        this.marked$);
    },
    function coveredClass() {
      return this.dynamic(
        function(covered, marked) { return covered && ! marked ? 'covered' : ''; },
        this.covered$,
        this.marked$);
    }
  ],

  templates: [
    function CSS() {/*
      $ {
        border: 1px solid gray;
        display: table-cell;
        font-size: 18px;
        font-weight: bold;
        height: 26px;
        text-align: center;
        vertical-align: middle;
        width: 26px;
      }
      $.covered {
        background: #ccc;
        box-shadow: -2px -2px 10px rgba(0,0,0,.25) inset, 2px 2px 10px white inset;
      }
      $.covered font { display: none; }
      $.marked font { display: none; }
      $-flag { display: none; }
      $.marked $-flag {
        display: block;
        color: #BD1616;
      }
      $.marked { background-color: #ccc; }
    */},
    function initE() {/*#U2

        &#x2691
        &#x2699
        {{this.mineCount}}

    */}
  ],

  listeners: [
    function mark(e) { this.marked = ! this.marked; e.preventDefault(); },
    function sweep(e) { this.covered = false; }
  ]
});
<|endoftext|>


<commit_before>'use strict';

/**
 * Returns an array of the passed-in function's arguments.
 */

var LPAREN = '(';
var RPAREN = ')';
var REGEXP = /([^\s,]+)/g;

function getParameterNames(fn) {
  var fnString = fn.toString();
  var matches = fnString.slice(fnString.indexOf(LPAREN) + 1, fnString.indexOf(RPAREN)).match(REGEXP);
  return matches || [];
}

module.exports = {
  getParameterNames: getParameterNames
};
<commit_msg>chore: Fix function-parser indentation -> 4 spaces<commit_after>'use strict';

/**
 * Returns an array of the passed-in function's arguments.
 */

var LPAREN = '(';
var RPAREN = ')';
var REGEXP = /([^\s,]+)/g;

function getParameterNames(fn) {
    var fnString = fn.toString();
    var matches = fnString.slice(fnString.indexOf(LPAREN) + 1, fnString.indexOf(RPAREN)).match(REGEXP);
    return matches || [];
}

module.exports = {
    getParameterNames: getParameterNames
};
<|endoftext|>


<commit_before>/* global btoa */
var _ = require('lodash').noConflict(),
    util,

    ASCII_SOURCE = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
    ASCII_SOURCE_LENGTH = ASCII_SOURCE.length,
    EMPTY = '';

/**
 * @module util
 * @private
 */
_.mixin( /** @lends util */ {

    /**
     * Creates an inheritance relation between the child and the parent, adding a 'super_' attribute to the
     * child, and setting up the child prototype.
     *
     *
     * @param child
     * @param base
     * @returns {*}
     */
    inherit: function (child, base) {
        Object.defineProperty(child, 'super_', {
            value: _.isFunction(base) ? base : _.noop,
            configurable: false,
            enumerable: false,
            writable: false
        });

        child.prototype = Object.create((_.isFunction(base) ? base.prototype : base), {
            constructor: {
                value: child,
                enumerable: false,
                writable: true,
                configurable: true
            }
        });
        return child;
    },

    /**
     * Creates an array from a Javascript "arguments" object.
     * https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/arguments
     *
     * @param args
     * @returns {Array.<T>}
     */
    args: function (args) {
        return Array.prototype.slice.call(args);
    },

    /**
     * Makes sure the given string is encoded only once.
     *
     * @param string
     * @returns {string}
     */
    ensureEncoded: function (string) {
        // Takes care of the case where the string is already encoded.
        return encodeURIComponent(decodeURIComponent(string));
    },

    /**
     * Creates a locked property on an object, which is not writable or enumerable.
     *
     * @param obj
     * @param name
     * @param prop
     * @returns {*}
     */
    assignLocked: function (obj, name, prop) {
        Object.defineProperty(obj, name, {
            value: prop,
            configurable: false,
            enumerable: false,
            writable: false
        });
        return obj;
    },

    /**
     * Creates a hidden property on an object, which can be changed, but is not enumerable.
     *
     * @param obj
     * @param name
     * @param prop
     * @returns {*}
     */
    assignHidden: function (obj, name, prop) {
        Object.defineProperty(obj, name, {
            value: prop,
            configurable: true,
            enumerable: false,
            writable: true
        });
        return obj;
    },

    /**
     * Creates a property on an object, with the given type.
     *
     * @param obj
     * @param name
     * @param Prop
     * @returns {Prop|undefined}
     */
    createDefined: function (obj, name, Prop) {
        return _.has(obj, name) ? (new Prop(obj[name])) : undefined;
    },

    /**
     * Returns the value of a property if defined in object, else the default
     *
     * @param {Object} obj
     * @param {String} prop
     * @param {*} def
     *
     * @returns {*}
     */
    getOwn: function (obj, prop, def) {
        return _.has(obj, prop) ? obj[prop] : def;
    },

    /**
     * Creates a clone of an object, but uses the toJSON method if available.
     *
     * @param obj
     * @returns {*}
     */
    cloneElement: function (obj) {
        return _.cloneDeep(obj, function (value) {
            // falls back to default deepclone if object does not have explicit toJSON().
            if (value && _.isFunction(value.toJSON)) {
                return value.toJSON();
            }
        });
    },

    /**
     * Returns the match of a value of a property by traversing the prototype
     *
     * @param {Object} obj
     * @param {String} key
     * @param {*} value
     *
     * @returns {Boolean}
     */
    inSuperChain: function (obj, key, value) {
        return obj ? ((obj[key] === value) || _.inSuperChain(obj.super_, key, value)) : false;
    },

    /**
     * Generates a random string of given length (useful for nonce generation, etc).
     *
     * @param {Number} length
     */
    randomString: function (length) {
        length = length || 6;

        var result = [],
            i;

        for (i = 0; i < length; i++) {
            result[i] = ASCII_SOURCE[(Math.random() * ASCII_SOURCE_LENGTH) | 0];
        }
        return result.join(EMPTY);
    }
});

util = {
    lodash: _,
    /**
     *
     * @param {String} data
     *
     * @returns {String} [description]
     */
    btoa: ((typeof btoa !== 'function' && typeof Buffer === 'function') ? function (data) {
        return new Buffer(data).toString('base64');
    } : btoa), // @todo use browserify to normalise this

    /**
     * ArrayBuffer to String
     *
     * @param {ArrayBuffer} buffer
     * @returns {String}
     */
    arrayBufferToString: function (buffer) {
        var str = '',
            uArrayVal = new Uint8Array(buffer),

            i,
            ii;

        for (i = 0, ii = uArrayVal.length; i < ii; i++) {
            str += String.fromCharCode(uArrayVal[i]);
        }

        return str;
    },

    bufferOrArrayBufferToString: function (buffer) {
        if (!buffer || _.isString(buffer)) {
            return buffer || '';
        }

        var str = buffer.toString('utf8') || E;
        (str === '[object ArrayBuffer]') && (str = util.arrayBufferToString(buffer));
        return str;
    },

    bufferOrArrayBufferToBase64: function (buffer) {
        if (!buffer) {
            return '';
        }

        var base64;

        // handle when buffer is pure string
        if (_.isString(buffer)) {
            return util.btoa(buffer);
        }

        // check if tostring works
        base64 = buffer.toString('base64') || '';

        if (base64 === '[object ArrayBuffer]') {
            return util.btoa(util.arrayBufferToString(buffer));
        }

        return base64;
    }
};

module.exports = util;

<commit_msg>Lint fix in util.js<commit_after>/* global btoa */
var _ = require('lodash').noConflict(),
    util,

    ASCII_SOURCE = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
    ASCII_SOURCE_LENGTH = ASCII_SOURCE.length,
    EMPTY = '';

/**
 * @module util
 * @private
 */
_.mixin( /** @lends util */ {

    /**
     * Creates an inheritance relation between the child and the parent, adding a 'super_' attribute to the
     * child, and setting up the child prototype.
     *
     *
     * @param child
     * @param base
     * @returns {*}
     */
    inherit: function (child, base) {
        Object.defineProperty(child, 'super_', {
            value: _.isFunction(base) ? base : _.noop,
            configurable: false,
            enumerable: false,
            writable: false
        });

        child.prototype = Object.create((_.isFunction(base) ? base.prototype : base), {
            constructor: {
                value: child,
                enumerable: false,
                writable: true,
                configurable: true
            }
        });
        return child;
    },

    /**
     * Creates an array from a Javascript "arguments" object.
     * https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/arguments
     *
     * @param args
     * @returns {Array.<T>}
     */
    args: function (args) {
        return Array.prototype.slice.call(args);
    },

    /**
     * Makes sure the given string is encoded only once.
     *
     * @param string
     * @returns {string}
     */
    ensureEncoded: function (string) {
        // Takes care of the case where the string is already encoded.
        return encodeURIComponent(decodeURIComponent(string));
    },

    /**
     * Creates a locked property on an object, which is not writable or enumerable.
     *
     * @param obj
     * @param name
     * @param prop
     * @returns {*}
     */
    assignLocked: function (obj, name, prop) {
        Object.defineProperty(obj, name, {
            value: prop,
            configurable: false,
            enumerable: false,
            writable: false
        });
        return obj;
    },

    /**
     * Creates a hidden property on an object, which can be changed, but is not enumerable.
     *
     * @param obj
     * @param name
     * @param prop
     * @returns {*}
     */
    assignHidden: function (obj, name, prop) {
        Object.defineProperty(obj, name, {
            value: prop,
            configurable: true,
            enumerable: false,
            writable: true
        });
        return obj;
    },

    /**
     * Creates a property on an object, with the given type.
     *
     * @param obj
     * @param name
     * @param Prop
     * @returns {Prop|undefined}
     */
    createDefined: function (obj, name, Prop) {
        return _.has(obj, name) ? (new Prop(obj[name])) : undefined;
    },

    /**
     * Returns the value of a property if defined in object, else the default
     *
     * @param {Object} obj
     * @param {String} prop
     * @param {*} def
     *
     * @returns {*}
     */
    getOwn: function (obj, prop, def) {
        return _.has(obj, prop) ? obj[prop] : def;
    },

    /**
     * Creates a clone of an object, but uses the toJSON method if available.
     *
     * @param obj
     * @returns {*}
     */
    cloneElement: function (obj) {
        return _.cloneDeep(obj, function (value) {
            // falls back to default deepclone if object does not have explicit toJSON().
            if (value && _.isFunction(value.toJSON)) {
                return value.toJSON();
            }
        });
    },

    /**
     * Returns the match of a value of a property by traversing the prototype
     *
     * @param {Object} obj
     * @param {String} key
     * @param {*} value
     *
     * @returns {Boolean}
     */
    inSuperChain: function (obj, key, value) {
        return obj ? ((obj[key] === value) || _.inSuperChain(obj.super_, key, value)) : false;
    },

    /**
     * Generates a random string of given length (useful for nonce generation, etc).
     *
     * @param {Number} length
     */
    randomString: function (length) {
        length = length || 6;

        var result = [],
            i;

        for (i = 0; i < length; i++) {
            result[i] = ASCII_SOURCE[(Math.random() * ASCII_SOURCE_LENGTH) | 0];
        }
        return result.join(EMPTY);
    }
});

util = {
    lodash: _,
    /**
     *
     * @param {String} data
     *
     * @returns {String} [description]
     */
    btoa: ((typeof btoa !== 'function' && typeof Buffer === 'function') ? function (data) {
        return new Buffer(data).toString('base64');
    } : btoa), // @todo use browserify to normalise this

    /**
     * ArrayBuffer to String
     *
     * @param {ArrayBuffer} buffer
     * @returns {String}
     */
    arrayBufferToString: function (buffer) {
        var str = '',
            uArrayVal = new Uint8Array(buffer),

            i,
            ii;

        for (i = 0, ii = uArrayVal.length; i < ii; i++) {
            str += String.fromCharCode(uArrayVal[i]);
        }

        return str;
    },

    bufferOrArrayBufferToString: function (buffer) {
        if (!buffer || _.isString(buffer)) {
            return buffer || '';
        }

        var str = buffer.toString('utf8') || '';
        (str === '[object ArrayBuffer]') && (str = util.arrayBufferToString(buffer));
        return str;
    },

    bufferOrArrayBufferToBase64: function (buffer) {
        if (!buffer) {
            return '';
        }

        var base64;

        // handle when buffer is pure string
        if (_.isString(buffer)) {
            return util.btoa(buffer);
        }

        // check if tostring works
        base64 = buffer.toString('base64') || '';

        if (base64 === '[object ArrayBuffer]') {
            return util.btoa(util.arrayBufferToString(buffer));
        }

        return base64;
    }
};

module.exports = util;

<|endoftext|>


<commit_before>import {join} from 'path';

export default {
  entry: {
    bundle: './dev/app.js',
    instantsearch: './index.js'
  },
  devtool: 'source-map',
  output: {
    path: './dev/',
    filename: '[name].js',
    library: '[name]',
    libraryTarget: 'umd'
  },
  module: {
    loaders: [{
      test: /\.js$/, exclude: /node_modules/, loader: 'babel'
    }, {
      test: /\.html$/, exclude: /node_modules/, loader: 'raw'
    }, {
      test: require.resolve('react'), loader: 'expose?React'
    }, {
      test: require.resolve('react-dom'), loader: 'expose?ReactDOM'
    }]
  },
  // when module not found, find locally first
  // helps fixing the npm link not working with webpack
  // http://stackoverflow.com/a/33722844/147079
  resolve: {
    fallback: [join(__dirname, '..', 'node_modules')]
  },
  // same issue, for loaders like babel
  resolveLoader: {
    fallback: [join(__dirname, '..', 'node_modules')]
  },
  devServer: {
    contentBase: 'dev/',
    host: '0.0.0.0',
    compress: true
  }
};
<commit_msg>chore(dev): accept NODE_ENV param in dev env<commit_after>import {join} from 'path';
import webpack from 'webpack';

export default {
  entry: {
    bundle: './dev/app.js',
    instantsearch: './index.js'
  },
  devtool: 'source-map',
  output: {
    path: './dev/',
    filename: '[name].js',
    library: '[name]',
    libraryTarget: 'umd'
  },
  module: {
    loaders: [{
      test: /\.js$/, exclude: /node_modules/, loader: 'babel'
    }, {
      test: /\.html$/, exclude: /node_modules/, loader: 'raw'
    }, {
      test: require.resolve('react'), loader: 'expose?React'
    }, {
      test: require.resolve('react-dom'), loader: 'expose?ReactDOM'
    }]
  },
  // when module not found, find locally first
  // helps fixing the npm link not working with webpack
  // http://stackoverflow.com/a/33722844/147079
  resolve: {
    fallback: [join(__dirname, '..', 'node_modules')]
  },
  // same issue, for loaders like babel
  resolveLoader: {
    fallback: [join(__dirname, '..', 'node_modules')]
  },
  devServer: {
    contentBase: 'dev/',
    host: '0.0.0.0',
    compress: true
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV)
      }
    })
  ]
};
<|endoftext|>


<commit_before>/*
 * grunt-require-rev
 * https://github.com/heavymery/grunt-require-rev
 *
 * Copyright (c) 2014 Shindeok Kang
 * Licensed under the MIT license.
 */

'use strict';

// Console color code
var black   = '\u001b[30m';
var red     = '\u001b[31m';
var green   = '\u001b[32m';
var yellow  = '\u001b[33m';
var blue    = '\u001b[34m';
var magenta = '\u001b[35m';
var cyan    = '\u001b[36m';
var white   = '\u001b[37m';
var reset   = '\u001b[0m';

// file hashing modules
var fs = require('fs');
var path = require('path');
var crypto = require('crypto');

module.exports = function(grunt) {

  var createHashFromFile = function(filepath, fileEncoding, hashAlgorithm) {
    var hash = crypto.createHash(hashAlgorithm);
    hash.update(grunt.file.read(filepath), fileEncoding);
    grunt.verbose.ok('Hashing ' + filepath + '...');
    return hash.digest('hex');
  }

  grunt.registerMultiTask('requireRev', 'File revisioning for requrejs.', function() {

    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      hash: {
        algorithm: 'md5',
        inputEncoding: 'utf8',
        length: 8
      },
      paths: { // key: file path, value: requirejs dependency path
        'scripts': '', // like as requirejs baseUrl == '/scripts'
        'styles': 'css!/styles/' // for requireCSS
      }
    });

    var dirPathPattern = new RegExp('[\\w\\d-_/.]*');

    var hashPrefixPatternSource = '([a-zA-Z0-9]{' + options.hash.length + '}\\.)?';

    var filePathPattern = new RegExp(hashPrefixPatternSource + '(([\\w\\d-_/.!]+)\\.(js|css|html))');

    var dependencyPathPattern
      = new RegExp('(\'|")[\\w\\d-_/.!]+(\'|")','g');
      // e.g. 'app', "controllers/main", "css!/styles/main"

    var definePattern
      = new RegExp('define\\s*\\(\\s*(' + dependencyPathPattern.source + '\\s*,?\\s*)*\\s*\\[\\s*(' + dependencyPathPattern.source + '\\s*,?\\s*)*\\s*\\]', 'ig');
      // e.g. define("moduleName",["app","controllers/main"]... define(["app","controllers/main"]...

    var requirePattern
      = new RegExp('(require\\s*\\(\\s*\\[\\s*(' + dependencyPathPattern.source + '\\s*,?\\s*)*\\]\\s*)|(require\\s*\\(\\s*(' + dependencyPathPattern.source + '\\s*,?\\s*)*)', 'ig');
      // e.g. require(['app']... require('app'...

    var dependenciesPattern
      = new RegExp('(dependencies\\s*(:|=)\\s*\\[\\s*(' + dependencyPathPattern.source + '\\s*,?\\s*)*\\]\\s*)|(dependencies\\s*\\.\\s*push\\(\\s*(' + dependencyPathPattern.source + '\\s*,?\\s*)*)', 'ig');
      // e.g. dependencies: ['css!../~','~']... dependencies = ['css!../~','~']... dependencies.push('~');

    var matchPatternFromArray = function(array, pattern) {
      for(var i=0; i<array.length; i++) {
        var match = array[i].match(pattern);
        if(match) {
          return match;
        }
      }

      return null;
    };

    var fileToDependencyPath = function(filePath) {
      var fileBasePathPattern = '(' + Object.keys(options.paths).join('|') + ')';
      var regexp = new RegExp(fileBasePathPattern + '/?(' + dirPathPattern.source + ')/' + filePathPattern.source);

      var pathMatch = filePath.match(regexp);
      if(!pathMatch) return '';

      var fileBasePath = pathMatch[1];
      var dependencyBasePath = options.paths[fileBasePath];

      // set base dependency path
      var path = dependencyBasePath;
      var pathOrigin = dependencyBasePath;
      var patternSource = dependencyBasePath.replace(/\//g,'\\/');

      // add sub dependency path
      if(pathMatch[2] && pathMatch[2].length>0) {
        path += pathMatch[2] + '/';
        pathOrigin += pathMatch[2] + '/';
        patternSource += pathMatch[2].replace(/\//g,'\\/') + '\\/';
      }

      // add hash prefix pattern
      patternSource += hashPrefixPatternSource;

      // add hash prefix
      if(pathMatch[3] && pathMatch[3].length>0) {
        path += pathMatch[3];
      }

      // add file name (exclude extension)
      if(pathMatch[5] && pathMatch[5].length>0) {
        path += pathMatch[5];
        pathOrigin += pathMatch[5];
        patternSource += pathMatch[5];
      }

      // create regular expression
      var pattern = new RegExp(patternSource, 'ig');

      return {
        path: path,
        pathOrigin: pathOrigin,
        pattern: pattern
      }
    };

    //--------------------------------------
    // 1. get target files
    //--------------------------------------

    var targetFiles = [];

    this.files.forEach(function(filePair) {
      filePair.src.forEach(function(file) {
        targetFiles.push(file);
      });
    });

    grunt.verbose.writeln();
    grunt.verbose.writeln('Target files:');
    grunt.verbose.writeln(green + targetFiles.join('\n') + reset);
    grunt.verbose.writeln();

    //--------------------------------------
    // 2. create dependencies map
    //  (key: filePath, value: dependencies)
    //--------------------------------------

    var dependenciesMap = {};

    targetFiles.forEach(function(targetPath) {

      var contents = grunt.file.read(targetPath);

      var defineMatchs = contents.match(definePattern);
      var requireMatchs = contents.match(requirePattern);
      var dependenciesMatchs = contents.match(dependenciesPattern);

      grunt.verbose.writeln('Define matchs:\n' + cyan + defineMatchs + reset);
      grunt.verbose.writeln('Require matchs:\n' + cyan + requireMatchs + reset);
      grunt.verbose.writeln('Dependencies matchs:\n' + cyan + dependenciesMatchs + reset);
      grunt.verbose.writeln();

      // dependency path array
      var dependencies = [];

      if(defineMatchs) {
        defineMatchs.forEach(function(defineMatch) {
          var pathMatchs = defineMatch.match(dependencyPathPattern);
          if(pathMatchs) {
            dependencies = dependencies.concat(defineMatch.match(dependencyPathPattern));
          }
        });
      }

      if(requireMatchs) {
        requireMatchs.forEach(function(requireMatch) {
          var pathMatchs = requireMatch.match(dependencyPathPattern);
          if(pathMatchs) {
            dependencies = dependencies.concat(pathMatchs);
          }
        });
      }

      if(dependenciesMatchs) {
        dependenciesMatchs.forEach(function(dependenciesMatch) {
          var pathMatchs = dependenciesMatch.match(dependencyPathPattern);
          if(pathMatchs) {
            dependencies = dependencies.concat(pathMatchs);
          }
        });
      }

      // remove quotation mark
      for(var i=0; i<dependencies.length; i++) {
        dependencies[i] = dependencies[i].replace(/'|"/g,'');
      }

      // remove duplicate dependency path
      for(var i=0; i<dependencies.length; i++) {
        var target = dependencies[i];
        var indexOfNext = dependencies.indexOf(target, i + 1);
        if(indexOfNext > 0) {
          dependencies.splice(indexOfNext, 1);
          i--;
        }
      }

      dependenciesMap[targetPath] = {};
      dependenciesMap[targetPath].dependencyPath = fileToDependencyPath(targetPath);
      dependenciesMap[targetPath].dependencies = dependencies;
    });

    //--------------------------------------
    // 3. order by dependencies
    //--------------------------------------

    var targetFilesSorted = [];

    while(targetFiles.length > 0) {
      if(targetFilesSorted.length > 0) {
        var nextTarget = targetFiles.pop();

        for(var i=0; i<targetFilesSorted.length; i++) {
          var targetFile = targetFilesSorted[i];
          var dependencies = dependenciesMap[targetFile].dependencies;

          var dependencyMatch = matchPatternFromArray(dependencies, dependenciesMap[nextTarget].dependencyPath.pattern);

          if(dependencyMatch) {
            break;
          }
        }

        // move dependent file to front
        targetFilesSorted.splice(i, 0, nextTarget);

      } else {
        targetFilesSorted.push(targetFiles.pop());
      }
    }

    grunt.verbose.writeln();

    //--------------------------------------
    // 4. hashing & replace dependency path
    //--------------------------------------

    targetFilesSorted.forEach(function(targetPath) {
      var dependencies = dependenciesMap[targetPath].dependencies;

      grunt.verbose.ok('Target ' + targetPath + ' ('
        + dependenciesMap[targetPath].dependencyPath.path + ' | '
        + dependenciesMap[targetPath].dependencyPath.pathOrigin + ' | '
        + dependenciesMap[targetPath].dependencyPath.pattern + ')');

      grunt.verbose.writeln(red + dependencies.length + reset + ' dependencies found.');
      if(dependencies && dependencies.length > 0) {
        grunt.verbose.writeln(magenta + dependencies.join('\n') + reset);
      }
      grunt.verbose.writeln();
    });

    for(var i=0; i<targetFilesSorted.length; i++) {
      var targetPath = targetFilesSorted[i];
      var originName = path.basename(targetPath);

      var hash = createHashFromFile(targetPath, options.hash.inputEncoding, options.hash.algorithm);
      var prefix = hash.slice(0, options.hash.length);

      // clear hash prefix from file name
      var filePathMatch = originName.match(filePathPattern);
      if(filePathMatch && filePathMatch[1] && filePathMatch[1].match(/\d/)) {
        originName = filePathMatch[2];
      }

      var targetPathNew = path.dirname(targetPath) + '/' + prefix + '.' +  originName;
      grunt.verbose.write('Rename ' + targetPath + ' to ' + targetPathNew + '...');

      // rename file (adding hash prefix)
      fs.renameSync(targetPath, targetPathNew);
      grunt.verbose.ok();

      // replace dependency path
      dependenciesMap[targetPath].dependencyPath = fileToDependencyPath(targetPathNew);

      for(var j=i+1; j<targetFilesSorted.length; j++) {
        var otherPath = targetFilesSorted[j];

        var dependencyMatch = matchPatternFromArray(dependenciesMap[otherPath].dependencies, dependenciesMap[targetPath].dependencyPath.pattern);
        if(dependencyMatch) {
          grunt.verbose.ok('Replace require path for ' + otherPath + '...');

          var contents = grunt.file.read(otherPath);

          grunt.file.write(otherPath, contents.replace(
            new RegExp('("|\')' + dependenciesMap[targetPath].dependencyPath.pattern.source + '("|\')', 'ig'),
            '$1' + dependenciesMap[targetPath].dependencyPath.path + '$3'
          ));
        }
      }

      grunt.verbose.writeln();
    }

  }); // grunt.registerMultiTask

}; // module.exports
<commit_msg>Update task<commit_after>/*
 * grunt-require-rev
 * https://github.com/heavymery/grunt-require-rev
 *
 * Copyright (c) 2014 Shindeok Kang
 * Licensed under the MIT license.
 */

'use strict';

// Console color code
var black   = '\u001b[30m';
var red     = '\u001b[31m';
var green   = '\u001b[32m';
var yellow  = '\u001b[33m';
var blue    = '\u001b[34m';
var magenta = '\u001b[35m';
var cyan    = '\u001b[36m';
var white   = '\u001b[37m';
var reset   = '\u001b[0m';

// file hashing modules
var fs = require('fs');
var path = require('path');
var crypto = require('crypto');

module.exports = function(grunt) {

  var createHashFromFile = function(filepath, fileEncoding, hashAlgorithm) {
    var hash = crypto.createHash(hashAlgorithm);
    hash.update(grunt.file.read(filepath), fileEncoding);
    grunt.verbose.ok('Hashing ' + filepath + '...');
    return hash.digest('hex');
  }

  grunt.registerMultiTask('requireRev', 'File revisioning for requrejs.', function() {

    // Merge task-specific and/or target-specific options with these defaults.
    var options = this.options({
      hash: {
        algorithm: 'md5',
        inputEncoding: 'utf8',
        length: 8
      },
      paths: { // key: file path, value: requirejs dependency path
        'scripts': '', // like as requirejs baseUrl == '/scripts'
        'styles': 'css!/styles/' // for requireCSS
      }
    });

    var dirPathPattern = new RegExp('[\\w\\d-_/.]*');

    var hashPrefixPatternSource = '([a-zA-Z0-9]{' + options.hash.length + '}\\.)?';

    var filePathPattern = new RegExp(hashPrefixPatternSource + '(([\\w\\d-_/.!]+)\\.(\.[0-9a-z]+)$)');

    var dependencyPathPattern
      = new RegExp('(\'|")[\\w\\d-_/.!]+(\'|")','g');
      // e.g. 'app', "controllers/main", "css!/styles/main"

    var definePattern
      = new RegExp('define\\s*\\(\\s*(' + dependencyPathPattern.source + '\\s*,?\\s*)*\\s*\\[\\s*(' + dependencyPathPattern.source + '\\s*,?\\s*)*\\s*\\]', 'ig');
      // e.g. define("moduleName",["app","controllers/main"]... define(["app","controllers/main"]...

    var requirePattern
      = new RegExp('(require\\s*\\(\\s*\\[\\s*(' + dependencyPathPattern.source + '\\s*,?\\s*)*\\]\\s*)|(require\\s*\\(\\s*(' + dependencyPathPattern.source + '\\s*,?\\s*)*)', 'ig');
      // e.g. require(['app']... require('app'...

    var dependenciesPattern
      = new RegExp('(dependencies\\s*(:|=)\\s*\\[\\s*(' + dependencyPathPattern.source + '\\s*,?\\s*)*\\]\\s*)|(dependencies\\s*\\.\\s*push\\(\\s*(' + dependencyPathPattern.source + '\\s*,?\\s*)*)', 'ig');
      // e.g. dependencies: ['css!../~','~']... dependencies = ['css!../~','~']... dependencies.push('~');

    var matchPatternFromArray = function(array, pattern) {
      for(var i=0; i<array.length; i++) {
        var match = array[i].match(pattern);
        if(match) {
          return match;
        }
      }

      return null;
    };

    var fileToDependencyPath = function(filePath) {
      var fileBasePathPattern = '(' + Object.keys(options.paths).join('|') + ')';
      var regexp = new RegExp(fileBasePathPattern + '/?(' + dirPathPattern.source + ')/' + filePathPattern.source);

      var pathMatch = filePath.match(regexp);
      if(!pathMatch) return '';

      var fileBasePath = pathMatch[1];
      var dependencyBasePath = options.paths[fileBasePath];

      // set base dependency path
      var path = dependencyBasePath;
      var pathOrigin = dependencyBasePath;
      var patternSource = dependencyBasePath.replace(/\//g,'\\/');

      // add sub dependency path
      if(pathMatch[2] && pathMatch[2].length>0) {
        path += pathMatch[2] + '/';
        pathOrigin += pathMatch[2] + '/';
        patternSource += pathMatch[2].replace(/\//g,'\\/') + '\\/';
      }

      // add hash prefix pattern
      patternSource += hashPrefixPatternSource;

      // add hash prefix
      if(pathMatch[3] && pathMatch[3].length>0) {
        path += pathMatch[3];
      }

      // add file name (exclude extension)
      if(pathMatch[5] && pathMatch[5].length>0) {
        path += pathMatch[5];
        pathOrigin += pathMatch[5];
        patternSource += pathMatch[5];
      }

      // create regular expression
      var pattern = new RegExp(patternSource, 'ig');

      return {
        path: path,
        pathOrigin: pathOrigin,
        pattern: pattern
      }
    };

    //--------------------------------------
    // 1. get target files
    //--------------------------------------

    var targetFiles = [];

    this.files.forEach(function(filePair) {
      filePair.src.forEach(function(file) {
        targetFiles.push(file);
      });
    });

    grunt.verbose.writeln();
    grunt.verbose.writeln('Target files:');
    grunt.verbose.writeln(green + targetFiles.join('\n') + reset);
    grunt.verbose.writeln();

    //--------------------------------------
    // 2. create dependencies map
    //  (key: filePath, value: dependencies)
    //--------------------------------------

    var dependenciesMap = {};

    targetFiles.forEach(function(targetPath) {

      var contents = grunt.file.read(targetPath);

      var defineMatchs = contents.match(definePattern);
      var requireMatchs = contents.match(requirePattern);
      var dependenciesMatchs = contents.match(dependenciesPattern);

      grunt.verbose.writeln('Define matchs:\n' + cyan + defineMatchs + reset);
      grunt.verbose.writeln('Require matchs:\n' + cyan + requireMatchs + reset);
      grunt.verbose.writeln('Dependencies matchs:\n' + cyan + dependenciesMatchs + reset);
      grunt.verbose.writeln();

      // dependency path array
      var dependencies = [];

      if(defineMatchs) {
        defineMatchs.forEach(function(defineMatch) {
          var pathMatchs = defineMatch.match(dependencyPathPattern);
          if(pathMatchs) {
            dependencies = dependencies.concat(defineMatch.match(dependencyPathPattern));
          }
        });
      }

      if(requireMatchs) {
        requireMatchs.forEach(function(requireMatch) {
          var pathMatchs = requireMatch.match(dependencyPathPattern);
          if(pathMatchs) {
            dependencies = dependencies.concat(pathMatchs);
          }
        });
      }

      if(dependenciesMatchs) {
        dependenciesMatchs.forEach(function(dependenciesMatch) {
          var pathMatchs = dependenciesMatch.match(dependencyPathPattern);
          if(pathMatchs) {
            dependencies = dependencies.concat(pathMatchs);
          }
        });
      }

      // remove quotation mark
      for(var i=0; i<dependencies.length; i++) {
        dependencies[i] = dependencies[i].replace(/'|"/g,'');
      }

      // remove duplicate dependency path
      for(var i=0; i<dependencies.length; i++) {
        var target = dependencies[i];
        var indexOfNext = dependencies.indexOf(target, i + 1);
        if(indexOfNext > 0) {
          dependencies.splice(indexOfNext, 1);
          i--;
        }
      }

      dependenciesMap[targetPath] = {};
      dependenciesMap[targetPath].dependencyPath = fileToDependencyPath(targetPath);
      dependenciesMap[targetPath].dependencies = dependencies;
    });

    //--------------------------------------
    // 3. order by dependencies
    //--------------------------------------

    var targetFilesSorted = [];

    while(targetFiles.length > 0) {
      if(targetFilesSorted.length > 0) {
        var nextTarget = targetFiles.pop();

        for(var i=0; i<targetFilesSorted.length; i++) {
          var targetFile = targetFilesSorted[i];
          var dependencies = dependenciesMap[targetFile].dependencies;

          var dependencyMatch = matchPatternFromArray(dependencies, dependenciesMap[nextTarget].dependencyPath.pattern);

          if(dependencyMatch) {
            break;
          }
        }

        // move dependent file to front
        targetFilesSorted.splice(i, 0, nextTarget);

      } else {
        targetFilesSorted.push(targetFiles.pop());
      }
    }

    grunt.verbose.writeln();

    //--------------------------------------
    // 4. hashing & replace dependency path
    //--------------------------------------

    targetFilesSorted.forEach(function(targetPath) {
      var dependencies = dependenciesMap[targetPath].dependencies;

      grunt.verbose.ok('Target ' + targetPath + ' ('
        + dependenciesMap[targetPath].dependencyPath.path + ' | '
        + dependenciesMap[targetPath].dependencyPath.pathOrigin + ' | '
        + dependenciesMap[targetPath].dependencyPath.pattern + ')');

      grunt.verbose.writeln(red + dependencies.length + reset + ' dependencies found.');
      if(dependencies && dependencies.length > 0) {
        grunt.verbose.writeln(magenta + dependencies.join('\n') + reset);
      }
      grunt.verbose.writeln();
    });

    for(var i=0; i<targetFilesSorted.length; i++) {
      var targetPath = targetFilesSorted[i];
      var originName = path.basename(targetPath);

      var hash = createHashFromFile(targetPath, options.hash.inputEncoding, options.hash.algorithm);
      var prefix = hash.slice(0, options.hash.length);

      // clear hash prefix from file name
      var filePathMatch = originName.match(filePathPattern);
      if(filePathMatch && filePathMatch[1] && filePathMatch[1].match(/\d/)) {
        originName = filePathMatch[2];
      }

      var targetPathNew = path.dirname(targetPath) + '/' + prefix + '.' +  originName;
      grunt.verbose.write('Rename ' + targetPath + ' to ' + targetPathNew + '...');

      // rename file (adding hash prefix)
      fs.renameSync(targetPath, targetPathNew);
      grunt.verbose.ok();

      // replace dependency path
      dependenciesMap[targetPath].dependencyPath = fileToDependencyPath(targetPathNew);

      for(var j=i+1; j<targetFilesSorted.length; j++) {
        var otherPath = targetFilesSorted[j];

        var dependencyMatch = matchPatternFromArray(dependenciesMap[otherPath].dependencies, dependenciesMap[targetPath].dependencyPath.pattern);
        if(dependencyMatch) {
          grunt.verbose.ok('Replace require path for ' + otherPath + '...');

          var contents = grunt.file.read(otherPath);

          grunt.file.write(otherPath, contents.replace(
            new RegExp('("|\')' + dependenciesMap[targetPath].dependencyPath.pattern.source + '("|\')', 'ig'),
            '$1' + dependenciesMap[targetPath].dependencyPath.path + '$3'
          ));
        }
      }

      grunt.verbose.writeln();
    }

  }); // grunt.registerMultiTask

}; // module.exports
<|endoftext|>


<commit_before>// Copyright 2014-2018, University of Colorado Boulder

/**
 * Displays the graph and everything that appears on it (aka, it's content).
 *
 * @author Andrea Lin
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( function( require ) {
  'use strict';

  // modules
  const GQColors = require( 'GRAPHING_QUADRATICS/common/GQColors' );
  const GQConstants = require( 'GRAPHING_QUADRATICS/common/GQConstants' );
  const graphingQuadratics = require( 'GRAPHING_QUADRATICS/graphingQuadratics' );
  const GraphNode = require( 'GRAPHING_LINES/common/view/GraphNode' );
  const Node = require( 'SCENERY/nodes/Node' );
  const PhetFont = require( 'SCENERY_PHET/PhetFont' );
  const Property = require( 'AXON/Property' );
  const QuadraticNode = require( 'GRAPHING_QUADRATICS/common/view/QuadraticNode' );
  const Rectangle = require( 'SCENERY/nodes/Rectangle' );
  const Shape = require( 'KITE/Shape' );
  const Text = require( 'SCENERY/nodes/Text' );
  const Vector2 = require( 'DOT/Vector2' );
  const VertexManipulator = require( 'GRAPHING_QUADRATICS/common/view/VertexManipulator' );

  // strings
  const noRealRootsString = require( 'string!GRAPHING_QUADRATICS/noRealRoots' );

  class GQGraphNode extends Node {

    /**
     * @param {GQScene} model
     * @param {Bounds2} layoutBounds
     * @param {GQViewProperties} viewProperties
     * @param {Object} [options]
     */
    constructor( model, layoutBounds, viewProperties, options ) {

      options = _.extend( {
        hasVertexManipulator: false // only vertex scene has vertex manipulator
      }, options );

      super( options );

      // Location of the origin in view coordinate frame, for layout
      const origin = model.modelViewTransform.modelToViewPosition( new Vector2( 0, 0 ) );

      // Cartesian coordinates graph
      const graphNode = new GraphNode( model.graph, model.modelViewTransform );

      // Interactive quadratic curve
      const quadraticNode = new QuadraticNode(
        model.quadraticProperty,
        model.graph,
        model.modelViewTransform,
        viewProperties
      );

      // Vertex manipulator
      let vertexManipulator;
      if ( options.hasVertexManipulator ) {
        vertexManipulator = new VertexManipulator(
          GQConstants.MANIPULATOR_RADIUS,
          model.quadraticProperty,
          model.graph.xRange,
          model.graph.yRange,
          model.modelViewTransform
        );
      }

      // 'no real roots' label
      const noRealRootsLabel = new Text( noRealRootsString, {
        font: new PhetFont( { size: 18, weight: 'bold' } ),
        fill: 'white'
      } );
      const noRealRootsBackground = new Rectangle( noRealRootsLabel.bounds.dilatedXY( 5, 2 ), {
        fill: GQColors.ROOTS,
        opacity: 0.75,
        cornerRadius: 2,
        center: noRealRootsLabel.center
      } );
      const noRealRootsNode = new Node( {
        children: [ noRealRootsBackground, noRealRootsLabel ],
        center: origin
      } );

      // Parent for saved curves
      const savedCurvesLayer = new Node();

      // Clip content to the graph
      const clipArea = Shape.rectangle(
        model.graph.xRange.min,
        model.graph.yRange.min,
        model.graph.xRange.getLength(),
        model.graph.yRange.getLength()
      ).transformed( model.modelViewTransform.getMatrix() );

      // Everything that's on the graph, clipped to the graph
      const contentNode = new Node( { clipArea: clipArea } );
      contentNode.addChild( savedCurvesLayer );
      contentNode.addChild( quadraticNode );
      contentNode.addChild( noRealRootsNode );
      if ( options.hasVertexManipulator ) { contentNode.addChild( vertexManipulator ); }

      // rendering order
      this.addChild( graphNode );
      this.addChild( contentNode );

      // When a quadratic is saved...
      model.savedQuadratics.addItemAddedListener( savedQuadratic => {

        // create Node for the new quadratic
        const newQuadraticNode = quadraticNode.createPathWithColor( savedQuadratic, GQColors.SAVED_CURVE );
        savedCurvesLayer.addChild( newQuadraticNode );

        //TODO memory leak?
        // add listener for when the quadratic is eventually removed
        model.savedQuadratics.addItemRemovedListener( removedQuadratic => {
          if ( removedQuadratic === savedQuadratic ) {
            savedCurvesLayer.removeChild( newQuadraticNode );
          }
        } );
      } );

      // Show/hide the graph content
      viewProperties.hideCurvesProperty.link( hideCurves => {contentNode.visible = !hideCurves; } );

      // If the quadratic has no roots, indicate so on the x axis
      Property.multilink( [ model.quadraticProperty, viewProperties.rootsVisibleProperty ],
        ( quadratic, rootsVisible ) => {
          noRealRootsNode.visible = ( !quadratic.hasRoots() && rootsVisible );
        } );
    }
  }

  return graphingQuadratics.register( 'GQGraphNode', GQGraphNode );
} );<commit_msg>don't show 'no real roots' for non-quadratic<commit_after>// Copyright 2014-2018, University of Colorado Boulder

/**
 * Displays the graph and everything that appears on it (aka, it's content).
 *
 * @author Andrea Lin
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( function( require ) {
  'use strict';

  // modules
  const GQColors = require( 'GRAPHING_QUADRATICS/common/GQColors' );
  const GQConstants = require( 'GRAPHING_QUADRATICS/common/GQConstants' );
  const graphingQuadratics = require( 'GRAPHING_QUADRATICS/graphingQuadratics' );
  const GraphNode = require( 'GRAPHING_LINES/common/view/GraphNode' );
  const Node = require( 'SCENERY/nodes/Node' );
  const PhetFont = require( 'SCENERY_PHET/PhetFont' );
  const Property = require( 'AXON/Property' );
  const QuadraticNode = require( 'GRAPHING_QUADRATICS/common/view/QuadraticNode' );
  const Rectangle = require( 'SCENERY/nodes/Rectangle' );
  const Shape = require( 'KITE/Shape' );
  const Text = require( 'SCENERY/nodes/Text' );
  const Vector2 = require( 'DOT/Vector2' );
  const VertexManipulator = require( 'GRAPHING_QUADRATICS/common/view/VertexManipulator' );

  // strings
  const noRealRootsString = require( 'string!GRAPHING_QUADRATICS/noRealRoots' );

  class GQGraphNode extends Node {

    /**
     * @param {GQScene} model
     * @param {Bounds2} layoutBounds
     * @param {GQViewProperties} viewProperties
     * @param {Object} [options]
     */
    constructor( model, layoutBounds, viewProperties, options ) {

      options = _.extend( {
        hasVertexManipulator: false // only vertex scene has vertex manipulator
      }, options );

      super( options );

      // Location of the origin in view coordinate frame, for layout
      const origin = model.modelViewTransform.modelToViewPosition( new Vector2( 0, 0 ) );

      // Cartesian coordinates graph
      const graphNode = new GraphNode( model.graph, model.modelViewTransform );

      // Interactive quadratic curve
      const quadraticNode = new QuadraticNode(
        model.quadraticProperty,
        model.graph,
        model.modelViewTransform,
        viewProperties
      );

      // Vertex manipulator
      let vertexManipulator;
      if ( options.hasVertexManipulator ) {
        vertexManipulator = new VertexManipulator(
          GQConstants.MANIPULATOR_RADIUS,
          model.quadraticProperty,
          model.graph.xRange,
          model.graph.yRange,
          model.modelViewTransform
        );
      }

      // 'no real roots' label
      const noRealRootsLabel = new Text( noRealRootsString, {
        font: new PhetFont( { size: 18, weight: 'bold' } ),
        fill: 'white'
      } );
      const noRealRootsBackground = new Rectangle( noRealRootsLabel.bounds.dilatedXY( 5, 1 ), {
        fill: GQColors.ROOTS,
        opacity: 0.8,
        cornerRadius: 2,
        center: noRealRootsLabel.center
      } );
      const noRealRootsNode = new Node( {
        children: [ noRealRootsBackground, noRealRootsLabel ],
        center: origin
      } );

      // Parent for saved curves
      const savedCurvesLayer = new Node();

      // Clip content to the graph
      const clipArea = Shape.rectangle(
        model.graph.xRange.min,
        model.graph.yRange.min,
        model.graph.xRange.getLength(),
        model.graph.yRange.getLength()
      ).transformed( model.modelViewTransform.getMatrix() );

      // Everything that's on the graph, clipped to the graph
      const contentNode = new Node( { clipArea: clipArea } );
      contentNode.addChild( savedCurvesLayer );
      contentNode.addChild( quadraticNode );
      contentNode.addChild( noRealRootsNode );
      if ( options.hasVertexManipulator ) { contentNode.addChild( vertexManipulator ); }

      // rendering order
      this.addChild( graphNode );
      this.addChild( contentNode );

      // When a quadratic is saved...
      model.savedQuadratics.addItemAddedListener( savedQuadratic => {

        // create Node for the new quadratic
        const newQuadraticNode = quadraticNode.createPathWithColor( savedQuadratic, GQColors.SAVED_CURVE );
        savedCurvesLayer.addChild( newQuadraticNode );

        //TODO memory leak?
        // add listener for when the quadratic is eventually removed
        model.savedQuadratics.addItemRemovedListener( removedQuadratic => {
          if ( removedQuadratic === savedQuadratic ) {
            savedCurvesLayer.removeChild( newQuadraticNode );
          }
        } );
      } );

      // Show/hide the graph content
      viewProperties.hideCurvesProperty.link( hideCurves => {contentNode.visible = !hideCurves; } );

      // If the quadratic has no roots, indicate so on the x axis
      Property.multilink( [ model.quadraticProperty, viewProperties.rootsVisibleProperty ],
        ( quadratic, rootsVisible ) => {
          noRealRootsNode.visible = ( quadratic.a !== 0 && !quadratic.hasRoots() && rootsVisible );
        } );
    }
  }

  return graphingQuadratics.register( 'GQGraphNode', GQGraphNode );
} );<|endoftext|>


<commit_before>var create = {
    space_key   : null,
    enemy_group : null,
    timer : null,
    arrows : null,
    tilesprite : null,
    tilespritedois : null,

    init : function(){
        //game defs
        game.world.setBounds(0, 0, 960, 600);
        game.physics.startSystem(Phaser.Physics.ARCADE);

      //  game.add.sprite(0,0,'background');

        // background
        // TODO: parallax background
        //Tentativa de parallax background

    	tilesprite = game.add.tileSprite(0, 0, 960,600,  'background');
    	tilesprite.autoScroll(-200, 0);

    	tilespritedois = game.add.tileSprite(0, game.world.height - 100, 960, 100, 'river');
    	tilespritedois.autoScroll(-100, 0);

        //player defs
        this.createPlayer();

        //enemy defs
        this.enemy_group = game.add.group();

        //input defs
        this.space_key = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
        this.space_key.onDown.add(this.jump, this);

        // timer defs
        this.enemyTimer = game.time.events.loop(3000, this.createEnemy, this);
    },
    createPlayer : function(){
        this.player = game.add.sprite(200, 423, 'pirarucu');
        game.physics.enable(this.player, Phaser.Physics.ARCADE);
        game.camera.follow(this.player);
        this.player.body.gravity.y = 1000;
        this.player.jumpForce = -500;
        this.player.anchor.setTo(0.5, 0.5);
        this.player.alive = true;
        // anima����o de rota����o para cima, quando o jogador pula
        this.player.rotateAnim = game.add.tween(this.player).to({angle: -15}, 300);
        // adicionando player a classe update
        update.player = this.player;
    },

    createEnemy : function() {
        if(!this.player.alive) return;
        var enemyIndex = this.random(1, 3);
        var enemySpeedMultiplier = this.random(1, 9);
        switch(enemyIndex){
            case 1:
                this.createAriranha(enemySpeedMultiplier);
                break;
            case 2:
                this.createArraia(enemySpeedMultiplier);
                break;
            case 3:
                this.createAnzol(enemySpeedMultiplier);
                break;
            default:
                this.createAriranha(enemySpeedMultiplier);
        }
    },

    //criacao dos inimigos
    createAnzol : function(enemySpeedMultiplier){
        var anzol = this.enemy_group.create(970, 0, 'anzol'); // criando do lado de fora
        game.physics.arcade.enable(anzol);
        anzol.body.velocity.x = -300 * (1 + enemySpeedMultiplier / 10);
        anzol.outOfBoundsKill = true;
    },
    createAriranha : function(enemySpeedMultiplier){
        var ariranha = this.enemy_group.create(1160, 170, 'ariranha'); // criando do lado de fora
        game.physics.arcade.enable(ariranha);
        ariranha.body.velocity.x = -300* (1 + enemySpeedMultiplier / 10);
        ariranha.outOfBoundsKill = true;
        ariranha.anchor.setTo(0.5, 0.5);
        game.add.tween(ariranha) //anima����o da ariranha descendo
            .to({y: 370, angle: -20}, 1000, null, false, 500) // em 500ms, descer e apontar angulo para cima, levando 1000ms
            .to({y: 270, angle: 20}, 1000) // subir e apontar angulo para baixo, em 1000ms
            .to({y: 170, angle: 0}, 500) // voltar a altura normal, zerar angulo
            .start();
    },
    createArraia : function(enemySpeedMultiplier){
        var arraia = this.enemy_group.create(1160, 570, 'arraia'); // criando do lado de fora
        game.physics.arcade.enable(arraia);
        arraia.body.velocity.x = -300* (1 + enemySpeedMultiplier / 10);
        arraia.outOfBoundsKill = true;
        arraia.anchor.setTo(0.5, 0.5);
        game.add.tween(arraia) // anima����o da arraia subindo
            .to({y: 370, angle: 20}, 1000, null, false, 500) // em 500ms, subir e apontar angulo para baixo, levando 1000ms
            .to({y: 470, angle: -20}, 1000) // descer e apontar angulo para cima, em 1000ms
            .to({y: 570, angle: 0}, 500) // voltar a altura normal, zerar angulo
            .start();
    },

    jump: function() {
        if(this.player.alive) {
            this.player.body.velocity.y = this.player.jumpForce;
            this.player.rotateAnim.start();
        }
    },

    // numero aleatorio entre [max, min]
    random: function(min, max) {
        return Math.floor(Math.random()*(max-min+1)+min);
    }
};<commit_msg>Ajustando velocidade do background<commit_after>var create = {
    space_key   : null,
    enemy_group : null,
    timer : null,
    arrows : null,
    nearBackground : null,
    farBackground : null,

    init : function(){
        //game defs
        game.world.setBounds(0, 0, 960, 600);
        game.physics.startSystem(Phaser.Physics.ARCADE);

        farBackground = game.add.tileSprite(0, 0, 960, 600,  'background');
        farBackground.autoScroll(-200, 0);

        nearBackground = game.add.tileSprite(0, game.world.height - 100, 960, 100, 'river');
        nearBackground.autoScroll(-400, 0);

        //player defs
        this.createPlayer();

        //enemy defs
        this.enemy_group = game.add.group();

        //input defs
        this.space_key = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
        this.space_key.onDown.add(this.jump, this);

        // timer defs
        this.enemyTimer = game.time.events.loop(3000, this.createEnemy, this);
    },
    createPlayer : function(){
        this.player = game.add.sprite(200, 423, 'pirarucu');
        game.physics.enable(this.player, Phaser.Physics.ARCADE);
        game.camera.follow(this.player);
        this.player.body.gravity.y = 1000;
        this.player.jumpForce = -500;
        this.player.anchor.setTo(0.5, 0.5);
        this.player.alive = true;
        // anima����o de rota����o para cima, quando o jogador pula
        this.player.rotateAnim = game.add.tween(this.player).to({angle: -15}, 300);
        // adicionando player a classe update
        update.player = this.player;
    },

    createEnemy : function() {
        if(!this.player.alive) return;
        var enemyIndex = this.random(1, 3);
        var enemySpeedMultiplier = this.random(1, 9);
        switch(enemyIndex){
            case 1:
                this.createAriranha(enemySpeedMultiplier);
                break;
            case 2:
                this.createArraia(enemySpeedMultiplier);
                break;
            case 3:
                this.createAnzol(enemySpeedMultiplier);
                break;
            default:
                this.createAriranha(enemySpeedMultiplier);
        }
    },

    //criacao dos inimigos
    createAnzol : function(enemySpeedMultiplier){
        var anzol = this.enemy_group.create(970, 0, 'anzol'); // criando do lado de fora
        game.physics.arcade.enable(anzol);
        anzol.body.velocity.x = -300 * (1 + enemySpeedMultiplier / 10);
        anzol.outOfBoundsKill = true;
    },
    createAriranha : function(enemySpeedMultiplier){
        var ariranha = this.enemy_group.create(1160, 170, 'ariranha'); // criando do lado de fora
        game.physics.arcade.enable(ariranha);
        ariranha.body.velocity.x = -300* (1 + enemySpeedMultiplier / 10);
        ariranha.outOfBoundsKill = true;
        ariranha.anchor.setTo(0.5, 0.5);
        game.add.tween(ariranha) //anima����o da ariranha descendo
            .to({y: 370, angle: -20}, 1000, null, false, 500) // em 500ms, descer e apontar angulo para cima, levando 1000ms
            .to({y: 270, angle: 20}, 1000) // subir e apontar angulo para baixo, em 1000ms
            .to({y: 170, angle: 0}, 500) // voltar a altura normal, zerar angulo
            .start();
    },
    createArraia : function(enemySpeedMultiplier){
        var arraia = this.enemy_group.create(1160, 570, 'arraia'); // criando do lado de fora
        game.physics.arcade.enable(arraia);
        arraia.body.velocity.x = -300* (1 + enemySpeedMultiplier / 10);
        arraia.outOfBoundsKill = true;
        arraia.anchor.setTo(0.5, 0.5);
        game.add.tween(arraia) // anima����o da arraia subindo
            .to({y: 370, angle: 20}, 1000, null, false, 500) // em 500ms, subir e apontar angulo para baixo, levando 1000ms
            .to({y: 470, angle: -20}, 1000) // descer e apontar angulo para cima, em 1000ms
            .to({y: 570, angle: 0}, 500) // voltar a altura normal, zerar angulo
            .start();
    },

    jump: function() {
        if(this.player.alive) {
            this.player.body.velocity.y = this.player.jumpForce;
            this.player.rotateAnim.start();
        }
    },

    // numero aleatorio entre [max, min]
    random: function(min, max) {
        return Math.floor(Math.random()*(max-min+1)+min);
    }
};<|endoftext|>


<commit_before>/**
 * Panax.js
 *
 * PanaxDB Abstraction Class
 *
 * HowTo instantiate:
 *
 * var Panax = new require('Panax')(config, params);
 *
 */
var sql = require('mssql');
var libxmljs = require('libxslt').libxmljs;
var path = require('path');
var fs = require('fs');
var mkdirp = require('mkdirp');

// ToDo
// @Parameters (Unknown)
// @FullPath (Unknown XPath)
// @ColumnList (Unknown XML parsing for Create, Update & Delete ?)
//
// ToDo from Panax.asp:
// Class_Initialize()
// - ln 26-84: Process Session Variables & Parameters
// - ln 91-100: Handle EncryptedID (eid). In different request? (ex. /to?eid=X)
// - ln 106-166: Filters: Manipulate filters
// - ln 167-169: Filters: Set identityKey filter
// - ln 172-175: Filters: Join filters
// - ln: 177-186: Sorters
//
// ToDo from xmlCatalogOptions.asp:
// @Filters
// @extraOptions
// @sortDirection
// @orderBy
// @enableInsert

/**
 * Constructor
 */
var Class = function(config, params) {

	this.config = config;

	if(!params) {
		this.params = {};
	} else {
		this.params = {
			userId: params.userId,
			tableName: params.tableName,
			output: params.output,
			getData: params.getData || '1',
			getStructure: params.getStructure || '1',
			rebuild: params.rebuild || 'DEFAULT',
			controlType: params.controlType || 'DEFAULT',
			mode: params.mode || 'DEFAULT',
			pageIndex: params.pageIndex || 'DEFAULT',
			pageSize: params.pageSize || 'DEFAULT',
			maxRecords: params.maxRecords || 'DEFAULT',
			parameters: params.parameters || 'DEFAULT',
			filters: params.filters || 'DEFAULT',
			sorters: params.sorters || 'DEFAULT',
			fullPath: params.fullPath || 'DEFAULT',
			columnList: params.columnList || 'DEFAULT',
			lang: params.lang || 'DEFAULT'
		};
	}
};

/**********************
 * Utility Methods
 **********************/

/**
 * Property setter
 */
Class.prototype.setParam = function(prop, value) {
	if (this.params.hasOwnProperty(prop)) {
		this.params[prop] = value;
	}
};

/**
 * To Array
 */
Class.prototype.toParamsArray = function(params) {
	var result = [];
	var prefix = '@';
	var value = '';

	for (var prop in params) {
		prefix = (prop !== 'userId') ? '@' : '@@';
		value = params[prop];

		if(prop === 'tableName' || prop === 'mode')
			if(value !== 'DEFAULT')
				value = '\'' + params[prop] + '\'';

		result.push(prefix + prop + '=' + value);
	}

	return result;
};

/**
 * To String
 */
Class.prototype.toParamsString = function(params) {
	return this.toParamsArray(params).join(', ');
};

// ToDo: Rename to Parse Catalog (parseCatalog)
/**
 * Get Catalog object from XML (from getXMLData)
 */
Class.prototype.getCatalog = function(xml, callback) {
	var xmlDoc = libxmljs.parseXml(xml); // Sync func

	if(!xmlDoc)
		return callback({message: "Error: Parsing XML"});

	var catalog = {
		dbId: xmlDoc.root().attr("dbId").value(),
		lang: xmlDoc.root().attr("lang").value(),
		Table_Schema: xmlDoc.root().attr("Table_Schema").value(),
		Table_Name: xmlDoc.root().attr("Table_Name").value(),
		mode: xmlDoc.root().attr("mode").value(),
		controlType: xmlDoc.root().attr("controlType").value()
	};

	var fileTemplate = xmlDoc.root().attr("fileTemplate");
	if(fileTemplate)
		catalog.fileTemplate = fileTemplate.value();

	callback(null, catalog);
};

/**
 * Get Filename Location from Catalog
 */
Class.prototype.getFilename = function(catalog, callback) {
	var sLocation = path.join(
		this.config.ui.guis[this.params.output].cache,
		catalog.dbId,
		catalog.lang,
		catalog.Table_Schema,
		catalog.Table_Name,
		catalog.mode
	);

	var sFileName = path.join(sLocation, catalog.controlType + '.js');

	// ToDo: Use Async functions?
	if(fs.existsSync(sFileName) && this.params.rebuild !== '1') {
		console.info('# PanaxJS - Existing file: ' + sFileName);
		callback(null, true, sFileName);
	} else {
		if(fs.existsSync(sFileName)) {
			fs.unlinkSync(sFileName);
			console.info('# PanaxJS - Deleted file: ' + sFileName);
		}
		if(!fs.existsSync(sLocation)) {
			mkdirp(sLocation);
			console.info('# PanaxJS - Mkdirp folder: ' + sLocation);
		}

		console.info('# PanaxJS - Missing file: ' + sFileName);
		callback(null, false, sFileName);
	}
};

// ToDo: Rename to Parse Results (parseResults)
/**
 * Get Results object from XML (from updateDB)
 */
Class.prototype.getResults = function(xml, callback) {
	var xmlDoc = libxmljs.parseXml(xml); // Sync func

	if(!xmlDoc)
		return callback({message: "Error: Parsing XML"});

	var results = [];

	xmlDoc.root().childNodes().forEach(function (child) {
		var res = {};
		var attrs = child.attrs();
		for(var i=0;i<attrs.length;i++) {
			res[attrs[i].name()] = attrs[i].value();
		}
		results.push(res);
	});

	callback(null, results);
};

/**********************
 * Config Methods
 **********************/

/**
 * Wrapper for SQL Queries:
 * [$Table].exportConfig
 * [$Table].config
 */
Class.prototype.tableConfig = function(args, callback) {
	var that = this;

	sql.connect(that.config.db, function (err) {
		if (err)
			return callback(err);

		var sql_req = new sql.Request();
		var sql_str = 'EXEC [$Table].exportConfig';

		if(args.length) {
			sql_str = 'EXEC [$Table].config ';
			sql_str += args.map(function(arg) {return '\''+arg+'\'';}).join(', ');
		}

		sql_req.query(sql_str, function (err, recordset) {
			if (err)
				return callback(err);

			//console.info('# PanaxJS - sql_str: ' + sql_str);

			callback(null, recordset);
		});
	});
}

/**
 * Wrapper for SQL Query:
 * [$Table].clearConfig
 */
Class.prototype.clearConfig = function(args, callback) {
	var that = this;

	sql.connect(that.config.db, function (err) {
		if (err)
			return callback(err);

		var sql_req = new sql.Request();
		var sql_str = 'EXEC [$Table].clearConfig ';

		sql_str += args.map(function(arg) {return '\''+arg+'\'';}).join(', ');

		sql_req.query(sql_str, function (err, recordset) {
			if (err)
				return callback(err);

			//console.info('# PanaxJS - sql_str: ' + sql_str);

			callback(null, recordset);
		});
	});
}

/**
 * Wrapper for SQL Query:
 * [$Table].clearCache
 */
Class.prototype.clearCache = function(args, callback) {
	var that = this;

	sql.connect(that.config.db, function (err) {
		if (err)
			return callback(err);

		var sql_req = new sql.Request();
		var sql_str = 'EXEC [$Ver:' + that.config.db.version + '].clearCache ';

		sql_str += args.map(function(arg) {return '\''+arg+'\'';}).join(', ');

		sql_req.query(sql_str, function (err, recordset) {
			if (err)
				return callback(err);

			//console.info('# PanaxJS - sql_str: ' + sql_str);

			callback(null, recordset);
		});
	});
}

/**
 * Wrapper for SQL Query:
 * [$Metadata].rebuild
 */
Class.prototype.rebuildMetadata = function(callback) {
	var that = this;

	sql.connect(that.config.db, function (err) {
		if (err)
			return callback(err);

		var sql_req = new sql.Request();
		var sql_str = 'EXEC [$Metadata].rebuild';

		sql_req.query(sql_str, function (err, recordset) {
			if (err)
				return callback(err);

			//console.info('# PanaxJS - sql_str: ' + sql_str);

			callback(null, recordset);
		});
	});
}

/**********************
 * Session Methods
 **********************/

/**
 * Get Vendor Info
 */
Class.prototype.getVendorInfo = function(callback) {
	var that = this;

	sql.connect(that.config.db, function (err) {
		if (err)
			return callback(err);

		var sql_req = new sql.Request();
		var sql_str = 'SELECT @@version as version';

		sql_req.query(sql_str, function (err, recordset) {
			if (err)
				return callback(err);

			console.info('# PanaxJS - sql_str: ' + sql_str);

			if(!recordset[0])
				return callback({message: "Error: Missing Vendor Info"});

			callback(null, recordset[0]);
		});
	});
};

/**
 * Wrapper for SQL Procedure:
 * [$PanaxDB].Authenticate
 */
Class.prototype.authenticate = function(username, password, callback) {
	var that = this;

	sql.connect(that.config.db, function (err) {
		if (err)
			return callback(err);

		var sql_req = new sql.Request();
		var sql_str = '[$Security].Authenticate';

		sql_req.input('username', sql.VarChar, username);
		sql_req.input('password', sql.VarChar, password);

		sql_req.execute(sql_str, function (err, recordsets, returnValue) {
			if (err)
				return callback(err);

			console.info('# PanaxJS - sql_str: ' + sql_str);

			var userId = recordsets[0][0].userId;
			//ToDo: oCn.execute "IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.ROUTINES IST WHERE routine_schema IN ('$Application') AND ROUTINE_NAME IN ('OnStartUp')) BEGIN EXEC [$Application].OnStartUp END"

			callback(null, userId);
		});
	});
};

/**
 * Wrapper for SQL Query:
 * [$PanaxDB].UserSitemap
 */
Class.prototype.getSitemap = function(callback) {
	var that = this;

	sql.connect(that.config.db, function (err) {
		if (err)
			return callback(err);

		var sql_req = new sql.Request();
		var sql_str = '[$Security].UserSitemap @@userId=' + that.params.userId;

		sql_req.query(sql_str, function (err, recordset) {
			if (err)
				return callback(err);

			console.info('# PanaxJS - sql_str: ' + sql_str);

			var xml = recordset[0]['userSiteMap'];

			if(!xml)
				return callback({message: "Error: Missing Sitemap XML"});

			callback(null, xml);
		});
	});
};

/**********************
 * CRUD Methods
 **********************/

/**
 * Wrapper for SQL Query:
 * [$Table].getCatalogOptions
 */
Class.prototype.getCatalogOptions = function(args, callback) {
	var that = this;

	sql.connect(that.config.db, function (err) {
		if (err)
			return callback(err);

		var sql_req = new sql.Request();
		var sql_str = 'EXEC [$Table].getCatalogOptions @@userId=' + that.params.userId + ", @catalogName='" + args.catalogName + "', " +
									"@valueColumn='" + args.valueColumn + "', @textColumn='" + args.textColumn + "'";

		sql_req.query(sql_str, function (err, recordset) {
			if (err)
				return callback(err);

			console.info('# PanaxJS - sql_str: ' + sql_str);

			var xml = recordset[0][''];

			if(!xml)
				return callback({message: "Error: Missing XML Data"});

			callback(null, xml);
		});
	});
};

/**
 * Wrapper for SQL Query:
 * [$PanaxDB].getXmlData
 */
// ToDo: Rename to getXmlData?
Class.prototype.getXML = function(callback) {
	var that = this;

	sql.connect(that.config.db, function (err) {
		if (err)
			return callback(err);

		var sql_req = new sql.Request();
		var sql_str = 'EXEC [$Ver:' + that.config.db.version + '].getXmlData ' + that.toParamsString(that.params);

		sql_req.query(sql_str, function (err, recordset) {
			if (err)
				return callback(err);

			console.info('# PanaxJS - sql_str: ' + sql_str);

			var xml = recordset[0][''];

			if(!xml)
				return callback({message: "Error: Missing XML Data"});

			callback(null, xml);
		});
	});
};

/**
 * Wrapper for SQL Query:
 * [$PanaxDB].UpdateDB
 */
Class.prototype.updateDB = function(xml, callback) {
	var that = this;

	sql.connect(that.config.db, function (err) {
		if (err)
			return callback(err);

		var sql_req = new sql.Request();
		var sql_str = "[$Tables].UpdateDB @userId=" + that.params.userId + ", @updateXML='" + xml + "'";

		sql_req.query(sql_str, function (err, recordset) {
			if (err)
				return callback(err);

			console.info('# PanaxJS - sql_str: ' + sql_str);

			var xml = recordset[0][''];

			if(!xml)
				return callback({message: "Error: Missing XML Data"});

			callback(null, xml);
		});
	});
};

/**********************
 * Module Export
 **********************/

module.exports = Class;
<commit_msg>REFACTORING: Use Promises to handle SQL Connections 	- https://github.com/patriksimek/node-mssql/issues/138 	- https://github.com/patriksimek/node-mssql/issues/135<commit_after>/**
 * Panax.js
 *
 * PanaxDB Abstraction Class
 *
 * HowTo instantiate:
 *
 * var Panax = new require('Panax')(config, params);
 *
 */
var sql = require('mssql');
var libxmljs = require('libxslt').libxmljs;
var path = require('path');
var fs = require('fs');
var mkdirp = require('mkdirp');

// ToDo
// @Parameters (Unknown)
// @FullPath (Unknown XPath)
// @ColumnList (Unknown XML parsing for Create, Update & Delete ?)
//
// ToDo from Panax.asp:
// Class_Initialize()
// - ln 26-84: Process Session Variables & Parameters
// - ln 91-100: Handle EncryptedID (eid). In different request? (ex. /to?eid=X)
// - ln 106-166: Filters: Manipulate filters
// - ln 167-169: Filters: Set identityKey filter
// - ln 172-175: Filters: Join filters
// - ln: 177-186: Sorters
//
// ToDo from xmlCatalogOptions.asp:
// @Filters
// @extraOptions
// @sortDirection
// @orderBy
// @enableInsert

/**
 * Constructor
 */
var Class = function(config, params) {

	this.config = config;

	if(!params) {
		this.params = {};
	} else {
		this.params = {
			userId: params.userId,
			tableName: params.tableName,
			output: params.output,
			getData: params.getData || '1',
			getStructure: params.getStructure || '1',
			rebuild: params.rebuild || 'DEFAULT',
			controlType: params.controlType || 'DEFAULT',
			mode: params.mode || 'DEFAULT',
			pageIndex: params.pageIndex || 'DEFAULT',
			pageSize: params.pageSize || 'DEFAULT',
			maxRecords: params.maxRecords || 'DEFAULT',
			parameters: params.parameters || 'DEFAULT',
			filters: params.filters || 'DEFAULT',
			sorters: params.sorters || 'DEFAULT',
			fullPath: params.fullPath || 'DEFAULT',
			columnList: params.columnList || 'DEFAULT',
			lang: params.lang || 'DEFAULT'
		};
	}
};

/**********************
 * Utility Methods
 **********************/

/**
 * Property setter
 */
Class.prototype.setParam = function(prop, value) {
	if (this.params.hasOwnProperty(prop)) {
		this.params[prop] = value;
	}
};

/**
 * To Array
 */
Class.prototype.toParamsArray = function(params) {
	var result = [];
	var prefix = '@';
	var value = '';

	for (var prop in params) {
		prefix = (prop !== 'userId') ? '@' : '@@';
		value = params[prop];

		if(prop === 'tableName' || prop === 'mode')
			if(value !== 'DEFAULT')
				value = '\'' + params[prop] + '\'';

		result.push(prefix + prop + '=' + value);
	}

	return result;
};

/**
 * To String
 */
Class.prototype.toParamsString = function(params) {
	return this.toParamsArray(params).join(', ');
};

// ToDo: Rename to Parse Catalog (parseCatalog)
/**
 * Get Catalog object from XML (from getXMLData)
 */
Class.prototype.getCatalog = function(xml, callback) {
	var xmlDoc = libxmljs.parseXml(xml); // Sync func

	if(!xmlDoc)
		return callback({message: "Error: Parsing XML"});

	var catalog = {
		dbId: xmlDoc.root().attr("dbId").value(),
		lang: xmlDoc.root().attr("lang").value(),
		Table_Schema: xmlDoc.root().attr("Table_Schema").value(),
		Table_Name: xmlDoc.root().attr("Table_Name").value(),
		mode: xmlDoc.root().attr("mode").value(),
		controlType: xmlDoc.root().attr("controlType").value()
	};

	var fileTemplate = xmlDoc.root().attr("fileTemplate");
	if(fileTemplate)
		catalog.fileTemplate = fileTemplate.value();

	callback(null, catalog);
};

/**
 * Get Filename Location from Catalog
 */
Class.prototype.getFilename = function(catalog, callback) {
	var sLocation = path.join(
		this.config.ui.guis[this.params.output].cache,
		catalog.dbId,
		catalog.lang,
		catalog.Table_Schema,
		catalog.Table_Name,
		catalog.mode
	);

	var sFileName = path.join(sLocation, catalog.controlType + '.js');

	// ToDo: Use Async functions?
	if(fs.existsSync(sFileName) && this.params.rebuild !== '1') {
		console.info('# PanaxJS - Existing file: ' + sFileName);
		callback(null, true, sFileName);
	} else {
		if(fs.existsSync(sFileName)) {
			fs.unlinkSync(sFileName);
			console.info('# PanaxJS - Deleted file: ' + sFileName);
		}
		if(!fs.existsSync(sLocation)) {
			mkdirp(sLocation);
			console.info('# PanaxJS - Mkdirp folder: ' + sLocation);
		}

		console.info('# PanaxJS - Missing file: ' + sFileName);
		callback(null, false, sFileName);
	}
};

// ToDo: Rename to Parse Results (parseResults)
/**
 * Get Results object from XML (from updateDB)
 */
Class.prototype.getResults = function(xml, callback) {
	var xmlDoc = libxmljs.parseXml(xml); // Sync func

	if(!xmlDoc)
		return callback({message: "Error: Parsing XML"});

	var results = [];

	xmlDoc.root().childNodes().forEach(function (child) {
		var res = {};
		var attrs = child.attrs();
		for(var i=0;i<attrs.length;i++) {
			res[attrs[i].name()] = attrs[i].value();
		}
		results.push(res);
	});

	callback(null, results);
};

/**********************
 * Config Methods
 **********************/

/**
 * Wrapper for SQL Queries:
 * [$Table].exportConfig
 * [$Table].config
 */
Class.prototype.tableConfig = function(args, callback) {
	var that = this;
	var sql_conn = new sql.Connection(that.config.db);

	sql_conn.connect().then(function () {
		var sql_req = new sql.Request(sql_conn);
		var sql_str = 'EXEC [$Table].exportConfig';

		if(args.length) {
			sql_str = 'EXEC [$Table].config ';
			sql_str += args.map(function(arg) {return '\''+arg+'\'';}).join(', ');
		}

		sql_req.query(sql_str).then(function (recordset) {
			//console.info('# PanaxJS - sql_str: ' + sql_str);

			callback(null, recordset);
		}).catch(function (err) {
			callback(err);
		});
	}).catch(function (err) {
		callback(err);
	});
}

/**
 * Wrapper for SQL Query:
 * [$Table].clearConfig
 */
Class.prototype.clearConfig = function(args, callback) {
	var that = this;
	var sql_conn = new sql.Connection(that.config.db);

	sql_conn.connect().then(function () {
		var sql_req = new sql.Request(sql_conn);
		var sql_str = 'EXEC [$Table].clearConfig ';

		sql_str += args.map(function(arg) {return '\''+arg+'\'';}).join(', ');

		sql_req.query(sql_str).then(function (recordset) {
			//console.info('# PanaxJS - sql_str: ' + sql_str);

			callback(null, recordset);
		}).catch(function (err) {
			callback(err);
		});
	}).catch(function (err) {
		callback(err);
	});
}

/**
 * Wrapper for SQL Query:
 * [$Table].clearCache
 */
Class.prototype.clearCache = function(args, callback) {
	var that = this;
	var sql_conn = new sql.Connection(that.config.db);

	sql_conn.connect().then(function () {
		var sql_req = new sql.Request(sql_conn);
		var sql_str = 'EXEC [$Ver:' + that.config.db.version + '].clearCache ';

		sql_str += args.map(function(arg) {return '\''+arg+'\'';}).join(', ');

		sql_req.query(sql_str).then(function (recordset) {
			//console.info('# PanaxJS - sql_str: ' + sql_str);

			callback(null, recordset);
		}).catch(function (err) {
			callback(err);
		});
	}).catch(function (err) {
		callback(err);
	});
}

/**
 * Wrapper for SQL Query:
 * [$Metadata].rebuild
 */
Class.prototype.rebuildMetadata = function(callback) {
	var that = this;
	var sql_conn = new sql.Connection(that.config.db);

	sql_conn.connect().then(function () {
		var sql_req = new sql.Request(sql_conn);
		var sql_str = 'EXEC [$Metadata].rebuild';

		sql_req.query(sql_str).then(function (recordset) {
			//console.info('# PanaxJS - sql_str: ' + sql_str);

			callback(null, recordset);
		}).catch(function (err) {
			callback(err);
		});
	}).catch(function (err) {
		callback(err);
	});
}

/**********************
 * Session Methods
 **********************/

/**
 * Get Vendor Info
 */
Class.prototype.getVendorInfo = function(callback) {
	var that = this;
	var sql_conn = new sql.Connection(that.config.db);

	sql_conn.connect().then(function () {
		var sql_req = new sql.Request(sql_conn);
		var sql_str = 'SELECT @@version as version';

		sql_req.query(sql_str).then(function (recordset) {
			console.info('# PanaxJS - sql_str: ' + sql_str);

			if(!recordset[0])
				return callback({message: "Error: Missing Vendor Info"});

			callback(null, recordset[0]);
		}).catch(function (err) {
			callback(err);
		});
	}).catch(function (err) {
		callback(err);
	});
};

/**
 * Wrapper for SQL Procedure:
 * [$PanaxDB].Authenticate
 */
Class.prototype.authenticate = function(username, password, callback) {
	var that = this;
	var sql_conn = new sql.Connection(that.config.db);

	sql_conn.connect().then(function () {
		var sql_req = new sql.Request(sql_conn);
		var sql_str = '[$Security].Authenticate';

		sql_req.input('username', sql.VarChar, username);
		sql_req.input('password', sql.VarChar, password);

		sql_req.execute(sql_str).then(function (recordsets, returnValue) {
			console.info('# PanaxJS - sql_str: ' + sql_str);

			var userId = recordsets[0][0].userId;
			//ToDo: oCn.execute "IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.ROUTINES IST WHERE routine_schema IN ('$Application') AND ROUTINE_NAME IN ('OnStartUp')) BEGIN EXEC [$Application].OnStartUp END"

			callback(null, userId);
		}).catch(function (err) {
			callback(err);
		});
	}).catch(function (err) {
		callback(err);
	});
};

/**
 * Wrapper for SQL Query:
 * [$PanaxDB].UserSitemap
 */
Class.prototype.getSitemap = function(callback) {
	var that = this;
	var sql_conn = new sql.Connection(that.config.db);

	sql_conn.connect().then(function () {
		var sql_req = new sql.Request(sql_conn);
		var sql_str = '[$Security].UserSitemap @@userId=' + that.params.userId;

		sql_req.query(sql_str).then(function (recordset) {
			console.info('# PanaxJS - sql_str: ' + sql_str);

			var xml = recordset[0]['userSiteMap'];

			if(!xml)
				return callback({message: "Error: Missing Sitemap XML"});

			callback(null, xml);
		}).catch(function (err) {
			callback(err);
		});
	}).catch(function (err) {
		callback(err);
	});
};

/**********************
 * CRUD Methods
 **********************/

/**
 * Wrapper for SQL Query:
 * [$Table].getCatalogOptions
 */
Class.prototype.getCatalogOptions = function(args, callback) {
	var that = this;
	var sql_conn = new sql.Connection(that.config.db);

	sql_conn.connect().then(function() {
		var sql_req = new sql.Request(sql_conn);
		var sql_str = 'EXEC [$Table].getCatalogOptions @@userId=' + that.params.userId + ", @catalogName='" + args.catalogName + "', " +
									"@valueColumn='" + args.valueColumn + "', @textColumn='" + args.textColumn + "'";

		sql_req.query(sql_str).then(function (recordset) {
			console.info('# PanaxJS - sql_str: ' + sql_str);

			var xml = recordset[0][''];

			if(!xml)
				return callback({message: "Error: Missing XML Data"});

			callback(null, xml);
		}).catch(function (err) {
			callback(err);
		});
	}).catch(function (err) {
		callback(err);
	});
};

/**
 * Wrapper for SQL Query:
 * [$PanaxDB].getXmlData
 */
// ToDo: Rename to getXmlData?
Class.prototype.getXML = function(callback) {
	var that = this;
	var sql_conn = new sql.Connection(that.config.db);

	sql_conn.connect().then(function () {
		var sql_req = new sql.Request(sql_conn);
		var sql_str = 'EXEC [$Ver:' + that.config.db.version + '].getXmlData ' + that.toParamsString(that.params);

		sql_req.query(sql_str).then(function (recordset) {
			console.info('# PanaxJS - sql_str: ' + sql_str);

			var xml = recordset[0][''];

			if(!xml)
				return callback({message: "Error: Missing XML Data"});

			callback(null, xml);
		}).catch(function (err) {
			callback(err);
		});
	}).catch(function (err) {
		callback(err);
	});
};

/**
 * Wrapper for SQL Query:
 * [$PanaxDB].UpdateDB
 */
Class.prototype.updateDB = function(xml, callback) {
	var that = this;
	var sql_conn = new sql.Connection(that.config.db);

	sql_conn.connect().then(function () {
		var sql_req = new sql.Request(sql_conn);
		var sql_str = "[$Tables].UpdateDB @userId=" + that.params.userId + ", @updateXML='" + xml + "'";

		sql_req.query(sql_str).then(function (recordset) {
			console.info('# PanaxJS - sql_str: ' + sql_str);

			var xml = recordset[0][''];

			if(!xml)
				return callback({message: "Error: Missing XML Data"});

			callback(null, xml);
		}).catch(function (err) {
			callback(err);
		});
	}).catch(function (err) {
		callback(err);
	});
};

/**********************
 * Module Export
 **********************/

module.exports = Class;
<|endoftext|>