<commit_before>#pragma strict

var origin : Transform;

var ray : Ray;
private var direction : Vector3;

function Awake () {
    direction = origin.forward;
}

function Update () {
    ray = MouseMovementRay();
}

private function DirectPointingRay () : Ray {
    var cameraHitInfo = RaycastHit ();
    var cameraRay = CameraManager.activeCamera.ScreenPointToRay(Input.mousePosition);
    if (Physics.Raycast(cameraRay, cameraHitInfo)) {
        return Ray(origin.position, cameraHitInfo.point - origin.position);
    } else {
        var aimingPoint = CameraManager.activeCamera.ScreenToWorldPoint(Vector3(Input.mousePosition.x, Input.mousePosition.y, 200));
        return Ray(origin.position, aimingPoint - origin.position);
    }
}

private function MouseMovementRay () : Ray {
    var sensitivity = 10;
    var newDirection = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * sensitivity, origin.up) * Quaternion.AngleAxis(Input.GetAxis("Mouse Y") * -sensitivity, origin.right) * direction;
    if (Vector3.Angle(newDirection, origin.forward) < 60) {
        direction = newDirection;
    }
    return Ray(origin.position, direction);
}
<commit_msg>Fixed aiming direction - it needs to be kept in local space.<commit_after>#pragma strict

var origin : Transform;

var ray : Ray;
private var direction : Vector3;

function Awake () {
    direction = origin.forward;
}

function Update () {
    ray = MouseMovementRay();
}

private function DirectPointingRay () : Ray {
    var cameraHitInfo = RaycastHit ();
    var cameraRay = CameraManager.activeCamera.ScreenPointToRay(Input.mousePosition);
    if (Physics.Raycast(cameraRay, cameraHitInfo)) {
        return Ray(origin.position, cameraHitInfo.point - origin.position);
    } else {
        var aimingPoint = CameraManager.activeCamera.ScreenToWorldPoint(Vector3(Input.mousePosition.x, Input.mousePosition.y, 200));
        return Ray(origin.position, aimingPoint - origin.position);
    }
}

private function MouseMovementRay () : Ray {
    var sensitivity = 10;
    var newDirection = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * sensitivity, Vector3.up) * Quaternion.AngleAxis(Input.GetAxis("Mouse Y") * -sensitivity, Vector3.right) * direction;
    if (Vector3.Angle(newDirection, Vector3.forward) < 60) {
        direction = newDirection;
    }

    return Ray(origin.position, origin.TransformDirection(direction));
}
<|endoftext|>


<commit_before>var util = require('util') // Native Node util module
  , path = require('path')
  , EventEmitter = require('events').EventEmitter
  , Task
  , TaskBase
  , utils = require('../utils')
  , async = require('async')
  , rule; // Lazy-require this at the bottom

var UNDEFINED_VALUE;

/**
  @name jake
  @namespace jake
*/
/**
  @name jake.Task
  @constructor
  @augments EventEmitter
  @description A Jake Task

  @param {String} name The name of the Task
  @param {Array} [prereqs] Prerequisites to be run before this task
  @param {Function} [action] The action to perform for this task
  @param {Object} [opts]
    @param {Array} [opts.asyc=false] Perform this task asynchronously.
    If you flag a task with this option, you must call the global
    `complete` method inside the task's action, for execution to proceed
    to the next task.
 */
Task = function () {
  // Do constructor-work only on actual instances, not when used
  // for inheritance
  if (arguments.length) {
    this.init.apply(this, arguments);
  }
};

util.inherits(Task, EventEmitter);

TaskBase = new (function () {

  // Parse any positional args attached to the task-name
  var parsePrereqName = function (name) {
        var taskArr = name.split('[')
          , taskName = taskArr[0]
          , taskArgs = [];
        if (taskArr[1]) {
          taskArgs = taskArr[1].replace(/\]$/, '');
          taskArgs = taskArgs.split(',');
        }
        return {
          name: taskName
        , args: taskArgs
        };
      };

  /**
    @name jake.Task#event:complete
    @event
   */

  this.init = function (name, prereqs, action, options) {
    var opts = options || {};

    this._currentPrereqIndex = 0;

    this.name = name;
    this.prereqs = prereqs;
    this.action = action;
    this.async = false;
    this.done = false;
    this.fullName = null;
    this.description = null;
    this.args = [];
    this.value = UNDEFINED_VALUE;
    this.namespace = null;
    this.runparallel = 1;

    // Support legacy async-flag -- if not explicitly passed or falsy, will
    // be set to empty-object
    if (typeof opts == 'boolean' && opts === true) {
      this.async = true;
    }
    else {
      if (opts.async) {
        this.async = true;
      }
      if (opts.runparallel) {
        this.runparallel = opts.runparallel;
      }
    }
  };

  /**
    @name jake.Task#invoke
    @function
    @description Runs prerequisites, then this task. If the task has already
    been run, will not run the task again.
   */
  this.invoke = function () {
    jake._invocationChain.push(this);
    this.args = Array.prototype.slice.call(arguments);
    this.runPrereqs();
  };

  /**
    @name jake.Task#execute
    @function
    @description Runs prerequisites, then this task. If the task has already
    been run, will not run the task again.
   */
  this.execute = function () {
    jake._invocationChain.push(this);
    this.args = Array.prototype.slice.call(arguments);
    this.reenable();
    this.run();
  };

  this.runPrereqs = function () {
    if (this.prereqs && this.prereqs.length) {
      if(this.runparallel > 1) {
        console.log("Run prereqs for '"+this.name+"' in parallel", this.prereqs);
        var currenttask = this;
        async.eachLimit(currenttask.prereqs,currenttask.runparallel,function(name, cb) {

          parsed = parsePrereqName(name);

          prereq = currenttask.namespace.resolveTask(parsed.name) ||
          jake.attemptRule(name, currenttask.namespace, 0) ||
          jake.createPlaceholderFileTask(name, currenttask.namespace);

          if (!prereq) {
            throw new Error('Unknown task "' + name + '"');
          }

          if (prereq.done) {
            //prereq already done, return
            cb();
          } else {
            //wait for complete before calling cb
            prereq.once('complete', function () {
              cb();
            });
            prereq.invoke.apply(prereq, parsed.args);
          }
        }, function(err) {
          //async callback is called after all prereqs have run.
          console.log("All prereqs for task '"+currenttask.name+"' done.");
          currenttask.run();
        });
      } else {
        this.nextPrereq();
      }
    }
    else {
      this.run();
    }
  };

  this.nextPrereq = function () {
    var self = this
      , index = this._currentPrereqIndex
      , name = this.prereqs[index]
      , prereq
      , parsed
      , filePath
      , stats;

    if (name) {

      parsed = parsePrereqName(name);

      prereq = this.namespace.resolveTask(parsed.name) ||
          jake.attemptRule(name, this.namespace, 0) ||
          jake.createPlaceholderFileTask(name, this.namespace);

      if (!prereq) {
        throw new Error('Unknown task "' + name + '"');
      }

      // Do when done
      if (prereq.done) {
        self.handlePrereqComplete(prereq);
      } else {
        prereq.once('complete', function () {
          self.handlePrereqComplete(prereq);
        });
        prereq.invoke.apply(prereq, parsed.args);
      }
    }
  };

  /**
    @name jake.Task#reenable
    @function
    @description Reenables a task so that it can be run again.
   */
  this.reenable = function (deep) {
    var prereqs
      , prereq;
    this.done = false;
    this.value = UNDEFINED_VALUE;
    if (deep && this.prereqs) {
      prereqs = this.prereqs;
      for (var i = 0, ii = prereqs.length; i < ii; i++) {
        prereq = jake.Task[prereqs[i]];
        if (prereq) {
          prereq.reenable(deep);
        }
      }
    }
  };

  this.handlePrereqComplete = function (prereq) {
    var self = this;
    this._currentPrereqIndex++;
    if (this._currentPrereqIndex < this.prereqs.length) {
      setTimeout(function () {
        self.nextPrereq();
      }, 0);
    }
    else {
      this.run();
    }
  };

  this.isNeeded = function () {
    if (this.done || typeof this.action != 'function') {
      return false;
    }
    return true;
  };

  this.run = function () {
    var runAction = this.isNeeded()
      , val;

    if (runAction) {
      this.emit('start');
      try {
        val = this.action.apply(this, this.args);

        if (typeof val == 'object' && typeof val.then == 'function') {
          this.async = true;

          val.then(
            function(result) {
              setTimeout(function() {
                  complete(result);
                },
                0);
            },
            function(err) {
              setTimeout(function() {
                  fail(err);
                },
                0);
            });
        }
      }
      catch (e) {
        this.emit('error', e);
        return; // Bail out, not complete
      }
    }
    else {
      this.emit('skip');
    }

    if (!(runAction && this.async)) {
      complete(val);
    }
  };

  this.complete = function (val) {
    //console.log("chain=", jake._invocationChain.map(function(c) {return c.name}));
    //console.log("will remove:", this.name);
    jake._invocationChain.splice(jake._invocationChain.indexOf(this),1);

    this._currentPrereqIndex = 0;
    this.done = true;

    // If 'complete' getting called because task has been
    // run already, value will not be passed -- leave in place
    if (typeof val != 'undefined') {
      this.value = val;
    }

    this.emit('complete', this.value);
  };

})();
utils.mixin(Task.prototype, TaskBase);

Task.getBaseNamespacePath = function (fullName) {
  return fullName.split(':').slice(0, -1).join(':');
};

Task.getBaseTaskName = function (fullName) {
  return fullName.split(':').pop();
};

exports.Task = Task;

// Lazy-require
rule = require('../rule');

<commit_msg>Do not start a task twice when runnning concurrent tasks<commit_after>var util = require('util') // Native Node util module
  , path = require('path')
  , EventEmitter = require('events').EventEmitter
  , Task
  , TaskBase
  , utils = require('../utils')
  , async = require('async')
  , rule; // Lazy-require this at the bottom

var UNDEFINED_VALUE;

/**
  @name jake
  @namespace jake
*/
/**
  @name jake.Task
  @constructor
  @augments EventEmitter
  @description A Jake Task

  @param {String} name The name of the Task
  @param {Array} [prereqs] Prerequisites to be run before this task
  @param {Function} [action] The action to perform for this task
  @param {Object} [opts]
    @param {Array} [opts.asyc=false] Perform this task asynchronously.
    If you flag a task with this option, you must call the global
    `complete` method inside the task's action, for execution to proceed
    to the next task.
 */
Task = function () {
  // Do constructor-work only on actual instances, not when used
  // for inheritance
  if (arguments.length) {
    this.init.apply(this, arguments);
  }
};

util.inherits(Task, EventEmitter);

TaskBase = new (function () {

  // Parse any positional args attached to the task-name
  var parsePrereqName = function (name) {
        var taskArr = name.split('[')
          , taskName = taskArr[0]
          , taskArgs = [];
        if (taskArr[1]) {
          taskArgs = taskArr[1].replace(/\]$/, '');
          taskArgs = taskArgs.split(',');
        }
        return {
          name: taskName
        , args: taskArgs
        };
      };

  /**
    @name jake.Task#event:complete
    @event
   */

  this.init = function (name, prereqs, action, options) {
    var opts = options || {};

    this._currentPrereqIndex = 0;

    this.name = name;
    this.prereqs = prereqs;
    this.action = action;
    this.async = false;
    this.done = false;
    this.fullName = null;
    this.description = null;
    this.args = [];
    this.value = UNDEFINED_VALUE;
    this.namespace = null;
    this.runparallel = 1;
    this.started = false;

    // Support legacy async-flag -- if not explicitly passed or falsy, will
    // be set to empty-object
    if (typeof opts == 'boolean' && opts === true) {
      this.async = true;
    }
    else {
      if (opts.async) {
        this.async = true;
      }
      if (opts.runparallel) {
        this.runparallel = opts.runparallel;
      }
    }
  };

  /**
    @name jake.Task#invoke
    @function
    @description Runs prerequisites, then this task. If the task has already
    been run, will not run the task again.
   */
  this.invoke = function () {
    jake._invocationChain.push(this);
    this.args = Array.prototype.slice.call(arguments);
    this.runPrereqs();
  };

  /**
    @name jake.Task#execute
    @function
    @description Runs prerequisites, then this task. If the task has already
    been run, will not run the task again.
   */
  this.execute = function () {
    jake._invocationChain.push(this);
    this.args = Array.prototype.slice.call(arguments);
    this.reenable();
    this.run();
  };

  this.runPrereqs = function () {
    if (this.prereqs && this.prereqs.length) {
      if(this.runparallel > 1) {
        console.log("Run prereqs for '"+this.name+"' in parallel", this.prereqs);
        var currenttask = this;
        async.eachLimit(currenttask.prereqs,currenttask.runparallel,function(name, cb) {

          parsed = parsePrereqName(name);

          prereq = currenttask.namespace.resolveTask(parsed.name) ||
          jake.attemptRule(name, currenttask.namespace, 0) ||
          jake.createPlaceholderFileTask(name, currenttask.namespace);

          if (!prereq) {
            throw new Error('Unknown task "' + name + '"');
          }

          if (prereq.done) {
            //prereq already done, return
            cb();
          } else {
            //wait for complete before calling cb
            prereq.once('complete', function () {
              cb();
            });
            //start te prereq if we are the first to encounter it
            if(!prereq.started) {
              prereq.started = true;
              prereq.invoke.apply(prereq, parsed.args);
            }
          }
        }, function(err) {
          //async callback is called after all prereqs have run.
          console.log("All prereqs for task '"+currenttask.name+"' done.");
          currenttask.run();
        });
      } else {
        this.nextPrereq();
      }
    }
    else {
      this.run();
    }
  };

  this.nextPrereq = function () {
    var self = this
      , index = this._currentPrereqIndex
      , name = this.prereqs[index]
      , prereq
      , parsed
      , filePath
      , stats;

    if (name) {

      parsed = parsePrereqName(name);

      prereq = this.namespace.resolveTask(parsed.name) ||
          jake.attemptRule(name, this.namespace, 0) ||
          jake.createPlaceholderFileTask(name, this.namespace);

      if (!prereq) {
        throw new Error('Unknown task "' + name + '"');
      }

      // Do when done
      if (prereq.done) {
        self.handlePrereqComplete(prereq);
      } else {
        prereq.once('complete', function () {
          self.handlePrereqComplete(prereq);
        });
        if(!prereq.started) {
           prereq.started = true;
           prereq.invoke.apply(prereq, parsed.args);
        }
      }
    }
  };

  /**
    @name jake.Task#reenable
    @function
    @description Reenables a task so that it can be run again.
   */
  this.reenable = function (deep) {
    var prereqs
      , prereq;
    this.done = false;
    this.started = false;
    this.value = UNDEFINED_VALUE;
    if (deep && this.prereqs) {
      prereqs = this.prereqs;
      for (var i = 0, ii = prereqs.length; i < ii; i++) {
        prereq = jake.Task[prereqs[i]];
        if (prereq) {
          prereq.reenable(deep);
        }
      }
    }
  };

  this.handlePrereqComplete = function (prereq) {
    var self = this;
    this._currentPrereqIndex++;
    if (this._currentPrereqIndex < this.prereqs.length) {
      setTimeout(function () {
        self.nextPrereq();
      }, 0);
    }
    else {
      this.run();
    }
  };

  this.isNeeded = function () {
    if (this.done || typeof this.action != 'function') {
      return false;
    }
    return true;
  };

  this.run = function () {
    var runAction = this.isNeeded()
      , val;

    if (runAction) {
      this.emit('start');
      try {
        val = this.action.apply(this, this.args);

        if (typeof val == 'object' && typeof val.then == 'function') {
          this.async = true;

          val.then(
            function(result) {
              setTimeout(function() {
                  complete(result);
                },
                0);
            },
            function(err) {
              setTimeout(function() {
                  fail(err);
                },
                0);
            });
        }
      }
      catch (e) {
        this.emit('error', e);
        return; // Bail out, not complete
      }
    }
    else {
      this.emit('skip');
    }

    if (!(runAction && this.async)) {
      this.complete(val);
    }
  };

  this.complete = function (val) {
    //console.log("chain=", jake._invocationChain.map(function(c) {return c.name}));
    //console.log("will remove:", this.name);
    jake._invocationChain.splice(jake._invocationChain.indexOf(this),1);

    this._currentPrereqIndex = 0;
    this.done = true;

    // If 'complete' getting called because task has been
    // run already, value will not be passed -- leave in place
    if (typeof val != 'undefined') {
      this.value = val;
    }

    this.emit('complete', this.value);
  };

})();
utils.mixin(Task.prototype, TaskBase);

Task.getBaseNamespacePath = function (fullName) {
  return fullName.split(':').slice(0, -1).join(':');
};

Task.getBaseTaskName = function (fullName) {
  return fullName.split(':').pop();
};

exports.Task = Task;

// Lazy-require
rule = require('../rule');

<|endoftext|>


<commit_before>/*
 * Copyright 2017, Emanuel Rabina (http://www.ultraq.net.nz/)
 *
 * 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
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

const StandardTextAttributeProcessor = require('./processors/StandardTextAttributeProcessor');
const {getThymeleafAttributeValue}   = require('./utilities/Dom');

const Promise                    = require('bluebird');
const {jsdom, serializeDocument} = require('jsdom');

const fs = require('fs');

// List of supported attribute processors, limits what we can do but lets me
// impose basic ordering as per the behaviour in main Thymeleaf.
const ATTRIBUTE_PROCESSORS = [
	StandardTextAttributeProcessor
];

/**
 * Process a DOM element.
 *
 * @param {Element} element
 * @param {Object} context
 */
function processNode(element, context) {

	// Process the current element
	ATTRIBUTE_PROCESSORS.forEach(attributeProcessor => {
		let attribute = getThymeleafAttributeValue(element, attributeProcessor.prefix, attributeProcessor.name);
		if (attribute) {
			attributeProcessor.process(element, attribute, context);
		}
	});

	// Process this element's children
	element.children.forEach(child => {
		processNode(child, context);
	});
}

/**
 * Process the Thymeleaf template data, returning the processed template.
 *
 * @param {String} template
 * @param {Object} context
 * @return {Promise}
 *   Bluebird promise resolved with the processed template, or rejected with an
 *   error message.
 */
function process(template, context) {

	return new Promise((resolve, reject) => {
		try {
			let document = jsdom(template, {
				features: {
					FetchExternalResources: false,
					ProcessExternalResources: false
				}
			});

			processNode(document.documentElement, context);

			let documentAsString = serializeDocument(document);
			resolve(documentAsString);
		}
		catch (exception) {
			reject(exception);
		}
	});
}

exports.process = process;

/**
 * Process the Thymeleaf template at the given path, returning a promise of the
 * processed template.
 *
 * @param {String} filePath
 * @param {Object} context
 * @return {Promise}
 *   Bluebird promise resolved with the processed template, or rejected with an
 *   error message.
 */
function processFile(filePath, context) {

	return new Promise(function(resolve, reject) {
		fs.readFile(filePath, function(error, data) {
			if (error) {
				reject(error);
			}
			else {
				resolve(process(data, context));
			}
		});
	});
}

exports.processFile = processFile;

/**
 * Export for integration w/ Express.
 *
 * @param {String} filePath
 * @param {Object} options
 * @param {Function} callback
 */
exports.__express = function(filePath, options, callback) {

	processFile(filePath, options).then(callback);
};
<commit_msg>Convert nodelist/htmlcollection to array<commit_after>/*
 * Copyright 2017, Emanuel Rabina (http://www.ultraq.net.nz/)
 *
 * 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
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

const StandardTextAttributeProcessor = require('./processors/StandardTextAttributeProcessor');
const {getThymeleafAttributeValue}   = require('./utilities/Dom');

const Promise                    = require('bluebird');
const {jsdom, serializeDocument} = require('jsdom');

const fs = require('fs');

// List of supported attribute processors, limits what we can do but lets me
// impose basic ordering as per the behaviour in main Thymeleaf.
const ATTRIBUTE_PROCESSORS = [
	StandardTextAttributeProcessor
];

/**
 * Process a DOM element.
 *
 * @param {Element} element
 * @param {Object} context
 */
function processNode(element, context) {

	// Process the current element
	ATTRIBUTE_PROCESSORS.forEach(attributeProcessor => {
		let attribute = getThymeleafAttributeValue(element, attributeProcessor.prefix, attributeProcessor.name);
		if (attribute) {
			attributeProcessor.process(element, attribute, context);
		}
	});

	// Process this element's children
	Array.from(element.children).forEach(child => {
		processNode(child, context);
	});
}

/**
 * Process the Thymeleaf template data, returning the processed template.
 *
 * @param {String} template
 * @param {Object} context
 * @return {Promise}
 *   Bluebird promise resolved with the processed template, or rejected with an
 *   error message.
 */
function process(template, context) {

	return new Promise((resolve, reject) => {
		try {
			let document = jsdom(template, {
				features: {
					FetchExternalResources: false,
					ProcessExternalResources: false
				}
			});

			processNode(document.documentElement, context);

			let documentAsString = serializeDocument(document);
			resolve(documentAsString);
		}
		catch (exception) {
			reject(exception);
		}
	});
}

exports.process = process;

/**
 * Process the Thymeleaf template at the given path, returning a promise of the
 * processed template.
 *
 * @param {String} filePath
 * @param {Object} context
 * @return {Promise}
 *   Bluebird promise resolved with the processed template, or rejected with an
 *   error message.
 */
function processFile(filePath, context) {

	return new Promise(function(resolve, reject) {
		fs.readFile(filePath, function(error, data) {
			if (error) {
				reject(error);
			}
			else {
				resolve(process(data, context));
			}
		});
	});
}

exports.processFile = processFile;

/**
 * Export for integration w/ Express.
 *
 * @param {String} filePath
 * @param {Object} options
 * @param {Function} callback
 */
exports.__express = function(filePath, options, callback) {

	processFile(filePath, options).then(callback);
};
<|endoftext|>


<commit_before>/**
 * Run animations easily, just with tss files
 *
 * @auther Mohamed Shaban <mohamed.shaban@codly.io>
 *
 * @param {object}	controller		set of properties from tss file
 */
module.exports = function(controller) {

	var currentState = null,
	    path = "/alloy/styles/" + controller.__controllerPath,
	    styles = require(path);

	/**
	 * Run animation function
	 *
	 * @param string	state		set of properties from tss file
	 * @param integer	duration	anomation duration
	 * @param function	cb			callback function after anomation completed
	 */
	this.changeToState = function(state, duration, cb) {
		console.log('Changing to state =', state, 'with duration =', duration);
		currentState = state;
		var i = 0,
		    comp,
		    style,
		    animation,
		    id = '',
		    props = {};
		for (i; i < styles.length; i += 1) {
			style = styles[i];
			if (style.key.indexOf(":" + state) > 0) {
				id = style.key.replace(":" + state, "").replace("#");

				comp = controller.getView(id);

				// set style and duration
				props = {};
				_.extend(props, style.style, {
					duration : duration
				});

				animation = Ti.UI.createAnimation(props);
				if (i === 0) {
					animation.addEventListener('complete', cb);
				}
				try {
					comp.animate(animation);
				} catch (e) {
					Ti.API.warn("Can't catch #" + id + " to animate");
				}
			}

		}
	};

	/**
	 * Get last called state
	 */
	this.getLastState = function() {
		return this.currentState;
	};
};
<commit_msg>Fix callback issue, now assigning callback to first style has this state instead of just first style<commit_after>/**
 * Run animations easily, just with tss files
 *
 * @auther Mohamed Shaban <mohamed.shaban@codly.io>
 *
 * @param {object}	controller		set of properties from tss file
 */
module.exports = function(controller) {

	var currentState = null,
	    path = "/alloy/styles/" + controller.__controllerPath,
	    styles = require(path);

	/**
	 * Run animation function
	 *
	 * @param string	state		set of properties from tss file
	 * @param integer	duration	anomation duration
	 * @param function	cb			callback function after anomation completed
	 */
	this.changeToState = function(state, duration, cb) {
		console.log('Changing to state =', state, 'with duration =', duration);
		currentState = state;
		var i = 0,
		    comp,
		    style,
		    animation,
		    id = '',
		    props = {},
		    cbAssigned = false;
		for (i; i < styles.length; i += 1) {
			style = styles[i];
			if (style.key.indexOf(":" + state) > 0) {
				id = style.key.replace(":" + state, "").replace("#");

				comp = controller.getView(id);

				// set style and duration
				props = {};
				_.extend(props, style.style, {
					duration : duration
				});

				animation = Ti.UI.createAnimation(props);

				// Make sure this is 1st time to assign callback
				if (!cbAssigned && cb) {
					cbAssigned = true;
					animation.addEventListener('complete', cb);
				}
				try {
					comp.animate(animation);
				} catch (e) {
					Ti.API.warn("Can't catch #" + id + " to animate");
				}
			}

		}
	};

	/**
	 * Get last called state
	 */
	this.getLastState = function() {
		return this.currentState;
	};
};
<|endoftext|>


<commit_before>// Save a reference to the global object (`window` in the browser, `global`
// on the server).
var root = this;

// The top-level namespace. All public Backbone classes and modules will
// be attached to this. Exported for both CommonJS and the browser.
var App, server = false;
if (typeof exports !== 'undefined') {
    App = exports;
    server = true;
} else {
    App = root.App = {};
}

// Require Underscore, Backbone & BackboneIO, if we're on the server, and it's not already present.
var _ = root._;
if (!_ && (typeof require !== 'undefined')) _ = require('underscore');

var BackboneIO = root.BackboneIO;
if ((typeof require !== 'undefined')) Backbone = require('backbone');

App.Collection = Backbone.Collection.extend({
    urlRoot: 'app',
    backend: 'appbackend',
    initialize: function () {
        if (!server) {
            this.bindBackend();

            this.bind('backend', function(method, model) {
                console.log ('got from backend:', method, model);
            });
        }
        console.log ('creating new App.Collection');

        Backbone.Collection.prototype.initialize.call (this);
    }
});

App.Status = Backbone.Model.extend ({
    backend: 'statusbackend',
    urlRoot: 'status',
    idAttribute: '_id',
    initialize: function () {
        if (!server) {
            this.bindBackend();

            this.bind('backend', function(method, model) {
                console.log ('STATUS got from backend:', method, model);
            });
        }
        console.log ('creating new STATUS');

        return Backbone.Model.prototype.initialize.call (this);
    },
    defaults: {
        _id: 2,
        piece: {
            previous: {name: ''},
            current:  {name: '', progress: '0%'},
            next:     {name: ''},
        },
        show: {
            previous: {name: ''},
            current:  {name: '', progress: '0%'},
            next:     {name: ''},
        },
        source: null,
        on_air: false,
    },
});

App.ProgressStatus = Backbone.Model.extend({
    urlRoot: 'progress',
    backend: 'framebackend',
    initialize: function () {
        if (!server) {
            this.bindBackend();

            this.bind('backend', function(method, model) {
                //console.log ('got from backend:', method, model);
            });
        }
        console.log ('creating new App.Model');

        return Backbone.Model.prototype.initialize.call (this);
    },
    defaults: {
        id: 3,
        currentFrame: 0,
        totalFrames: 0,
    },
});

App.TranscodeProgress = Backbone.Model.extend({
    urlRoot: 'transcode',
    backend: 'transcodeprogressbackend',
    idAttribute: '_id',
    initialize: function () {
        return Backbone.Model.prototype.initialize.call (this);
    },
    defaults: {
        'input': {
            'stat': {
                'size': 0,
            },
            'path': '',
        },
        'filename': '',
        'stage':    '',
        'progress': '0',
        // list of: {name:'', status:'', message:''}
        'tasks':  [],
    }
});

App.TranscodeProgressCollection = Backbone.Collection.extend({
    url: 'transcode',
    model: App.TranscodeProgress,
    backend: 'transcodebackend',
    initialize: function () {
        if(!server) {
            this.bindBackend();
        }
    },
});

App.TranscodeStatus = Backbone.Model.extend({
    urlRoot: 'transcodestatus',
    backend: 'transcodestatusbackend',
    idAttribute: '_id',
    initialize: function () {
        if(!server) {
            this.bindBackend();
        }
        return Backbone.Model.prototype.initialize.call (this);
    },
    defaults: {
        '_id': 1,
        'running': false,
    }
});

// Given a path like 'Caspa.Branding.name', a hash-like with the user config
// and another one with defaults retrieves both.
function get_value (path, conf, defaults) {
    var path = path.split('.');
    var val = conf;
    var dfl = defaults;

    var found = false;
    var key;
    var ret = {
        value:   null,
        default: null,
        found:   false,
    };

    do {
        key = path.shift();
        if (_.has(val, key) ) {
            val = val[key];
            if (path.length == 0) {
                found = true;
            }
        }

        if (_.has(dfl, key) ) {
            dfl = dfl[key];
        }
    } while (path.length);

    ret.default = ret.value = dfl;
    ret.found = found;
    if (found) {
        ret.value = val;
    }

    return ret;
};

// Given three objects like the ones returned from configStore, merge them
// in a structure suitable to parse into nested relational models.
// Guess how big N is...
function flatten_conf (conf, defaults, descriptions, root) {
    if (root == undefined) {
        var root = {
            properties: [],
        };

        // XXX: _.omit() returns a copy of the object.
        _.extend(root, _.omit(descriptions, ['properties', 'type']));
        if (!descriptions.type.match(/config|defaults|descriptions|object/)) {
            root.type = descriptions.type;
        }
    }

    _.each(descriptions.properties, function(contents, name, par) {
        var dfl, dsc, cnf;
        var ret = get_value(name, conf, defaults);

        dfl = ret.default;
        cnf = ret.value;
        dsc = contents;

        var elm = {
            name: name,
            properties: [],
        };

        // XXX: _.omit() returns a copy of the object.
        _.extend(elm, _.omit(contents, ['properties', 'type']));
        if (!contents.type.match(/config|defaults|descriptions|object/)) {
            elm.type = contents.type;
        }

        if (!_.has(dsc, 'properties') || dsc.properties.length==0) {
            elm.value = cnf;
            elm.default = dfl;
        }

        root.properties.push(elm);
        flatten_conf(cnf, dfl, dsc, elm);
    });

    return root;
};

// Given a nested structure like the one from RelationalConfig.toJSON()
// transforms it to the format expected by configStore
function relational_to_server_conf (rel, root) {
    var root = root || {};

    _.each(rel.properties, function(contents, name, par) {
        if (!_.has(contents, 'properties') || contents.properties.length==0) {
            root[contents.name] = contents.value;
        } else {
            var elm = { };
            root[contents.name] = elm;
            relational_to_server_conf(contents, elm);
        }
    });

    return root;
};

if(!server){
App.RelationalConfig = Backbone.RelationalModel.extend({
    idAttribute: '_id',
    relations: [{
        type: Backbone.HasMany,
        key: 'properties',
        relatedModel: 'App.RelationalConfig',
        collectionType: 'Backbone.Collection',
        includeInJSON: true,
    }],
    initialize: function () {
        var self = this;
        console.log ('creating new RelationalConfig');
        Backbone.RelationalModel.prototype.initialize.call (this);
    },

    defaults: {
        type:           null,
        widget:         'input',
        title:          '',
        description:    '',
        name:           '',
        value:          null,
        default:        null,
        properties:     [],
    },
});
}

if(server) module.exports = App;
else root.App = App;
<commit_msg>config: correctly handle elements type.<commit_after>// Save a reference to the global object (`window` in the browser, `global`
// on the server).
var root = this;

// The top-level namespace. All public Backbone classes and modules will
// be attached to this. Exported for both CommonJS and the browser.
var App, server = false;
if (typeof exports !== 'undefined') {
    App = exports;
    server = true;
} else {
    App = root.App = {};
}

// Require Underscore, Backbone & BackboneIO, if we're on the server, and it's not already present.
var _ = root._;
if (!_ && (typeof require !== 'undefined')) _ = require('underscore');

var BackboneIO = root.BackboneIO;
if ((typeof require !== 'undefined')) Backbone = require('backbone');

App.Collection = Backbone.Collection.extend({
    urlRoot: 'app',
    backend: 'appbackend',
    initialize: function () {
        if (!server) {
            this.bindBackend();

            this.bind('backend', function(method, model) {
                console.log ('got from backend:', method, model);
            });
        }
        console.log ('creating new App.Collection');

        Backbone.Collection.prototype.initialize.call (this);
    }
});

App.Status = Backbone.Model.extend ({
    backend: 'statusbackend',
    urlRoot: 'status',
    idAttribute: '_id',
    initialize: function () {
        if (!server) {
            this.bindBackend();

            this.bind('backend', function(method, model) {
                console.log ('STATUS got from backend:', method, model);
            });
        }
        console.log ('creating new STATUS');

        return Backbone.Model.prototype.initialize.call (this);
    },
    defaults: {
        _id: 2,
        piece: {
            previous: {name: ''},
            current:  {name: '', progress: '0%'},
            next:     {name: ''},
        },
        show: {
            previous: {name: ''},
            current:  {name: '', progress: '0%'},
            next:     {name: ''},
        },
        source: null,
        on_air: false,
    },
});

App.ProgressStatus = Backbone.Model.extend({
    urlRoot: 'progress',
    backend: 'framebackend',
    initialize: function () {
        if (!server) {
            this.bindBackend();

            this.bind('backend', function(method, model) {
                //console.log ('got from backend:', method, model);
            });
        }
        console.log ('creating new App.Model');

        return Backbone.Model.prototype.initialize.call (this);
    },
    defaults: {
        id: 3,
        currentFrame: 0,
        totalFrames: 0,
    },
});

App.TranscodeProgress = Backbone.Model.extend({
    urlRoot: 'transcode',
    backend: 'transcodeprogressbackend',
    idAttribute: '_id',
    initialize: function () {
        return Backbone.Model.prototype.initialize.call (this);
    },
    defaults: {
        'input': {
            'stat': {
                'size': 0,
            },
            'path': '',
        },
        'filename': '',
        'stage':    '',
        'progress': '0',
        // list of: {name:'', status:'', message:''}
        'tasks':  [],
    }
});

App.TranscodeProgressCollection = Backbone.Collection.extend({
    url: 'transcode',
    model: App.TranscodeProgress,
    backend: 'transcodebackend',
    initialize: function () {
        if(!server) {
            this.bindBackend();
        }
    },
});

App.TranscodeStatus = Backbone.Model.extend({
    urlRoot: 'transcodestatus',
    backend: 'transcodestatusbackend',
    idAttribute: '_id',
    initialize: function () {
        if(!server) {
            this.bindBackend();
        }
        return Backbone.Model.prototype.initialize.call (this);
    },
    defaults: {
        '_id': 1,
        'running': false,
    }
});

// Given a path like 'Caspa.Branding.name', a hash-like with the user config
// and another one with defaults retrieves both.
function get_value (path, conf, defaults) {
    var path = path.split('.');
    var val = conf;
    var dfl = defaults;

    var found = false;
    var key;
    var ret = {
        value:   null,
        default: null,
        found:   false,
    };

    do {
        key = path.shift();
        if (_.has(val, key) ) {
            val = val[key];
            if (path.length == 0) {
                found = true;
            }
        }

        if (_.has(dfl, key) ) {
            dfl = dfl[key];
        }
    } while (path.length);

    ret.default = ret.value = dfl;
    ret.found = found;
    if (found) {
        ret.value = val;
    }

    return ret;
};

// Given three objects like the ones returned from configStore, merge them
// in a structure suitable to parse into nested relational models.
// Guess how big N is...
function flatten_conf (conf, defaults, descriptions, root) {
    if (root == undefined) {
        var root = {
            properties: [],
        };

        // XXX: _.omit() returns a copy of the object.
        _.extend(root, _.omit(descriptions, ['properties', 'type']));
        if (!_.has(descriptions, 'properties') || descriptions.properties.length==0) {
            if (descriptions.type && !descriptions.type.match(/config|defaults|descriptions/)) {
                root.type = descriptions.type;
            }
        }
    }

    _.each(descriptions.properties, function(contents, name, par) {
        var dfl, dsc, cnf;
        var ret = get_value(name, conf, defaults);

        dfl = ret.default;
        cnf = ret.value;
        dsc = contents;

        var elm = {
            name: name,
            properties: [],
        };

        // XXX: _.omit() returns a copy of the object.
        _.extend(elm, _.omit(contents, ['properties', 'type']));
        if (!_.has(dsc, 'properties') || dsc.properties.length==0) {
            elm.value = cnf;
            elm.default = dfl;
            if (contents.type && !contents.type.match(/config|defaults|descriptions/)) {
                elm.type = contents.type;
            }
        }

        root.properties.push(elm);
        flatten_conf(cnf, dfl, dsc, elm);
    });

    return root;
};

// Given a nested structure like the one from RelationalConfig.toJSON()
// transforms it to the format expected by configStore
function relational_to_server_conf (rel, root) {
    var root = root || {};

    _.each(rel.properties, function(contents, name, par) {
        if (!_.has(contents, 'properties') || contents.properties.length==0) {
            root[contents.name] = contents.value;
        } else {
            var elm = { };
            root[contents.name] = elm;
            relational_to_server_conf(contents, elm);
        }
    });

    return root;
};

if(!server){
App.RelationalConfig = Backbone.RelationalModel.extend({
    idAttribute: '_id',
    relations: [{
        type: Backbone.HasMany,
        key: 'properties',
        relatedModel: 'App.RelationalConfig',
        collectionType: 'Backbone.Collection',
        includeInJSON: true,
    }],
    initialize: function () {
        var self = this;
        console.log ('creating new RelationalConfig');
        Backbone.RelationalModel.prototype.initialize.call (this);
    },

    defaults: {
        type:           null,
        widget:         'input',
        title:          '',
        description:    '',
        name:           '',
        value:          null,
        default:        null,
        properties:     [],
    },
});
}

if(server) module.exports = App;
else root.App = App;
<|endoftext|>


<commit_before>/*!
 * transform
 * Version: 0.0.1
 * Date: 2016/8/1
 * https://github.com/Nuintun/fengine
 *
 * Original Author: http://www.jsbug.com/lab/samples/fengine/
 *
 * This is licensed under the MIT License (MIT).
 * For details, see: https://github.com/Nuintun/fengine/blob/master/LICENSE
 */

'use strict';

var CWD = process.cwd();
var fs = require('fs');
var path = require('path');
var util = require('./util');
var Events = require('./events');

var assert = {
  delimiter: function (){

  },
  data: function (){

  },
  directive: function (){

  }
};

/**
 * Transform
 * @param source
 * @param options
 * @constructor
 */
function Transform(source, options){
  if (!util.string(source)) {
    throw new TypeError('source must be a string.');
  }

  var context = this;
  var defaults = {
    src: '',
    root: CWD,
    delimiter: {
      data: ['{{', '}}'],
      command: ['<!--', '-->']
    },
    data: {
      dirname: function (src){
        return path.dirname(src);
      },
      filename: function (src){
        return path.basename(src);
      }
    },
    command: {
      slot: 'slot',
      include: 'include',
      layout: 'layout',
      nonlayout: '!layout'
    }
  };

  context.index = 0;
  context.entry = null;
  context.source = source;
  context.options = options = util.mix({
    src: '',
    root: CWD,
    delimiter: {
      data: ['{{', '}}'],
      directive: ['<!--', '-->']
    },
    data: {
      dirname: function (src){
        return path.dirname(src);
      },
      filename: function (src){
        return path.basename(src);
      }
    },
    directive: {
      slot: 'slot',
      include: 'include',
      layout: 'layout',
      nonlayout: '!layout'
    }
  }, options);

  Object.keys(options.delimiter).forEach(function (delimiter){
    assert.delimiter(delimiter, defaults.delimiter);
  });

  Object.keys(options.data).forEach(function (data){
    assert.data(data, defaults.data);
  });

  Object.keys(options.directive).forEach(function (directive){
    assert.directive(directive, defaults.directive);
  });

  context.src = options.src;
  context.root = options.root;
  context.dirname = path.dirname(context.src);
  context.filename = path.basename(context.src);
  context.regexp = new RegExp(
    util.str4regex(options.delimiter.directive[0])
    + '\\s*(\\S+?)\\s*'
    + util.str4regex(options.delimiter.directive[1])
    + '|'
    + util.str4regex(options.delimiter.data[0])
    + '\\s*(\\S+?)\\s*'
    + util.str4regex(options.delimiter.data[1]),
    'img'
  );
}

/**
 * extend
 * @type {EventEmitter}
 */
Transform.prototype = Object.create(Events.prototype, {
  constructor: { value: Transform }
});

Transform.prototype.exec = function (){
  var context = this;
  var match = context.regexp.exec(context.source);

  if (!match) return false;

  var index = match.index;
  var type = match[1] ? 'directive' : 'data';
  var command = type === 'directive' ? match[1] : match[2];

  match = match[0];

  context.emit('data', context.source.substring(context.index, index));

  if (type === 'directive') {
    if (command === context.options.directive.include) {
      var entry = context.entry;

      while (entry instanceof Transform) {
        if (context.src === entry.src) {
          return true;
        }

        entry = entry.entry;
      }

      fs.readFile(context.resolve(command), function (error, source){
        if (error) {
          return context.next();
        }

        var child = new Transform(source.toString(), context.options);

        child.entry = context;

        child.on('end', function (){
          var entry = this.entry;

          if (this.entry instanceof Transform) {
            entry.next();
          }
        });
      });
    }
  } else {
    context.emit('data', context.options.data[command] || match);
  }

  context.index = index + match.length;

  return true;
};
Transform.prototype.resolve = function (url){
  var context = this;

  if (path.isAbsolute(url)) {
    return path.join(context.root, url);
  } else {
    return path.join(context.dirname, url);
  }
};

Transform.prototype.next = function (){
  if (!this.exec()) {
    this.emit('end');
  }
};

// exports
module.exports = Transform;
<commit_msg>update files<commit_after>/*!
 * transform
 * Version: 0.0.1
 * Date: 2016/8/1
 * https://github.com/Nuintun/fengine
 *
 * Original Author: http://www.jsbug.com/lab/samples/fengine/
 *
 * This is licensed under the MIT License (MIT).
 * For details, see: https://github.com/Nuintun/fengine/blob/master/LICENSE
 */

'use strict';

var CWD = process.cwd();
var fs = require('fs');
var path = require('path');
var util = require('./util');
var Events = require('./events');

var assert = {
  delimiter: function (){

  },
  data: function (){

  },
  directive: function (){

  }
};

/**
 * Transform
 * @param source
 * @param options
 * @constructor
 */
function Transform(source, options){
  if (!util.string(source)) {
    throw new TypeError('source must be a string.');
  }

  var context = this;
  var defaults = {
    src: '',
    root: CWD,
    delimiter: {
      data: ['{{', '}}'],
      command: ['<!--', '-->']
    },
    data: {
      dirname: function (src){
        return path.dirname(src);
      },
      filename: function (src){
        return path.basename(src);
      }
    },
    command: {
      slot: 'slot',
      include: 'include',
      layout: 'layout',
      nonlayout: '!layout'
    }
  };

  context.index = 0;
  context.entry = null;
  context.source = source;
  context.options = options = util.mix({
    src: '',
    root: CWD,
    delimiter: {
      data: ['{{', '}}'],
      directive: ['<!--', '-->']
    },
    data: {
      dirname: function (src){
        return path.dirname(src);
      },
      filename: function (src){
        return path.basename(src);
      }
    },
    directive: {
      slot: 'slot',
      include: 'include',
      layout: 'layout',
      nonlayout: '!layout'
    }
  }, options);

  Object.keys(options.delimiter).forEach(function (delimiter){
    assert.delimiter(delimiter, defaults.delimiter);
  });

  Object.keys(options.data).forEach(function (data){
    assert.data(data, defaults.data);
  });

  Object.keys(options.directive).forEach(function (directive){
    assert.directive(directive, defaults.directive);
  });

  context.src = options.src;
  context.root = options.root;
  context.dirname = path.dirname(context.src);
  context.filename = path.basename(context.src);
  context.regexp = new RegExp(
    util.str4regex(options.delimiter.directive[0])
    + '\\s*(\\S+?)\\s*'
    + util.str4regex(options.delimiter.directive[1])
    + '|'
    + util.str4regex(options.delimiter.data[0])
    + '\\s*(\\S+?)\\s*'
    + util.str4regex(options.delimiter.data[1]),
    'img'
  );

  context.next();
}

/**
 * extend
 * @type {EventEmitter}
 */
Transform.prototype = Object.create(Events.prototype, {
  constructor: { value: Transform }
});

Transform.prototype.exec = function (){
  var context = this;
  var match = context.regexp.exec(context.source);

  if (!match) return false;

  var index = match.index;
  var type = match[1] ? 'directive' : 'data';
  var command = type === 'directive' ? match[1] : match[2];

  match = match[0];

  context.emit('data', context.source.substring(context.index, index));

  if (type === 'directive') {
    if (command === context.options.directive.include) {
      var entry = context.entry;

      while (entry instanceof Transform) {
        if (context.src === entry.src) {
          return true;
        }

        entry = entry.entry;
      }

      fs.readFile(context.resolve(command), function (error, source){
        if (error) {
          return context.next();
        }

        var child = new Transform(source.toString(), context.options);

        child.entry = context;

        child.on('end', function (){
          var entry = this.entry;

          if (this.entry instanceof Transform) {
            entry.next();
          }
        });
      });
    }
  } else {
    context.emit('data', context.options.data[command] || match);
  }

  context.index = index + match.length;

  return true;
};
Transform.prototype.resolve = function (url){
  var context = this;

  if (path.isAbsolute(url)) {
    return path.join(context.root, url);
  } else {
    return path.join(context.dirname, url);
  }
};

Transform.prototype.next = function (){
  if (!this.exec()) {
    this.emit('end');
  }
};

// exports
module.exports = Transform;
<|endoftext|>


<commit_before>import DS from 'ember-data';
import '../computed/foreign-key';

var attr = DS.attr,
    belongsTo = DS.belongsTo;

export default DS.Model.extend({
  quantity:        attr('number'),
  length:          attr('number'),
  width:           attr('number'),
  height:          attr('number'),
  notes:           attr('string'),
  state:           attr('string', {defaultValue:'expecting'}),
  state_event:     attr('string'),
  receivedAt:      attr('date'),
  rejectedAt:      attr('date'),
  createdAt:       attr('date'),
  updatedAt:       attr('date'),
  item:            belongsTo('item', { async: false }),
  packageType:     belongsTo('package_type', { async: false }),
  location:        belongsTo('location', { async: false }),
  favouriteImage:  belongsTo('image', { async: false }),
  offerId:         attr('number'),
  inventoryNumber: attr('string'),
  grade:           attr('string'),
  sentOn:          attr('date'),
  designationId:   attr('number'),

  isDispatched: Ember.computed.bool('sentOn'),
  isDesignated: Ember.computed('designationId', 'sentOn', function () {
    return this.get('designationId') && this.get('sentOn') === null && this.get('inventoryNumber');
  }),

  donorCondition:   belongsTo('donor_condition', { async: false }),
  donorConditionId: Ember.computed.foreignKey('donorCondition.id'),

  isReceived: Ember.computed.equal("state", "received"),

  packageName: Ember.computed('packageType', function(){
    return this.get('packageType.name');
  }),

  packageTypeId:   Ember.computed.foreignKey('packageType.id'),

  packageTypeObject: Ember.computed('packageType', function(){
    var obj = this.get('packageType').getProperties('id', 'name', 'isItemTypeNode');
    obj.id = obj.packageTypeId = parseInt(obj.id);
    return obj;
  }),

  dimensions: Ember.computed('width', 'height', 'length', function(){
    var res = '';
    var append = val => {
      if (val) { res += !res ? val : ' x ' + val; }
    }
    append(this.get('width'));
    append(this.get('height'));
    append(this.get('length'));
    return !res ? '' : res + 'cm';
  }),

  displayImageUrl: Ember.computed("favouriteImage", "item.displayImageUrl", function(){
    return this.get("favouriteImage") ? this.get("favouriteImage.thumbImageUrl") : this.get("item.displayImageUrl");
  })
});
<commit_msg>GCW-1245 update package model<commit_after>import DS from 'ember-data';

export default DS.Model.extend();
<|endoftext|>


<commit_before>'use strict';

module.exports.translate = function(version) {
  require('shelljs/global');
  var fs = require('fs');
  var path = require('path');
  var yaml = require('js-yaml');
  var async = require('async');
  var parallel = 2;

  if (!which('git')) {
    echo('This script requires git');
    exit(1);
  }

  var versions;
  if (!version) {
    var gitlabConfig = yaml.load(fs.readFileSync('config/gitlab.yml', 'utf8'));
    versions = Object.keys(gitlabConfig.versions);
  } else {
    versions = [version];
  }

  function getRandomArbitary(min, max) {
    //return Math.random() * (max - min) + min;
    return Math.floor( Math.random() * (max - min + 1) ) + min;
  }

  mkdir('-p', '.gitlabhq');
  var queue = [];
  var Server = function() {
    this.running = false;
  };
  Server.prototype.start = function() {
    if (!this.running) {
      this.running = true;
    }
    console.log('Starting.. ');
    process.nextTick(this.process.bind(this));
  };
  Server.prototype.request = function(cb) {
    queue.push(cb);
  };
  Server.prototype.process = function() {
    // If there are any requests for getting resource in the queue, check it
    if (!this.running) {
      return false;
    }
    if (queue.length > 0) {
      console.log(queue);
      var cb = queue.shift();
      console.log('Trying to get resource..');
      this.getResource(function(res) {
        async.nextTick(function() {
          async.waterfall([
            function(cb2) {
              console.log('Process request: ' + res);
              // Callback with resource
              cb(res);
              cb2();
            }
          ], function() {
            // Unlock the resource
            console.log('Unlock resource ' + res);
            fs.unlinkSync(path.join('.gitlabhq', '' + res, '.lock'));
          });
        });
        console.log('Register processing resource ' + res);
        //process.nextTick(this.process.bind(this));
      }.bind(this));
    //} else {
    //  process.nextTick(this.process.bind(this));
    }
    process.nextTick(this.process.bind(this));
  };
  Server.prototype.getResource = function(cb) {
    // Check .gitlabhq/1/.lock
    for (var i = 1; i <= parallel; i++) {
      //if (getRandomArbitary(1, 10) < 5) {
      if (!fs.existsSync(path.join('.gitlabhq', '' + i, '.lock'))) {
        // OK
        console.log('Found resource');

        var dir = path.join('.gitlabhq', '' + i);
        if (!fs.existsSync(dir)) {
          fs.mkdirSync(dir);
        }
        console.log('Lock resource ' + i);
        if (!fs.existsSync(path.join('.gitlabhq', '' + i, '.lock'))) {
          fs.writeFileSync(path.join('.gitlabhq', '' + i, '.lock'), '');
          process.nextTick(cb.bind(this, i));
        }
        //cb(i); //getRandomArbitary(1, 10)); // this should be resource number
        return;
      }
      //console.log('Unavailable: ' + i);
    }
    // NG, wait
    //console.log('Busy, wait..');
    process.nextTick(this.getResource.bind(this, cb));
  };
  Server.prototype.stop = function() {
    this.running = false;
    console.log('Stopping..');
  };
  var server = new Server();
  server.start();

  // Queue with the size `parallel`
  // push on initialization
  // poll on worker process is completed
  // Locked
  //   .gitlabhq/1/gitlabhq/app/..
  //   .gitlabhq/1/.lock
  // Unlocked
  //   .gitlabhq/2/gitlabhq/app/..

  //cd('gitlabhq');
  //exec('git fetch');
  //cd('..');

  async.parallelLimit(versions.map(function(v) {
    return function(cb) {
      console.log("Translate " + v);
      server.request(function(res) {
        console.log('Got resource: ' + res);
        cd('.gitlabhq/' + res);
        //if (!fs.existsSync(path.join('.gitlabhq', '' + res, 'gitlabhq'))) {
        if (!fs.existsSync('gitlabhq')) {
          exec('pwd && git clone https://github.com/gitlabhq/gitlabhq.git gitlabhq');
        }
        cd('gitlabhq');
        exec('git clean -d -f', {silent: true});
        exec('git checkout -f ' + v, {silent: true});
        cd('../../..');

        exec('i18n-patch --statistics --unmatched --condition version=' + v.replace(/v/, '') + ' -- ja .gitlabhq/' + res + '/gitlabhq 2> unmatched.log', {silent: true});
        mkdir('-p', 'patches/' + v);
        cd('.gitlabhq/' + res + '/gitlabhq');
        exec('git add .');
        exec('git diff --cached', {silent: true}).to('../../../patches/' + v + '/app_ja.patch');
        // Cleanup
        exec('git reset --hard HEAD', {silent: true});
        exec('git clean -d -f');
        cd('../../..');
        cb();
      });
    };
  }), parallel, function() {
    server.stop();
  });
//  for (var i = 0; i < versions.length; i++) {
//    var v = versions[i];
//    toBeProcessed.push(function() {
//      console.log("Translate " + v);
//      var id = seq;
//      // Lock
//      cd('.gitlabhq/' + id);
//      exec('git clean -d -f', {silent: true});
//      exec('git checkout -f ' + v, {silent: true});
//      cd('..');
//
//      exec('i18n-patch --statistics --unmatched --condition version=' + v.replace(/v/, '') + ' -- ja gitlabhq 2> unmatched.log');
//      mkdir('-p', 'patches/' + v);
//      cd('gitlabhq');
//      exec('git add .');
//      exec('git diff --cached', {silent: true}).to('../patches/' + v + '/app_ja.patch');
//      // Cleanup
//      exec('git reset --hard HEAD', {silent: true});
//      exec('git clean -d -f');
//      // Unlock
//      cd('..');
//    });
//  }
//  var toBeProcessed = [
//    function(cb) {
//      console.log('1');
//      server.request(function(res) {
//        console.log('1: Got resource: ' + res);
//        cb();
//      });
//    },
//    function(cb) {
//      console.log('2');
//      server.request(function(res) {
//        console.log('2: Got resource: ' + res);
//        cb();
//      });
//    },
//    function(cb) {
//      console.log('3');
//      server.request(function(res) {
//        console.log('3: Got resource: ' + res);
//        cb();
//      });
//    },
//  ];
//  async.parallelLimit(toBeProcessed, parallel, function() {
//    server.stop();
//  });
};
<commit_msg>forkを使用<commit_after>'use strict';

module.exports.translate = function(version) {
  require('shelljs/global');
  var fs = require('fs');
  var path = require('path');
  var yaml = require('js-yaml');
  var async = require('async');
  var numCPUs = require('os').cpus().length;
  var cluster = require('cluster');
  var parallel = 3;

  if (!which('git')) {
    echo('This script requires git');
    exit(1);
  }

  var queue = [];
  var versions;
  if (!version) {
    var gitlabConfig = yaml.load(fs.readFileSync('config/gitlab.yml', 'utf8'));
    versions = Object.keys(gitlabConfig.versions);
  } else {
    versions = [version];
  }

  if (cluster.isMaster) {
    mkdir('-p', '.gitlabhq');
    // Starting server
    var Server = function() {
      this.running = false;
    };
    Server.prototype.start = function() {
      if (!this.running) {
        this.running = true;
      }
      console.log('Starting.. ');
      process.nextTick(this.process.bind(this));
    };
    Server.prototype.request = function(cb) {
      queue.push(cb);
    };
    Server.prototype.process = function() {
      // If there are any requests for getting resource in the queue, check it
      if (!this.running) {
        return false;
      }
      if (queue.length > 0) {
        //console.log(queue);
        var cb = queue.shift();
        console.log('Trying to get resource..');
        this.getResource(function(res) {
          process.nextTick(function() {
            async.waterfall([
              function(cb2) {
                console.log('Process request: ' + res);
                // Callback with resource
                cb(res);
                cb2();
              }
            ], function() {
              // Unlock the resource
              console.log('Unlock resource: ' + res);
              fs.unlinkSync(path.join('.gitlabhq', '' + res, '.lock'));
            });
          });
          console.log('Register processing resource: ' + res);
          //process.nextTick(this.process.bind(this));
        }.bind(this));
      //} else {
      //  process.nextTick(this.process.bind(this));
      }
      process.nextTick(this.process.bind(this));
    };
    Server.prototype.getResource = function(cb) {
      // Check .gitlabhq/1/.lock
      for (var i = 1; i <= parallel; i++) {
        if (!fs.existsSync(path.join('.gitlabhq', '' + i, '.lock'))) {
          // OK
          //console.log('Found resource');

          var dir = path.join('.gitlabhq', '' + i);
          if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir);
          }
          console.log('Lock resource: ' + i);
          if (fs.existsSync(path.join('.gitlabhq', '' + i, '.lock'))) {
            console.log('Interrupted: ' + i);
          } else {
            fs.writeFileSync(path.join('.gitlabhq', '' + i, '.lock'), '');
            process.nextTick(cb.bind(this, i));
          }
          return;
        }
        //console.log('Unavailable: ' + i);
      }
      // NG, wait
      //console.log('Busy, wait..');
      process.nextTick(this.getResource.bind(this, cb));
    };
    Server.prototype.stop = function() {
      this.running = false;
      console.log('Stopping..');
    };
    var server = new Server();
    server.start();

    for (var i = 0; i < numCPUs; i++) {
      cluster.fork();
    }
    // When queue is empty then stop server and finish
  } else {
    // Just shift queue and process it, while the queue is not empty
    process.on('message', function(msg) {
    });
    async.parallelLimit(versions.map(function(v) {
      return function(cb) {
        console.log("Translate " + v);
        server.request(function(res) {
          console.log('Got resource: ' + res);
          //cd('.gitlabhq/' + res);
          ////if (!fs.existsSync(path.join('.gitlabhq', '' + res, 'gitlabhq'))) {
          //if (!fs.existsSync('gitlabhq')) {
          //  exec('pwd && git clone https://github.com/gitlabhq/gitlabhq.git gitlabhq');
          //}
          //cd('gitlabhq');
          //exec('git clean -d -f', {silent: true});
          //exec('git checkout -f ' + v, {silent: true});
          //cd('../../..');

          //exec('i18n-patch --statistics --unmatched --condition version=' + v.replace(/v/, '') + ' -- ja .gitlabhq/' + res + '/gitlabhq 2> unmatched.log', {silent: true});
          //mkdir('-p', 'patches/' + v);
          //cd('.gitlabhq/' + res + '/gitlabhq');
          //exec('git add .');
          //exec('git diff --cached', {silent: true}).to('../../../patches/' + v + '/app_ja.patch');
          //// Cleanup
          //exec('git reset --hard HEAD', {silent: true});
          //exec('git clean -d -f');
          //cd('../../..');
          cb();
        });
      };
    }), parallel, function() {
      server.stop();
    });
  }
};
<|endoftext|>


<commit_before>/*
Copyright © 2012, Anton Drachev <anton@drachev.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
    list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/** @see https://github.com/omgtehlion/jscollect */

var crypto = require("crypto");
var fs = require("fs");
var path = require("path");

/*=========================================================================*/

/**
 * @private
 *
 * This function mixes in unprocessed Buffers into Items array
 */
var makeParsed = function(items, content) {
    var result = [];
    var lastInd = 0;
    items.forEach(function(item) {
        if (lastInd > item.range[0])
            throw "makeParsed: unexpected index " + item.range[0];
        if (lastInd < item.range[0])
            result.push(new Buffer(content.substring(lastInd, item.range[0]), "utf-8"));
        result.push(item);
        lastInd = item.range[1] + 1;
    });
    if (lastInd < content.length)
        result.push(new Buffer(content.substring(lastInd), "utf-8"));
    return result;
}

/*=========================================================================*/

var jsFile = (function() {
    // js is parsed using a real parser:
    var esprima = require("esprima");

    function traverseTree(item, calls) {
        if (!item) {
            return;
        }
        switch (item.type) {
            case "AssignmentExpression":
                traverseTree(item.right, calls);
                break;
            case "CallExpression":
                if (item.callee.type === "Identifier" && item.callee.name === "include") {
                    var args = item.arguments;
                    if (args.length !== 1 && args[0].type !== "Literal")
                        throw args;
                    calls.push({ func: item.callee.name, arg: args[0].value, range: item.range });
                }
                break;
            case "ExpressionStatement":
                traverseTree(item.expression, calls);
                break;
            case "VariableDeclaration":
                item.declarations.forEach(function(node) {
                    traverseTree(node.init, calls);
                });
                break;
            case "ForStatement":
            case "WhileStatement":
            case "FunctionExpression":
            case "FunctionDeclaration":
                traverseTree(item.body, calls);
                break;
            case "IfStatement":
                traverseTree(item.consequent, calls);
                traverseTree(item.alternate, calls);
                break;
            case "SwitchStatement":
                item.cases.forEach(function(nodes) {
                    nodes.consequent.forEach(function(node) {
                        traverseTree(node, calls);
                    });
                });
                break;
            case "Program":
            case "BlockStatement":
                if (item.body) {
                    item.body.forEach(function(node) {
                        traverseTree(node, calls);
                    });
                }
                break;
        }
        return calls;
    }

    return function(content) {
        var parsed = esprima.parse(content, { range: true });
        var calls = traverseTree(parsed, []);
        return makeParsed(calls, content);
    };
})();

/*=========================================================================*/

var cssFile = (function() {
    // but css is parsed with regexes...
    var stringPat = "(?:(?:'[^'\\r\\n]*')|(?:\"[^\"\\r\\n]*\"))";
    var urlPat = "(?:(?:url\\(\\s*" + stringPat + "\\s*\\))|(?:url\\(\\s*[^\\s\\r\\n'\"]*\\s*\\)))";
    var commentPat = "(?:/\\*[^*]*\\*+(?:[^/][^*]*\\*+)*/)";
    var importPat = "(?:\\@import\\s+(" + urlPat + "|" + stringPat + ");?)";
    var allRx = new RegExp(commentPat + "|" + importPat + "|" + urlPat, "g");
    var urlRx = new RegExp("^" + urlPat + "$");

    function parseUrl(url) {
        if (url.lastIndexOf("url(", 0) === 0)
            url = url.replace(/^url\(\s*/, "").replace(/\s*\)$/, "");
        if (url.charAt(0) === "'" || url.charAt(0) === '"')
            url = url.substr(1, url.length - 2);
        // todo: handle escape and unicode http://www.w3.org/TR/css3-syntax/
        return url;
    }

    return function(content) {
        var found = [];
        var m;
        while (m = allRx.exec(content)) {
            if (m[0].lastIndexOf("/*", 0) === 0) {
                // skip comment
            } else if (m[0].charAt(0) === "@") {
                // @import
                var url = parseUrl(m[1]);
                found.push({ type: "import", url: url, range: [m.index, allRx.lastIndex - 1] });
            } else if (urlRx.test(m[0])) {
                // url(...)
                var url = parseUrl(m[0]);
                found.push({ type: "url", url: url, range: [m.index, allRx.lastIndex - 1] });
            } else {
                console.error({ match: m[0] });
            }
        }
        return makeParsed(found, content);
    };
})();

/*=========================================================================*/

var filetypes = { ".js": jsFile, ".css": cssFile };
var pathToMetadata = {};
var shaToContent = {};

exports.getParsed = function(filePath) {
    // checking in `pathToMetadata`
    var meta = pathToMetadata[filePath];
    var mTime = fs.statSync(filePath).mtime.getTime();
    var binContent;
    if (!meta || meta.mTime !== mTime) {
        var sha1sum = crypto.createHash("sha1");
        binContent = fs.readFileSync(filePath);
        sha1sum.update(binContent);
        meta = pathToMetadata[filePath] = { sha: sha1sum.digest("hex"), mTime: mTime };
        //console.log("meta " + JSON.stringify(meta));
        //watchDir(dir);
    }

    // checking in `shaToContent`
    var parsedFile = shaToContent[meta.sha];
    if (!parsedFile) {
        if (!binContent) {
            //throw "no binary content";
            binContent = fs.readFileSync(filePath);
        }
        var parser = filetypes[path.extname(filePath)];
        shaToContent[meta.sha] = parsedFile = parser(binContent.toString("utf-8"));
    }

    return parsedFile;
}

/*=========================================================================*/

//var watchers = {};

//function watchDir(dir) {
//    if (watchers[dir])
//        return;
//    console.error("watchDir: " + dir);
//    watchers[dir] = fs.watch(dir, function(event, filename) {
//        watcherCallback(event, path.resolve(dir, filename));
//    });
//}

//function watcherCallback(event, filename) {
//    delete pathToSha[filename];
//}

/*=========================================================================*/
<commit_msg>consistency fix<commit_after>/*
Copyright © 2012, Anton Drachev <anton@drachev.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
    list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/** @see https://github.com/omgtehlion/jscollect */

var crypto = require("crypto");
var fs = require("fs");
var path = require("path");

/*=========================================================================*/

/**
 * @private
 *
 * This function mixes in unprocessed Buffers into Items array
 */
var makeParsed = function(items, content) {
    var result = [];
    var lastInd = 0;
    items.forEach(function(item) {
        if (lastInd > item.range[0])
            throw "makeParsed: unexpected index " + item.range[0];
        if (lastInd < item.range[0])
            result.push(new Buffer(content.substring(lastInd, item.range[0]), "utf-8"));
        result.push(item);
        lastInd = item.range[1] + 1;
    });
    if (lastInd < content.length)
        result.push(new Buffer(content.substring(lastInd), "utf-8"));
    return result;
}

/*=========================================================================*/

var jsFile = (function() {
    // js is parsed using a real parser:
    var esprima = require("esprima");

    function traverseTree(item, calls) {
        if (!item) {
            return calls;
        }
        switch (item.type) {
            case "AssignmentExpression":
                traverseTree(item.right, calls);
                break;
            case "CallExpression":
                if (item.callee.type === "Identifier" && item.callee.name === "include") {
                    var args = item.arguments;
                    if (args.length !== 1 && args[0].type !== "Literal")
                        throw args;
                    calls.push({ func: item.callee.name, arg: args[0].value, range: item.range });
                }
                break;
            case "ExpressionStatement":
                traverseTree(item.expression, calls);
                break;
            case "VariableDeclaration":
                item.declarations.forEach(function(node) {
                    traverseTree(node.init, calls);
                });
                break;
            case "ForStatement":
            case "WhileStatement":
            case "FunctionExpression":
            case "FunctionDeclaration":
                traverseTree(item.body, calls);
                break;
            case "IfStatement":
                traverseTree(item.consequent, calls);
                traverseTree(item.alternate, calls);
                break;
            case "SwitchStatement":
                item.cases.forEach(function(nodes) {
                    nodes.consequent.forEach(function(node) {
                        traverseTree(node, calls);
                    });
                });
                break;
            case "Program":
            case "BlockStatement":
                if (item.body) {
                    item.body.forEach(function(node) {
                        traverseTree(node, calls);
                    });
                }
                break;
        }
        return calls;
    }

    return function(content) {
        var parsed = esprima.parse(content, { range: true });
        var calls = traverseTree(parsed, []);
        return makeParsed(calls, content);
    };
})();

/*=========================================================================*/

var cssFile = (function() {
    // but css is parsed with regexes...
    var stringPat = "(?:(?:'[^'\\r\\n]*')|(?:\"[^\"\\r\\n]*\"))";
    var urlPat = "(?:(?:url\\(\\s*" + stringPat + "\\s*\\))|(?:url\\(\\s*[^\\s\\r\\n'\"]*\\s*\\)))";
    var commentPat = "(?:/\\*[^*]*\\*+(?:[^/][^*]*\\*+)*/)";
    var importPat = "(?:\\@import\\s+(" + urlPat + "|" + stringPat + ");?)";
    var allRx = new RegExp(commentPat + "|" + importPat + "|" + urlPat, "g");
    var urlRx = new RegExp("^" + urlPat + "$");

    function parseUrl(url) {
        if (url.lastIndexOf("url(", 0) === 0)
            url = url.replace(/^url\(\s*/, "").replace(/\s*\)$/, "");
        if (url.charAt(0) === "'" || url.charAt(0) === '"')
            url = url.substr(1, url.length - 2);
        // todo: handle escape and unicode http://www.w3.org/TR/css3-syntax/
        return url;
    }

    return function(content) {
        var found = [];
        var m;
        while (m = allRx.exec(content)) {
            if (m[0].lastIndexOf("/*", 0) === 0) {
                // skip comment
            } else if (m[0].charAt(0) === "@") {
                // @import
                var url = parseUrl(m[1]);
                found.push({ type: "import", url: url, range: [m.index, allRx.lastIndex - 1] });
            } else if (urlRx.test(m[0])) {
                // url(...)
                var url = parseUrl(m[0]);
                found.push({ type: "url", url: url, range: [m.index, allRx.lastIndex - 1] });
            } else {
                console.error({ match: m[0] });
            }
        }
        return makeParsed(found, content);
    };
})();

/*=========================================================================*/

var filetypes = { ".js": jsFile, ".css": cssFile };
var pathToMetadata = {};
var shaToContent = {};

exports.getParsed = function(filePath) {
    // checking in `pathToMetadata`
    var meta = pathToMetadata[filePath];
    var mTime = fs.statSync(filePath).mtime.getTime();
    var binContent;
    if (!meta || meta.mTime !== mTime) {
        var sha1sum = crypto.createHash("sha1");
        binContent = fs.readFileSync(filePath);
        sha1sum.update(binContent);
        meta = pathToMetadata[filePath] = { sha: sha1sum.digest("hex"), mTime: mTime };
        //console.log("meta " + JSON.stringify(meta));
        //watchDir(dir);
    }

    // checking in `shaToContent`
    var parsedFile = shaToContent[meta.sha];
    if (!parsedFile) {
        if (!binContent) {
            //throw "no binary content";
            binContent = fs.readFileSync(filePath);
        }
        var parser = filetypes[path.extname(filePath)];
        shaToContent[meta.sha] = parsedFile = parser(binContent.toString("utf-8"));
    }

    return parsedFile;
}

/*=========================================================================*/

//var watchers = {};

//function watchDir(dir) {
//    if (watchers[dir])
//        return;
//    console.error("watchDir: " + dir);
//    watchers[dir] = fs.watch(dir, function(event, filename) {
//        watcherCallback(event, path.resolve(dir, filename));
//    });
//}

//function watcherCallback(event, filename) {
//    delete pathToSha[filename];
//}

/*=========================================================================*/
<|endoftext|>


<commit_before>// ManagerDash.js
import React, { Component } from 'react';
import { CardColumns } from 'reactstrap';
import CardDash from './children/CardDash';
import ManagerMenubar from './children/ManagerMenubar';
import './../../css/index.css'

class ManagerDashboard extends Component {
  render() {
    return (

        <ManagerMenubar />

Your Manager Dashboard

        <CardColumns>
          <CardDash source={require("./../../img/goat1.png")} title={"MyProfile"} descr={"Edit your profile"} linkto={"/managerprofile"}/>
          <CardDash source={require("./../../img/goat2.png")} title={"Schedule"} descr={"See Current Schedule"} linkto={"/managerschedule"}/>
          <CardDash source={require("./../../img/goat3.png")} title={"Shift Planner"} descr={"Add and Remove desired Shifts"} linkto={"/planner"}/>
        </CardColumns>

    );
  }
}

export default ManagerDashboard;<commit_msg>Update ManagerDash.js<commit_after>// ManagerDash.js
import React, { Component } from 'react';
import { CardColumns } from 'reactstrap';
import CardDash from './children/CardDash';
import ManagerMenubar from './children/ManagerMenubar';
import './../../css/index.css'

class ManagerDashboard extends Component {
  render() {
    return (

        <ManagerMenubar />

Your Manager Dashboard

        <CardColumns>
          <CardDash source={require("./../../img/goat1.png")} title={"MyProfile"} descr={"Edit your profile"} linkto={"/managerprofile"}/>
          <CardDash source={require("./../../img/goat2.png")} title={"Schedule"} descr={"See Current Schedule"} linkto={"/managerschedule"}/>
          <CardDash source={require("./../../img/goat3.png")} title={"Shift Planner"} descr={"Add and Remove desired Shifts"} linkto={"/managerplanner"}/>
        </CardColumns>

    );
  }
}

export default ManagerDashboard;
<|endoftext|>


<commit_before>$(document).ready(function () {
    $(".add-extension .Div1").each(function (e) {
        if (e != 0)
            $(this).hide();
        else
            $("#previous").hide();
    });

    $("#next").click(function () {
        if ($('#extension-select').parsley().isValid() == false) {
            $('#extension-select').parsley().validate();
            preventDefault();
            // e.stopPropagation();
        }
            if ($(".add-extension .Div1:visible").next().length != 0) {
                $(".add-extension .Div1:visible").next().show().prev().hide();
                $("#previous").show();
            }
            else {
                $(".add-extension .Div1:visible").hide();
                $(".add-extension .Div1:first").show();
            }
            return false;
    });

    $("#previous").click(function () {
        if ($(".add-extension .Div1:visible").prev().length != 0)
            $(".add-extension .Div1:visible").prev().show().next().hide();
        else {
            $(".add-extension .Div1:visible").hide();
            $(".add-extension .Div1:last").show();
        }
        return false;
    });

    $("#extension-select").change(function () {
        selected = $(this).val();
        if (selected === "-1") {
            $("#custom_due_date").show();
        }
        else {
            $("#custom_due_date").hide();
        }
    });

    $("#dtpick").datepicker({
        dateFormat: "yy-mm-dd"
    });

    $('#extension-select').attr('data-parsley-required', '');
    $('#extension-select').attr('data-parsley-required-message', 'Extension length must be selected');

});
<commit_msg>Added parsley validation to custom datepicker<commit_after>$(document).ready(function () {
    $(".add-extension .Div1").each(function (e) {
        if (e != 0)
            $(this).hide();
        else
            $("#previous").hide();
    });
    $("#add_extension").parsley().validate();

    $("#next").click(function () {
        if ($('#extension-select').parsley().isValid() == false){
            $('#extension-select').parsley().validate();
            preventDefault();
            // e.stopPropagation();
        }
        if ($('#dtpick').parsley().isValid() == false) {
            $('#dtpick').parsley().validate();
            preventDefault();
        }
            if ($(".add-extension .Div1:visible").next().length != 0) {
                $('#dtpick').parsley().reset();
                $(".add-extension .Div1:visible").next().show().prev().hide();
                $("#previous").show();
            }
            else {
                $(".add-extension .Div1:visible").hide();
                $(".add-extension .Div1:first").show();
            }
            return false;
    });

    $("#previous").click(function () {
        if ($(".add-extension .Div1:visible").prev().length != 0)
            $(".add-extension .Div1:visible").prev().show().next().hide();
        else {
            $(".add-extension .Div1:visible").hide();
            $(".add-extension .Div1:last").show();
        }
        return false;
    });

    $("#extension-select").change(function () {
        selected = $(this).val();
        if (selected === "-1") {
            $("#custom_due_date").show();
        }
        else {
            $("#custom_due_date").hide();
        }
    });

    $("#dtpick").datepicker({
        dateFormat: "yy-mm-dd"
    });

    $('#extension-select').attr('data-parsley-required', '');
    $('#dtpick').attr('data-parsley-required','');
    $('#dtpick').attr('data-parsley-required-message', 'Extension date must be chosen');
    $('#extension-select').attr('data-parsley-required-message', 'Extension length must be selected');

});
<|endoftext|>


<commit_before>/* Copyright 2013 Intelligent Technology Inc.
 *
 * 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
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var socketio = require('socket.io');
var dateformat = require('dateformat');

module.exports = sio;

function sio(server) {
	// Socket.IO
	var sio = socketio.listen(server);
	sio.set('transports', [ 'websocket' ]);

	// 接続時
	sio.sockets.on('connection', function(socket) {

		// 通知受信
		socket.on('notice', function(data) {
			// すべてのクライアントへ通知を送信
			// ブロードキャスト
			socket.broadcast.emit('recieve', {
				type : data.type,
				user : data.user,
				value : data.value,
				time : dateformat(new Date(), 'yyyy-mm-dd HH:MM:ss'),
			});
		});

		// 切断時
		socket.on("disconnect", function() {
		});
	});
}
<commit_msg>送信者にも送信できるようになる<commit_after>/* Copyright 2013 Intelligent Technology Inc.
 *
 * 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
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var socketio = require('socket.io');
var dateformat = require('dateformat');

module.exports = sio;

function sio(server) {
	// Socket.IO
	var sio = socketio.listen(server);
	sio.set('transports', [ 'websocket' ]);

	// 接続時
	sio.sockets.on('connection', function(socket) {

		// 通知受信
		socket.on('notice', function(data) {
			// すべてのクライアントへ通知を送信
			// ブロードキャスト
			socket.sockets.emit('recieve', {
				type : data.type,
				user : data.user,
				value : data.value,
				time : dateformat(new Date(), 'yyyy-mm-dd HH:MM:ss'),
			});
		});

		// 切断時
		socket.on("disconnect", function() {
		});
	});
}
<|endoftext|>


<commit_before>(function () {
    'use strict';

    angular
        .module('app')
        .controller('Techniques.TechniquesController', Controller);

    function Controller($window, $rootScope, $state, TechniqueService, FlashService, GradeService, UserService) {
        var vm = this;

        vm.removeWhiteSpace = removeWhiteSpace;
        vm.removeWhiteSpaceId = removeWhiteSpaceId;

        vm.filters = ['Grade', 'Techniques'];
        vm.filteredBy = vm.filters[0];
        vm.user = {};

        vm.techniques = []

        vm.techniqueSets = [];

        vm.sets = [];

        vm.availableGrades = [];
        vm.filterByType = filterByType;

        initController();

        function initController() {
            UserService.GetCurrent().then(function(user){
                vm.user = user;
                $rootScope.currentUser = user;
                vm.availableGrades = GradeService.GetAvaliableGrades(vm.user.grade.grade);
                vm.availableGrades.unshift({grade: "all", displayName: "All"});
                TechniqueService.GetAll().then(function (techniques){
                    vm.techniques =_.filter(techniques, function(technique){
                        if(GradeService.UserCanSeeAsset(technique.grade.grade, vm.user.grade.grade)){
                            if(technique.assetType === "video"){
                                return technique;
                            }
                        }
                    });
                    setTechniquesForDisplay();
                });
            });
        }

        function setTechniquesForDisplay(){
            vm.techniqueSets = _.groupBy(vm.techniques, function(technique){ return technique.techniqueSet });
            var techniqueSets = Object.getOwnPropertyNames(vm.techniqueSets);
            vm.sets = TechniqueService.SortTechniques(techniqueSets);
            sortSets();
            filterByType(vm.filteredBy);
        }

        function removeWhiteSpace(str){
            return str.replace(/\s+/g, '')+ '-id';

        }

        function removeWhiteSpaceId(str){
            return '#' + str.replace(/\s+/g, '') + '-id';

        }

        function filterByType(type){
            if(type === vm.filters[1]){
                //technique
                var gradeTechniques =_.filter(vm.techniques, function(technique){
                    if(GradeService.UserCanSeeAsset(technique.grade.grade, vm.user.grade.grade)){
                        return technique;
                    }
                });
                setTechniquesForDisplay();
            } else if(type === vm.filters[0]){
                //grade
                var gradeTechniques =_.filter(vm.techniques, function(technique){
                    if(GradeService.UserCanSeeAsset(technique.grade.grade, vm.user.grade.grade)){
                        return technique;
                    }
                });
                vm.techniqueSets = _.groupBy(gradeTechniques, function(technique){ return technique.grade.displayName });
                var grades = Object.getOwnPropertyNames(vm.techniqueSets);
                vm.sets = GradeService.SortGrades(grades);
                sortAlphabetically();
            }

        }

        function sortAlphabetically(){
            _.each(vm.techniqueSets, function(sets){
                sets.sort(function(a, b) {
                    if (a.techniqueName < b.techniqueName) return -1;
                    if (a.techniqueName > b.techniqueName) return 1;
                    return 0;
                });
            });
        }

        function sortSets(){
            _.each(vm.techniqueSets, function(sets){
                var lastIndexOfA = sets[0].techniqueName.lastIndexOf(" ");
                var aString = sets[0].techniqueName.substring(lastIndexOfA, sets[0].techniqueName.length);
                var aInt = parseInt(aString);
                if(isNaN(aInt)){
                    GradeService.SortTechniquesByGrades(sets);
                } else {
                    sets.sort(function(a, b){
                        var lastIndexOfA = a.techniqueName.lastIndexOf(" ");
                        var aString = a.techniqueName.substring(lastIndexOfA, a.techniqueName.length);
                        var aInt = parseInt(aString);

                        var lastIndexOfB = b.techniqueName.lastIndexOf(" ");
                        var bString = b.techniqueName.substring(lastIndexOfB, b.techniqueName.length);
                        var bInt = parseInt(bString);

                        return aInt - bInt;
                    });
                }

            });
        }

    }

})();<commit_msg>removed asset type requirements<commit_after>(function () {
    'use strict';

    angular
        .module('app')
        .controller('Techniques.TechniquesController', Controller);

    function Controller($window, $rootScope, $state, TechniqueService, FlashService, GradeService, UserService) {
        var vm = this;

        vm.removeWhiteSpace = removeWhiteSpace;
        vm.removeWhiteSpaceId = removeWhiteSpaceId;

        vm.filters = ['Grade', 'Techniques'];
        vm.filteredBy = vm.filters[0];
        vm.user = {};

        vm.techniques = []

        vm.techniqueSets = [];

        vm.sets = [];

        vm.availableGrades = [];
        vm.filterByType = filterByType;

        initController();

        function initController() {
            UserService.GetCurrent().then(function(user){
                vm.user = user;
                $rootScope.currentUser = user;
                vm.availableGrades = GradeService.GetAvaliableGrades(vm.user.grade.grade);
                vm.availableGrades.unshift({grade: "all", displayName: "All"});
                TechniqueService.GetAll().then(function (techniques){
                    vm.techniques =_.filter(techniques, function(technique){
                        if(GradeService.UserCanSeeAsset(technique.grade.grade, vm.user.grade.grade)){
                            return technique;
                        }
                    });
                    setTechniquesForDisplay();
                });
            });
        }

        function setTechniquesForDisplay(){
            vm.techniqueSets = _.groupBy(vm.techniques, function(technique){ return technique.techniqueSet });
            var techniqueSets = Object.getOwnPropertyNames(vm.techniqueSets);
            vm.sets = TechniqueService.SortTechniques(techniqueSets);
            sortSets();
            filterByType(vm.filteredBy);
        }

        function removeWhiteSpace(str){
            return str.replace(/\s+/g, '')+ '-id';

        }

        function removeWhiteSpaceId(str){
            return '#' + str.replace(/\s+/g, '') + '-id';

        }

        function filterByType(type){
            if(type === vm.filters[1]){
                //technique
                var gradeTechniques =_.filter(vm.techniques, function(technique){
                    if(GradeService.UserCanSeeAsset(technique.grade.grade, vm.user.grade.grade)){
                        return technique;
                    }
                });
                setTechniquesForDisplay();
            } else if(type === vm.filters[0]){
                //grade
                var gradeTechniques =_.filter(vm.techniques, function(technique){
                    if(GradeService.UserCanSeeAsset(technique.grade.grade, vm.user.grade.grade)){
                        return technique;
                    }
                });
                vm.techniqueSets = _.groupBy(gradeTechniques, function(technique){ return technique.grade.displayName });
                var grades = Object.getOwnPropertyNames(vm.techniqueSets);
                vm.sets = GradeService.SortGrades(grades);
                sortAlphabetically();
            }

        }

        function sortAlphabetically(){
            _.each(vm.techniqueSets, function(sets){
                sets.sort(function(a, b) {
                    if (a.techniqueName < b.techniqueName) return -1;
                    if (a.techniqueName > b.techniqueName) return 1;
                    return 0;
                });
            });
        }

        function sortSets(){
            _.each(vm.techniqueSets, function(sets){
                var lastIndexOfA = sets[0].techniqueName.lastIndexOf(" ");
                var aString = sets[0].techniqueName.substring(lastIndexOfA, sets[0].techniqueName.length);
                var aInt = parseInt(aString);
                if(isNaN(aInt)){
                    GradeService.SortTechniquesByGrades(sets);
                } else {
                    sets.sort(function(a, b){
                        var lastIndexOfA = a.techniqueName.lastIndexOf(" ");
                        var aString = a.techniqueName.substring(lastIndexOfA, a.techniqueName.length);
                        var aInt = parseInt(aString);

                        var lastIndexOfB = b.techniqueName.lastIndexOf(" ");
                        var bString = b.techniqueName.substring(lastIndexOfB, b.techniqueName.length);
                        var bInt = parseInt(bString);

                        return aInt - bInt;
                    });
                }

            });
        }

    }

})();<|endoftext|>