<commit_before>$ext = {
  /*
   * Identity function.
   */
  id: function(obj) {
    return obj;
  },

  BREAK: {
    $break: 'break'
  },
  CONTINUE: {
    $continue: 'continue'
  },

  /*
   * Apply a function f to each element in an Object, as long as that function
   * does not return anything.
   *
   * The parameter scope will be provided to the function and can be used for
   * 'this' scoping.
   */
  each: function(obj, f, scope) {
    if(obj instanceof Array) {
      for( var i = 0; i < obj.length; i++) {
        var r = f.call(scope, obj[i], i);
        if(r === this.CONTINUE) {
          continue;
        } else if(r === this.BREAK) {
          break;
        } else if(r !== undefined) {
          return r;
        }
      }
    } else if(obj instanceof Object) {
      for( var k in obj) {
        if(Object.prototype[k] !== undefined) {
          continue;
        }

        var r = f.call(scope, obj[k], k);
        if(r === this.CONTINUE) {
          continue;
        } else if(r === this.BREAK) {
          break;
        } else if(r !== undefined) {
          return r;
        }
      }
    }
  },

  /*
   * Extend an object with a given extension.
   */
  extend: function(orig, extension) {
    if(orig instanceof Array) {
      return orig.concat(extension);
    } else if(orig instanceof Object) {
      this.each(extension, function(v, k) {
        if(v !== undefined) {
          orig[k] = v;
        }
      }, this);
      return orig;
    }
  },

  /*
   * Create a copy of an object.
   */
  copy: function(obj) {
    if(obj instanceof Array) {
      return this.extend([], obj);
    } else if(obj instanceof Object) {
      return this.extend({}, obj);
    }
  },

  /*
   * Create a deep copy of an object.
   */
  deepCopy: function(obj) {
    if(obj === null || typeof obj !== "object") {
      return obj;
    }

    if(obj instanceof Array) {
      var r = new Array();
      this.each(obj, function(v, i) {
        r[i] = this.deepCopy(v);
      }, this);
      return r;
    } else if(obj instanceof Object) {
      var r = new Object();
      this.each(obj, function(v, k) {
        if(obj.hasOwnProperty(k)) {
          r[k] = this.deepCopy(v);
        }
      }, this);
      return r;
    }
  },

  /*
   * Merge two objects, either destructive (modify the current object) or
   * nondestructive (return a new object that is the merge result).
   */
  merge: function(orig, extension, nondestructive) {
    if(nondestructive) {
      var r = this.copy(orig);
    } else {
      var r = orig;
    }

    if(orig instanceof Array) {
      this.each(extension, function(v) {
        if(v !== undefined && r.indexOf(v) === -1) {
          r.push(v);
        }
      });
      return r;
    } else if(orig instanceof Object) {
      this.each(extension, function(v, k) {
        if(typeof r[k] === 'object' && typeof v === 'object') {
          this.merge(r[k], v);
        } else {
          r[k] = v;
        }
      }, this);
      return r;
    }
  },

  /*
   * Determine whether the user is using a broken IE browser (i.e. IE <= 8).
   */
  onBrokenIE: function() {
    return BrowserDetect.browser === "Explorer" && BrowserDetect.version < 9;
  },

  /*
   * Determine if the user is using Firefox.
   *
   * Used to fix MouseEvent button problems.
   */
  onFirefox: function() {
    return BrowserDetect.browser === "Firefox";
  }
};<commit_msg>Fixed object instanceof for old IE browsers.<commit_after>$ext = {
  /*
   * Identity function.
   */
  id: function(obj) {
    return obj;
  },

  BREAK: {
    $break: 'break'
  },
  CONTINUE: {
    $continue: 'continue'
  },

  /*
   * Apply a function f to each element in an Object, as long as that function
   * does not return anything.
   *
   * The parameter scope will be provided to the function and can be used for
   * 'this' scoping.
   */
  each: function(obj, f, scope) {
    if(obj instanceof Array) {
      for( var i = 0; i < obj.length; i++) {
        var r = f.call(scope, obj[i], i);
        if(r === this.CONTINUE) {
          continue;
        } else if(r === this.BREAK) {
          break;
        } else if(r !== undefined) {
          return r;
        }
      }
    } else if(obj instanceof Object || typeof obj === "object") {
      for( var k in obj) {
        if(Object.prototype[k] !== undefined) {
          continue;
        }

        var r = f.call(scope, obj[k], k);
        if(r === this.CONTINUE) {
          continue;
        } else if(r === this.BREAK) {
          break;
        } else if(r !== undefined) {
          return r;
        }
      }
    }
  },

  /*
   * Extend an object with a given extension.
   */
  extend: function(orig, extension) {
    if(orig instanceof Array) {
      return orig.concat(extension);
    } else if(orig instanceof Object || typeof orig === "object") {
      this.each(extension, function(v, k) {
        if(v !== undefined) {
          orig[k] = v;
        }
      }, this);
      return orig;
    }
  },

  /*
   * Create a copy of an object.
   */
  copy: function(obj) {
    if(obj instanceof Array) {
      return this.extend([], obj);
    } else if(obj instanceof Object || typeof obj === "object") {
      return this.extend({}, obj);
    }
  },

  /*
   * Create a deep copy of an object.
   */
  deepCopy: function(obj) {
    if(obj === null || typeof obj !== "object") {
      return obj;
    }

    if(obj instanceof Array) {
      var r = new Array();
      this.each(obj, function(v, i) {
        r[i] = this.deepCopy(v);
      }, this);
      return r;
    } else if(obj instanceof Object || typeof obj === "object") {
      var r = new Object();
      this.each(obj, function(v, k) {
        if(obj.hasOwnProperty(k)) {
          r[k] = this.deepCopy(v);
        }
      }, this);
      return r;
    }
  },

  /*
   * Merge two objects, either destructive (modify the current object) or
   * nondestructive (return a new object that is the merge result).
   */
  merge: function(orig, extension, nondestructive) {
    if(nondestructive) {
      var r = this.copy(orig);
    } else {
      var r = orig;
    }

    if(orig instanceof Array) {
      this.each(extension, function(v) {
        if(v !== undefined && r.indexOf(v) === -1) {
          r.push(v);
        }
      });
      return r;
    } else if(orig instanceof Object || typeof orig === "object") {
      this.each(extension, function(v, k) {
        if(typeof r[k] === 'object' && typeof v === 'object') {
          this.merge(r[k], v);
        } else {
          r[k] = v;
        }
      }, this);
      return r;
    }
  },

  /*
   * Determine whether the user is using a broken IE browser (i.e. IE <= 8).
   */
  onBrokenIE: function() {
    return BrowserDetect.browser === "Explorer" && BrowserDetect.version < 9;
  },

  /*
   * Determine if the user is using Firefox.
   *
   * Used to fix MouseEvent button problems.
   */
  onFirefox: function() {
    return BrowserDetect.browser === "Firefox";
  }
};<|endoftext|>


<commit_before>/**
 * @flow
 */

var StoreFacade = require('./StoreFacade.js');

var invariant = require('../invariant.js');

var HINT_LINK =
  'Learn more about defining fields with the StoreDependencyMixin:' +
  ' https://github.com/HubSpot/general-store#react';

type derefingFunction = (
  props: Object,
  state: Object,
  stores: Array<StoreFacade>
) => any;

type CompoundStoreDependency = {
  stores: Array<StoreFacade>;
  deref: derefingFunction;
};

type StoreDependencies = {
  [key:string]: StoreFacade | CompoundStoreDependency;
};

function defaultDeref(
  _,
  _,
  stores: Array<StoreFacade>
): any {
  return stores[0].get();
}

function extractDeref(
  dependencies: StoreDependencies,
  field: string
): derefingFunction {
  var dependency = dependencies[field];
  if (dependency instanceof StoreFacade) {
    return defaultDeref;
  }
  invariant(
    typeof dependency.deref === 'function',
    'StoreDependencyDefinition: the compound field "%s" does not have' +
    ' a `deref` function. Provide one, or make it a simple field instead. %s',
    field,
    HINT_LINK
  );
  return dependency.deref;
}

function extractStores(
  dependencies: StoreDependencies,
  field: string
): Array<StoreFacade> {
  var dependency = dependencies[field];
  if (dependency instanceof StoreFacade) {
    return [dependency];
  }
  invariant(
    Array.isArray(dependency.stores) && dependency.stores.length,
    'StoreDependencyDefinition: the `stores` property on the compound field' +
    ' "%s" must be an array of Stores with at least one Store. %s',
    HINT_LINK
  );
  return dependency.stores;
}

class StoreDependencyDefinition {

  _derefs: {[key:string]: derefingFunction};
  _stores: {[key:string]: Array<StoreFacade>};

  constructor(dependencyMap: StoreDependencies) {
    this._derefs = {};
    this._stores = {};
    var dependency;
    for (var field in dependencyMap) {
      dependency = dependencyMap[field];
      this._derefs[field] = extractDeref(dependencyMap, field);
      this._stores[field] = extractStores(dependencyMap, field);
    }
  }

  _derefStore(
    field: string,
    props: Object,
    state: Object
  ): any {
    return this._derefs[field](
      props,
      state,
      this._stores[field]
    );
  }

  getState(
    props: Object,
    state: Object
  ): Object {
    var updates = {};
    for(var field in this._stores) {
      updates[field] = this._derefStore(field, props, state);
    }
    return updates;
  }

  getStateField(
    field: string,
    props: Object,
    state: Object
  ): Object {
    var update = {};
    update[field] = this._derefStore(field, props, state);
    return update;
  }

  getStores(): {[key:string]: Array<StoreFacade>} {
    return this._stores;
  }

};

module.exports = StoreDependencyDefinition;
<commit_msg>missing arg in an invariant<commit_after>/**
 * @flow
 */

var StoreFacade = require('./StoreFacade.js');

var invariant = require('../invariant.js');

var HINT_LINK =
  'Learn more about defining fields with the StoreDependencyMixin:' +
  ' https://github.com/HubSpot/general-store#react';

type derefingFunction = (
  props: Object,
  state: Object,
  stores: Array<StoreFacade>
) => any;

type CompoundStoreDependency = {
  stores: Array<StoreFacade>;
  deref: derefingFunction;
};

type StoreDependencies = {
  [key:string]: StoreFacade | CompoundStoreDependency;
};

function defaultDeref(
  _,
  _,
  stores: Array<StoreFacade>
): any {
  return stores[0].get();
}

function extractDeref(
  dependencies: StoreDependencies,
  field: string
): derefingFunction {
  var dependency = dependencies[field];
  if (dependency instanceof StoreFacade) {
    return defaultDeref;
  }
  invariant(
    typeof dependency.deref === 'function',
    'StoreDependencyDefinition: the compound field "%s" does not have' +
    ' a `deref` function. Provide one, or make it a simple field instead. %s',
    field,
    HINT_LINK
  );
  return dependency.deref;
}

function extractStores(
  dependencies: StoreDependencies,
  field: string
): Array<StoreFacade> {
  var dependency = dependencies[field];
  if (dependency instanceof StoreFacade) {
    return [dependency];
  }
  invariant(
    Array.isArray(dependency.stores) && dependency.stores.length,
    'StoreDependencyDefinition: the `stores` property on the compound field' +
    ' "%s" must be an array of Stores with at least one Store. %s',
    field,
    HINT_LINK
  );
  return dependency.stores;
}

class StoreDependencyDefinition {

  _derefs: {[key:string]: derefingFunction};
  _stores: {[key:string]: Array<StoreFacade>};

  constructor(dependencyMap: StoreDependencies) {
    this._derefs = {};
    this._stores = {};
    var dependency;
    for (var field in dependencyMap) {
      dependency = dependencyMap[field];
      this._derefs[field] = extractDeref(dependencyMap, field);
      this._stores[field] = extractStores(dependencyMap, field);
    }
  }

  _derefStore(
    field: string,
    props: Object,
    state: Object
  ): any {
    return this._derefs[field](
      props,
      state,
      this._stores[field]
    );
  }

  getState(
    props: Object,
    state: Object
  ): Object {
    var updates = {};
    for(var field in this._stores) {
      updates[field] = this._derefStore(field, props, state);
    }
    return updates;
  }

  getStateField(
    field: string,
    props: Object,
    state: Object
  ): Object {
    var update = {};
    update[field] = this._derefStore(field, props, state);
    return update;
  }

  getStores(): {[key:string]: Array<StoreFacade>} {
    return this._stores;
  }

};

module.exports = StoreDependencyDefinition;
<|endoftext|>


<commit_before>var git = require('../'),
    rimraf = require('rimraf'),
    fs = require('fs');

var sha = '5716e9757886eaf38d51c86b192258c960d9cfea';
var fileCount = 513;

exports.walk = function(test) {
  test.expect(516);

  git.repo('../.git', function(error, repo) {
      repo.commit(sha, function(error, commit) {
        var entryCount = 0;
        commit.tree(function(error, tree) {
          tree.walk().on('entry', function(error, index, entry) {
              test.equals(error, null, 'There should be no error');
              entryCount++;
          }).on('end', function(error, entries) {
            test.equals(error, null, 'There should be no error');
            test.equals(entryCount, fileCount, 'The manual tree entry count and the "end" tree entry count do not match');
            test.equals(entries.length, fileCount, 'The end entries count and the manual entry count do not match');
            test.done();
          });
        });
      });
   });
};
<commit_msg>Updated convenience-tree test<commit_after>var git = require('../'),
    rimraf = require('rimraf'),
    fs = require('fs');

var sha = '5716e9757886eaf38d51c86b192258c960d9cfea';
var fileCount = 512; // Number of blob & blob executabless

exports.walk = function(test) {
  test.expect(516);

  git.repo('../.git', function(error, repo) {
    repo.commit(sha, function(error, commit) {
      var entryCount = 0;
      commit.tree(function(error, tree) {
        tree.walk().on('entry', function(error, index, entry) {
            test.equals(error, null, 'There should be no error');
            entryCount++;
        }).on('end', function(error, entries) {
          test.equals(error, null, 'There should be no error');
          test.equals(entryCount, fileCount, 'The manual tree entry count and the "end" tree entry count do not match');
          test.equals(entries.length, fileCount, 'The end entries count and the manual entry count do not match');
          test.done();
        });
      });
    });
  });
};
<|endoftext|>


<commit_before>/*##################################################|*/
/* #CMS# */

// ensuring django namespace is set correctly
var django = window.django || undefined;

// ensuring jQuery namespace is set correctly
var jQuery = (django) ? django.jQuery : window.jQuery || undefined;

// ensuring Class namespace is set correctly
var Class = window.Class || undefined;

// ensuring CMS namespace is set correctly
var CMS = {
	'$': (jQuery) ? jQuery.noConflict() : undefined,
	'Class': (Class) ? Class.noConflict() : undefined,
	'API': {}
};

/*##################################################|*/
/* #CMS.API# */
(function($) {
// CMS.$ will be passed for $
$(document).ready(function () {
	/*!
	 * CNS.API.Helpers
	 * @version: 1.0.0
	 * @public_methods:
	 *	- CMS.API.Helpers.reloadBrowser();
	 */
	CMS.API.Helpers = {

		// redirects to a specific url or reloads browser
		reloadBrowser: function (url, timeout) {
			// is there a parent window?
			parent = (window.parent) ? window.parent : window;
			// add timeout if provided
			parent.setTimeout(function () {
				(url) ? parent.location.href = url : parent.location.reload();
			}, timeout || 0);
		},

		// disable multiple form submissions
		preventSubmit: function () {
			$('form').submit(function () {
				// we cannot use disabled as the name action will be ignored
				$('input[type="submit"]').bind('click', function (e) {
					e.preventDefault();
				}).css('opacity', 0.5);
			});
		},

		// fixes csrf behaviour
		csrf: function (csrf_token) {
			$.ajaxSetup({
				beforeSend: function (xhr) {
					// set csrf_token
					xhr.setRequestHeader("X-CSRFToken", csrf_token);
				}
			});
		}

	};

	// autoinits
	CMS.API.Helpers.preventSubmit();

});
})(CMS.$);<commit_msg>restrict form submit prevent to cms_toolbar namespace<commit_after>/*##################################################|*/
/* #CMS# */

// ensuring django namespace is set correctly
var django = window.django || undefined;

// ensuring jQuery namespace is set correctly
var jQuery = (django) ? django.jQuery : window.jQuery || undefined;

// ensuring Class namespace is set correctly
var Class = window.Class || undefined;

// ensuring CMS namespace is set correctly
var CMS = {
	'$': (jQuery) ? jQuery.noConflict() : undefined,
	'Class': (Class) ? Class.noConflict() : undefined,
	'API': {}
};

/*##################################################|*/
/* #CMS.API# */
(function($) {
// CMS.$ will be passed for $
$(document).ready(function () {
	/*!
	 * CNS.API.Helpers
	 * @version: 1.0.0
	 * @public_methods:
	 *	- CMS.API.Helpers.reloadBrowser();
	 */
	CMS.API.Helpers = {

		// redirects to a specific url or reloads browser
		reloadBrowser: function (url, timeout) {
			// is there a parent window?
			parent = (window.parent) ? window.parent : window;
			// add timeout if provided
			parent.setTimeout(function () {
				(url) ? parent.location.href = url : parent.location.reload();
			}, timeout || 0);
		},

		// disable multiple form submissions
		preventSubmit: function () {
			$('#cms_toolbar form').submit(function () {
				// we cannot use disabled as the name action will be ignored
				$('input[type="submit"]').bind('click', function (e) {
					e.preventDefault();
				}).css('opacity', 0.5);
			});
		},

		// fixes csrf behaviour
		csrf: function (csrf_token) {
			$.ajaxSetup({
				beforeSend: function (xhr) {
					// set csrf_token
					xhr.setRequestHeader("X-CSRFToken", csrf_token);
				}
			});
		}

	};

	// autoinits
	CMS.API.Helpers.preventSubmit();

});
})(CMS.$);<|endoftext|>


<commit_before>document.write('<script type="text/javascript" charset="utf-8" src="../../phonegap-1.3.0.js"></script>');
document.write('<script type="text/javascript" charset="utf-8" src="../phonegap-1.3.0.js"></script>');
document.write('<script type="text/javascript" charset="utf-8" src="phonegap-1.3.0.js"></script>');

function backHome() {
	if (device.platform.toLowerCase() == 'android') {
            navigator.app.backHistory();
	}
	else {
	    document.location = "../index.html";
	}
}
<commit_msg>update test harness to run against cordova 1.6.0<commit_after>document.write('<script type="text/javascript" charset="utf-8" src="../../cordova-1.6.0.js"></script>');
document.write('<script type="text/javascript" charset="utf-8" src="../cordova-1.6.0.js"></script>');
document.write('<script type="text/javascript" charset="utf-8" src="cordova-1.6.0.js"></script>');

function backHome() {
	if (device.platform.toLowerCase() == 'android') {
            navigator.app.backHistory();
	}
	else {
	    document.location = "../index.html";
	}
}
<|endoftext|>


<commit_before>var fs = require('fs');
var log = require('../../log').logger('gcode');
var config = require('../../config');
var countLineNumbers = require('../../util').countLineNumbers

function GCodeRuntime() {
	this.machine = null;
	this.driver = null;
	this.ok_to_disconnect = true;
	this.completeCallback = null;
    this.inFeedHold = false;
    this._file_or_stream_in_progress = false;
}

GCodeRuntime.prototype.toString = function() {
	return "[GCodeRuntime]";
}
//Check if move requires auth
GCodeRuntime.prototype.needsAuth = function(s) {
	//all needs auth (check) so just return true
	return true;
}
GCodeRuntime.prototype.connect = function(machine) {
	this.machine = machine;
	this.driver = machine.driver;
	this.status_handler =  this._onDriverStatus.bind(this);
	this.status_report = {};
	this.driver.on('status',this.status_handler);
	log.info("Connected G-Code Runtime");
};

GCodeRuntime.prototype.disconnect = function() {
	if(this.ok_to_disconnect) {
		this.driver.removeListener('status', this.status_handler);
		log.info("Disconnected G-Code Runtime");
	} else {
		throw new Error("Cannot disconnect GCode Runtime")
	}
};

GCodeRuntime.prototype.pause = function() {
	this.driver.feedHold();
    this.inFeedHold = true;
}

GCodeRuntime.prototype.quit = function() {
	this.driver.quit();
}

GCodeRuntime.prototype.resume = function() {
	this.driver.resume();
    this.inFeedHold = false;
}

GCodeRuntime.prototype._changeState = function(newstate) {
	log.debug("Changing state to " + newstate)
	if(newstate != "idle") {
		this.ok_to_disconnect = false;
	}
	this.machine.setState(this, newstate);
};

GCodeRuntime.prototype._limit = function() {
	var er = this.driver.getLastException();
	if(er && er.st == 203) {
		var msg = er.msg.replace(/\[[^\[\]]*\]/,'');
		this.driver.clearLastException();
		this._fail(msg);
		return true;
	}
	return false;
}

GCodeRuntime.prototype._onDriverStatus = function(status) {
	// Update the machine copy of g2 status variables
	for (var key in this.machine.status) {
		if(key in status) {
			this.machine.status[key] = status[key];
		}
	}
	// Update the machine copy of g2 status variables
	for (key in status) {
		this.status_report[key] = status[key];
	}

	this.machine.emit('status',this.machine.status);
};

GCodeRuntime.prototype._die = function() {
	this.machine.status.current_file = null;
	this.machine.status.line=null;
	this.machine.status.nb_lines=null;
 	try {
 		this.machine.status.job.fail();
 	} catch(e) {}
 	finally {
		this.machine.status.job=null;
 		this.machine.setState(this, 'dead', {error : 'A G2 exception has occurred. You must reboot your tool.'});
 	}
}

GCodeRuntime.prototype._fail = function(message) {
	this.machine.status.current_file = null;
	this.machine.status.line=null;
	this.machine.status.nb_lines=null;
 	try {
 		this.machine.status.job.fail();
 	} catch(e) {}
 	finally {
		this.machine.status.job=null;
 		this.machine.setState(this, 'stopped', {error : message});
 	}
}

GCodeRuntime.prototype._idle = function() {
	this.machine.status.current_file = null;
	this.machine.status.line=null;
	this.machine.status.nb_lines=null;
	var job = this.machine.status.job;
	// Set the machine state to idle and return the units to their default configuration
	var finishUp = function() {
		this.driver.setUnits(config.machine.get('units'), function() {
			var callback = this.completeCallback || function() {};
			this.ok_to_disconnect = true;
			this.completeCallback = null;
			this.machine.setState(this, 'idle');
			callback();
		}.bind(this))
	}.bind(this);

	if(job) {
		if(job.pending_cancel) {
			this.machine.status.job.cancel(function(err, job) {
				this.machine.status.job=null;
				finishUp();
			}.bind(this));
		} else {
			this.machine.status.job.finish(function(err, job) {
				this.machine.status.job=null;
				finishUp();
			}.bind(this));
		}
	} else {
		finishUp();
	}
};

// Run the provided string
// callback runs only when execution is complete.
GCodeRuntime.prototype.runString = function(string, callback) {
	if(callback) { log.error("CALLBACK PASSED TO RUNSTRING")}

	if(this.machine.status.state === 'idle' || this.machine.status.state === 'armed') {
		var lines =  string.split('\n');
		var mode = config.driver.get('gdi') ? 'G91': 'G90';
		this.machine.status.nb_lines = lines.length;
		for (i=0;i<lines.length;i++){
			if (lines[i][0]!==undefined && lines[i][0].toUpperCase() !== 'N' ){
				lines[i]= 'N'+ (i+1) + lines[i];
			}
		}
		lines.unshift(mode);
		this.completeCallback = callback;
		this._changeState("running");
		return this.driver.runList(lines)
		.on('stat', this._handleStateChange.bind(this))
		.then(this._handleStop.bind(this));
	}
};

GCodeRuntime.prototype._handleStop = function() {
	this._idle();
}

GCodeRuntime.prototype._handleStateChange = function(stat) {
	switch(stat) {
		case this.driver.STAT_HOLDING:
			this._changeState('paused');
			break;
		case this.driver.STAT_RUNNING:
			this._changeState('running');
			break;
        case this.driver.STAT_STOP:
            // This that the g2core is in stat:3, meaning it has processed all available gcode
            // so we need to tell it to move to stat:4 by sending an end of job "M30"
            // There may have been an M30 in the file but the g2core will have ignored it, this
            // may change someday in the future on the g2core end, so we may end up revisiting this.
            // OTOH, an extra M30 should not cause a problem.
            if (this._file_or_stream_in_progress) {
                this.driver.sendM30();
                this._file_or_stream_in_progress = false;
            }

		default:
			break;
	}
}

// Run a file given the filename
GCodeRuntime.prototype.runFile = function(filename, callback) {
        this._file_or_stream_in_progress = true;
	countLineNumbers(filename, function(err, lines) {
		this.machine.status.nb_lines = lines;
		this.driver.runFile(filename, callback)
			.on('stat', this._handleStateChange.bind(this))
			.then(this._handleStop.bind(this));
	}.bind(this));
}

// Run the given string as gcode
GCodeRuntime.prototype.executeCode = function(string, callback) {
	this._file_or_stream_in_progress = true;
	return this.runString(string);
}

exports.GCodeRuntime = GCodeRuntime;<commit_msg>refs #49787 move file and string handling into gcode runtime.<commit_after>var fs = require('fs');
var log = require('../../log').logger('gcode');
var config = require('../../config');
var countLineNumbers = require('../../util').countLineNumbers
var LineNumberer = require('./util').LineNumberer

function GCodeRuntime() {
	this.machine = null;
	this.driver = null;
	this.ok_to_disconnect = true;
	this.completeCallback = null;
    this.inFeedHold = false;
    this._file_or_stream_in_progress = false;
}

GCodeRuntime.prototype.toString = function() {
	return "[GCodeRuntime]";
}
//Check if move requires auth
GCodeRuntime.prototype.needsAuth = function(s) {
	//all needs auth (check) so just return true
	return true;
}
GCodeRuntime.prototype.connect = function(machine) {
	this.machine = machine;
	this.driver = machine.driver;
	this.status_handler =  this._onDriverStatus.bind(this);
	this.status_report = {};
	this.driver.on('status',this.status_handler);
	log.info("Connected G-Code Runtime");
};

GCodeRuntime.prototype.disconnect = function() {
	if(this.ok_to_disconnect) {
		this.driver.removeListener('status', this.status_handler);
		log.info("Disconnected G-Code Runtime");
	} else {
		throw new Error("Cannot disconnect GCode Runtime")
	}
};

GCodeRuntime.prototype.pause = function() {
	this.driver.feedHold();
    this.inFeedHold = true;
}

GCodeRuntime.prototype.quit = function() {
	this.driver.quit();
}

GCodeRuntime.prototype.resume = function() {
	this.driver.resume();
    this.inFeedHold = false;
}

GCodeRuntime.prototype._changeState = function(newstate) {
	log.debug("Changing state to " + newstate)
	if(newstate != "idle") {
		this.ok_to_disconnect = false;
	}
	this.machine.setState(this, newstate);
};

GCodeRuntime.prototype._limit = function() {
	var er = this.driver.getLastException();
	if(er && er.st == 203) {
		var msg = er.msg.replace(/\[[^\[\]]*\]/,'');
		this.driver.clearLastException();
		this._fail(msg);
		return true;
	}
	return false;
}

GCodeRuntime.prototype._onDriverStatus = function(status) {
	// Update the machine copy of g2 status variables
	for (var key in this.machine.status) {
		if(key in status) {
			this.machine.status[key] = status[key];
		}
	}
	// Update the machine copy of g2 status variables
	for (key in status) {
		this.status_report[key] = status[key];
	}

	this.machine.emit('status',this.machine.status);
};

GCodeRuntime.prototype._die = function() {
	this.machine.status.current_file = null;
	this.machine.status.line=null;
	this.machine.status.nb_lines=null;
 	try {
 		this.machine.status.job.fail();
 	} catch(e) {}
 	finally {
		this.machine.status.job=null;
 		this.machine.setState(this, 'dead', {error : 'A G2 exception has occurred. You must reboot your tool.'});
 	}
}

GCodeRuntime.prototype._fail = function(message) {
	this.machine.status.current_file = null;
	this.machine.status.line=null;
	this.machine.status.nb_lines=null;
 	try {
 		this.machine.status.job.fail();
 	} catch(e) {}
 	finally {
		this.machine.status.job=null;
 		this.machine.setState(this, 'stopped', {error : message});
 	}
}

GCodeRuntime.prototype._idle = function() {
	this.machine.status.current_file = null;
	this.machine.status.line=null;
	this.machine.status.nb_lines=null;
	var job = this.machine.status.job;
	// Set the machine state to idle and return the units to their default configuration
	var finishUp = function() {
		this.driver.setUnits(config.machine.get('units'), function() {
			var callback = this.completeCallback || function() {};
			this.ok_to_disconnect = true;
			this.completeCallback = null;
			this.machine.setState(this, 'idle');
			callback();
		}.bind(this))
	}.bind(this);

	if(job) {
		if(job.pending_cancel) {
			this.machine.status.job.cancel(function(err, job) {
				this.machine.status.job=null;
				finishUp();
			}.bind(this));
		} else {
			this.machine.status.job.finish(function(err, job) {
				this.machine.status.job=null;
				finishUp();
			}.bind(this));
		}
	} else {
		finishUp();
	}
};

// Run the provided string
// callback runs only when execution is complete.
GCodeRuntime.prototype.runString = function(string, callback) {
	if(callback) { log.error("CALLBACK PASSED TO RUNSTRING")}

	if(this.machine.status.state === 'idle' || this.machine.status.state === 'armed') {
		// Add line numbers to Gcode string.
		var lines =  string.split('\n');
		this.machine.status.nb_lines = lines.length;
		for (i=0;i<lines.length;i++){
			if (lines[i][0]!==undefined && lines[i][0].toUpperCase() !== 'N' ){
				lines[i]= 'N'+ (i+1) + lines[i];
			}
		}
		// Set absolute or incremental per config.
		var mode = config.driver.get('gdi') ? 'G91': 'G90';
		lines.unshift(mode);
		this.completeCallback = callback;
		this._changeState("running");
		var stringStream = new stream.Readable();
		// Push lines to stream.
		for(var i=0; i<lines.length; i++) {
			stringStream.push(lines[i] + "\n");
		}
		stringStream.push(null);
		return this.driver.runStream(stringStream)
		.on('stat', this._handleStateChange.bind(this))
		.then(this._handleStop.bind(this));
	}
};

GCodeRuntime.prototype._handleStop = function() {
	this._idle();
}

GCodeRuntime.prototype._handleStateChange = function(stat) {
	switch(stat) {
		case this.driver.STAT_HOLDING:
			this._changeState('paused');
			break;
		case this.driver.STAT_RUNNING:
			this._changeState('running');
			break;
        case this.driver.STAT_STOP:
            // This that the g2core is in stat:3, meaning it has processed all available gcode
            // so we need to tell it to move to stat:4 by sending an end of job "M30"
            // There may have been an M30 in the file but the g2core will have ignored it, this
            // may change someday in the future on the g2core end, so we may end up revisiting this.
            // OTOH, an extra M30 should not cause a problem.
            if (this._file_or_stream_in_progress) {
                this.driver.sendM30();
                this._file_or_stream_in_progress = false;
            }

		default:
			break;
	}
}

// Run a file given the filename
GCodeRuntime.prototype.runFile = function(filename, callback) {
    this._file_or_stream_in_progress = true;
	countLineNumbers(filename, function(err, lines) {
		this.machine.status.nb_lines = lines;
		var st = fs.createReadStream(filename);
		var ln = new LineNumberer();
		return this.driver.runStream(st.pipe(ln))
			.on('stat', this._handleStateChange.bind(this))
			.then(this._handleStop.bind(this));
	}.bind(this));
}

// Run the given string as gcode
GCodeRuntime.prototype.executeCode = function(string, callback) {
	this._file_or_stream_in_progress = true;
	return this.runString(string);
}

exports.GCodeRuntime = GCodeRuntime;<|endoftext|>


<commit_before>"use strict";
(function(func) {
  var script, installer, onclick, container;
  script = document.createElement("script");
  if (script.style === null) { return; }
  window.addEventListener("VimiumRegistrationElementEvent", installer = function(event) {
    window.removeEventListener("VimiumRegistrationElementEvent", installer, true);
    container = event.target;
    container.addEventListener("VimiumRegistrationElementEvent-click", onclick, true);
    installer = null;
  }, true);
  window.addEventListener("VimiumRegistrationElementEvent-onclick", onclick = function(event) {
    event.target.hasOnclick = true;
    event.stopPropagation();
  }, true);
  Settings.onDestroy.registerClick = function() {
    window.removeEventListener("VimiumRegistrationElementEvent", installer, true);
    window.removeEventListener("VimiumRegistrationElementEvent-onclick", onclick, true);
    container && container.removeEventListener("VimiumRegistrationElementEvent-onclick", onclick, true);
  };
  script.type = "text/javascript";
  script.id = "vimium-plus-extend-click";
  script.textContent = "(" + func.toString() + ")()";
  container = document.head || document.documentElement;
  container.insertBefore(script, container.firstElementChild);
  script.remove();
})(function() {
"use strict";
var _listen, container, handler, reg, register, toRegister;

_listen = EventTarget.prototype.addEventListener;
toRegister = [];
register = function(element) { toRegister.push(element); };
EventTarget.prototype.addEventListener = function(type) {
  if (type === "click" && this instanceof Element) {
    register(this);
  }
  return _listen.apply(this, arguments);
};

handler = function() {
  container = document.createElementNS("http://www.w3.org/1999/xhtml", "div");
  document.documentElement.appendChild(container);
  container.dispatchEvent(new CustomEvent("VimiumRegistrationElementEvent"));
  document.documentElement.removeChild(container);
  register = reg;
  for (var i = toRegister.length; 0 <= --i; ) { register(toRegister[i]); }
  window.removeEventListener("DOMContentLoaded", handler, true);
  handler = toRegister = reg = null;
};
_listen.call(window, "DOMContentLoaded", handler, true);

reg = setTimeout.bind(window, function(element) {
  var e1, e2, registrationEvent, wrapIncontainer;
  wrapIncontainer = !document.contains(element);
  if (wrapIncontainer) {
    for (e1 = element; (e2 = e1.parentElement) != null; e1 = e2) {}
    if (e1.parentNode != null) { return; }
    container.appendChild(e1);
  }
  registrationEvent = new CustomEvent("VimiumRegistrationElementEvent-onclick");
  element.dispatchEvent(registrationEvent);
  if (wrapIncontainer) {
    container.removeChild(e1);
  }
}, 0);
});
<commit_msg>noop; rework extend_click::reg<commit_after>"use strict";
(function(func) {
  var script, installer, onclick, container;
  script = document.createElement("script");
  if (script.style === null) { return; }
  window.addEventListener("VimiumRegistrationElementEvent", installer = function(event) {
    window.removeEventListener("VimiumRegistrationElementEvent", installer, true);
    container = event.target;
    container.addEventListener("VimiumRegistrationElementEvent-click", onclick, true);
    installer = null;
  }, true);
  window.addEventListener("VimiumRegistrationElementEvent-onclick", onclick = function(event) {
    event.target.hasOnclick = true;
    event.stopPropagation();
  }, true);
  Settings.onDestroy.registerClick = function() {
    window.removeEventListener("VimiumRegistrationElementEvent", installer, true);
    window.removeEventListener("VimiumRegistrationElementEvent-onclick", onclick, true);
    container && container.removeEventListener("VimiumRegistrationElementEvent-onclick", onclick, true);
  };
  script.type = "text/javascript";
  script.id = "vimium-plus-extend-click";
  script.textContent = "(" + func.toString() + ")()";
  container = document.head || document.documentElement;
  container.insertBefore(script, container.firstElementChild);
  script.remove();
})(function() {
"use strict";
var _listen, container, handler, reg, register, toRegister;

_listen = EventTarget.prototype.addEventListener;
toRegister = [];
register = function(element) { toRegister.push(element); };
EventTarget.prototype.addEventListener = function(type) {
  if (type === "click" && this instanceof Element) {
    register(this);
  }
  return _listen.apply(this, arguments);
};

handler = function() {
  container = document.createElementNS("http://www.w3.org/1999/xhtml", "div");
  document.documentElement.appendChild(container);
  container.dispatchEvent(new CustomEvent("VimiumRegistrationElementEvent"));
  document.documentElement.removeChild(container);
  register = reg;
  for (var i = toRegister.length; 0 <= --i; ) { register(toRegister[i]); }
  window.removeEventListener("DOMContentLoaded", handler, true);
  handler = toRegister = reg = null;
};
_listen.call(window, "DOMContentLoaded", handler, true);

reg = setTimeout.bind(window, function(element) {
  var e1, e2, registrationEvent, wrapIncontainer;
  registrationEvent = new CustomEvent("VimiumRegistrationElementEvent-onclick");
  if (document.contains(element)) {
    element.dispatchEvent(registrationEvent);
    return;
  }
  for (e1 = element; (e2 = e1.parentElement) != null; e1 = e2) {}
  if (e1.parentNode != null) { return; }
  container.appendChild(e1);
  element.dispatchEvent(registrationEvent);
  container.removeChild(e1);
}, 0);
});
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013 DataTorrent, Inc. ALL Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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 text = DT.text;

/**
 * Page View Definitions
 *
 * This file contains a list of objects that
 * are definitions for every page view of the
 * UI.
 *
 * The keys on each are the following:
 * @param name         {String}           View name, should be unique from other page names (does not have to match with the view's pageName attribute).
 * @param routes       {Array}            List of one or more route expressions that should point to the page. These get extracted in NavModel.initialize.
 * @param view         {Backbone.View}    The page's backbone view. This should be a subclass of BasePageView.js.
 * @param paramList    {Array}            Specifies the key names for the pageParam object that gets injected into a page. @see PageLoaderView.
 * @param mode         {String}           Specifies the mode that the page resides in ('dev'|'ops')
 * @param breadcrumbs  {Array}            Array of objects representing an item of the breadcrumbs. Each object requires a 'name' field and optionally a 'href' field.
*/
exports = module.exports = [

    /**
     * CONFIGURATION MODE
     */
    {
        name: 'LoginPageView',
        routes: ['login','config/login','signin'],
        view: require('./lib/pages/LoginPageView'),
        paramList: [],
        mode: 'config',
        breadcrumbs: [
            {
                name: text('Log In')
            }
        ]
    },
    {
        'name': 'InstallWizardPageView',
        'routes': ['welcome', 'config/install-wizard'],
        'view': require('./lib/pages/InstallWizardPageView'),
        'paramList': [],
        'mode': 'config',
        'breadcrumbs': [
            {
                name: text('configuration'),
                href: '#config'
            },
            {
                name: text('Installation Wizard')
            }
        ]
    },

    {
        name: 'DiagnosticsPageView',
        routes: ['config/diagnostics'],
        view: require('./lib/pages/DiagnosticsPageView'),
        paramList: [],
        mode: 'config',
        breadcrumbs: [
            {
                name: text('configuration'),
                href: '#config'
            },
            {
                name: text('System Diagnostics')
            }
        ]
    },

    {
        'name': 'ConfigurationPageView',
        'routes': ['config', '/config', '/configuration'],
        'view': require('./lib/pages/ConfigPageView'),
        'paramList': [],
        'mode': 'config',
        'breadcrumbs': [
            {
                name: text('configuration')
            }
        ]
    },

    {
        name: 'LicensePageView',
        routes: ['config/license'],
        view: require('./lib/pages/LicensePageView'),
        mode: 'config',
        breadcrumbs: [
            {
                name: text('configuration'),
                href: '#config'
            },
            {
                name: text('License Information')
            }
        ]
    },

    // {
    //     name: 'ConfigPropertiesPageView',
    //     routes: ['config/properties'],
    //     view: require('./lib/pages/ConfigPropertiesPageView'),
    //     mode: 'config',
    //     breadcrumbs: [
    //         {
    //             name: text('configuration'),
    //             href: '#config'
    //         },
    //         {
    //             name: text('Properties')
    //         }
    //     ]
    // },

    /**
     * OPERATIONS MODE
     *
    */

    /** Operations View */
    {
        'name': 'OpsHomePageView',
        'routes': ['', '/', 'ops', 'ops/apps'],
        'view': require('./lib/pages/OpsHomePageView'),
        'paramList': [],
        'mode': 'ops',
        'breadcrumbs': [
            {
                name: text('ops_main_breadcrumb')
            }
        ]
    },

    /** App Instance View */
    {
        'name': 'AppInstancePageView',
        'routes': ['ops/apps/:appId'],
        'view': require('./lib/pages/AppInstancePageView'),
        'paramList': ['appId'],
        'mode': 'ops',
        'breadcrumbs': [
            // HCURL
            {
                name: text('ops_main_breadcrumb'),
                href: '#ops'
            },
            {
                name: function(page, appId) {
                    return appId;
                }
            }
        ]
    },

    /** Physical Operator View */
    {
        'name': 'PhysOpPageView',
        'routes': ['ops/apps/:appId/operators/:operatorId'],
        'view': require('./lib/pages/PhysOpPageView'),
        'paramList': ['appId', 'operatorId'],
        'mode': 'ops',
        'breadcrumbs': [
            // HCURL
            { name: text('ops_main_breadcrumb'), href: '#ops' },
            { name: function(page, appId, operatorId) {
                return appId;
            },href: function(page, appId, operatorId) {
                // HCURL
                return '#ops/apps/'+appId;
            }},
            { name: 'physical operators' },
            { name: function(page, appId, operatorId) {
                return operatorId;
            } }
        ]
    },

    /** Logical Operator View */
    {
        'name': 'LogicalOpPageView',
        'routes': ['ops/apps/:appId/logicalOperators/:logicalName'],
        'view': require('./lib/pages/LogicalOpPageView'),
        'paramList': ['appId', 'logicalName'],
        'mode': 'ops',
        'breadcrumbs': [
            { name: text('ops_main_breadcrumb'), href: '#ops' },
            { name: function(page, appId, operatorId) {
                return appId;
            },href: function(page, appId, operatorId) {
                // HCURL
                return '#ops/apps/'+appId;
            }},
            {
                name: 'logical operators'
            },
            {
                name: function(page, appId, logicalName) {
                    return logicalName;
                }
            }
        ]
    },

    /** Physical Port View */
    {
        'name': 'PortPageView',
        'routes': ['ops/apps/:appId/operators/:operatorId/ports/:portName'],
        'view': require('./lib/pages/PortPageView'),
        'paramList': ['appId', 'operatorId', 'portName'],
        'mode': 'ops',
        'breadcrumbs': [
            // HCURL
            { name: text('ops_main_breadcrumb'), href: '#ops' },
            { name: function(page, appId, operatorId) {
                return appId;
            },href: function(page, appId, operatorId) {
                // HCURL
                return '#ops/apps/'+appId;
            }},
            { name: function(page, appId, operatorId) {
                return 'operator_'+operatorId;
            },href: function(page, appId, operatorId) {
                // HCURL
                return '#ops/apps/'+appId+'/operators/'+operatorId;
            }},
            { name: function(page, appId, operatorId, portname) {
                return 'port_'+portname;
            }}
        ]
    },

    /** Stream View */
    {
        'name': 'StreamPageView',
        'routes': ['ops/apps/:appId/streams/:streamName'],
        'view': require('./lib/pages/StreamPageView'),
        'paramList': ['appId', 'streamName'],
        'mode': 'ops',
        'breadcrumbs': [
            {
                name: text('ops_main_breadcrumb'),
                // HCURL
                href: '#ops'
            },

            {
                name: function(page, appId, streamName) {
                    return appId;
                },
                href: function(page, appId, streamName) {
                    // HCURL
                    return '#ops/apps/' + appId;
                }
            },

            {
                name: function(page, appId, streamName) {
                    return 'stream ' + streamName;
                }
            }
        ]
    },

    /** Container View */
    {
        'name': 'ContainerPageView',
        'routes': ['ops/apps/:appId/containers/:containerid'],
        'view': require('./lib/pages/ContainerPageView'),
        'paramList': ['appId','containerId'],
        'mode': 'ops',
        'breadcrumbs': [
            {
                name: text('ops_main_breadcrumb'),
                // HCURL
                href: '#ops'
            },

            {
                name: function(page, appId, ctnrid) {
                    return appId;
                },
                href: function(page, appId, ctnrid) {
                    // HCURL
                    return '#ops/apps/' + appId;
                }
            },

            {
                name: function(page, appId, containerId) {
                    return containerId;
                }
            }
        ]
    },

    /** Recording View */
    {
        'name': 'RecordingPageView',
        'routes': ['ops/apps/:appId/operators/:operatorId/recordings/:startTime'],
        'view': require('./lib/pages/RecordingPageView'),
        'paramList': ['appId', 'operatorId', 'startTime'],
        'mode': 'ops',
        'breadcrumbs': [
            // HCURL
            { name: text('ops_main_breadcrumb'), href: '#ops' },
            { name: function(page, appId, operatorId) {
                return appId;
            },href: function(page, appId, operatorId) {
                // HCURL
                return '#ops/apps/'+appId;
            }},
            { name: function(page, appId, operatorId) {
                return 'operator_'+operatorId;
            },href: function(page, appId, operatorId) {
                // HCURL
                return '#ops/apps/'+appId+'/operators/'+operatorId;
            }},
            { name: function(page, appId, operatorId, starttime) {
                return 'recording_'+starttime;
            }}
        ]
    },

    /** Instance DAG View */
    {
        'name': 'DagPageView',
        'routes': ['ops/apps/:appId/dag'],
        'view': require('./lib/pages/DagPageView'),
        'paramList': ['appId'],
        'mode': 'ops',
        'breadcrumbs': [
            // HCURL
            {
                name: text('ops_main_breadcrumb'),
                href: '#ops'
            },
            {
                name: function(page, appid) {
                    return appid;
                }
            }
        ]
    },

    /** Add Alert View */
    {
        'name': 'AddAlertPageView',
        'routes': [
            'ops/apps/:appId/add_alert',
            'ops/apps/:appId/add_alert/:operatorName',
            'ops/apps/:appId/add_alert/:operatorName/:portName'
        ],
        'view': require('./lib/pages/AddAlertPageView'),
        'paramList': ['appId', 'operatorName', 'portName'],
        'mode': 'ops',
        'breadcrumbs': [
            // HCURL
            {
                name: text('ops_main_breadcrumb'),
                href: '#ops'
            },
            {
                name: function(page, appId) {
                    return appId;
                },
                href: function(page, appId, ctnrid) {
                    // HCURL
                    return '#ops/apps/' + appId;
                }
            },
            {
                name: 'add an alert'
            }
        ]
    },

    /**
     * DEVELOPMENT MODE
     *
    */

    /** Development View */
    // {
    //     'name': 'DevHomePageView',
    //     'routes': ['dev'],
    //     'view': require('./lib/pages/DevHomePageView'),
    //     'paramList': [],
    //     'mode': 'dev',
    //     'breadcrumbs': [
    //         {
    //             name: 'development'
    //         }
    //     ]
    // },

    /** Jar File Page */
    // {
    //     'name': 'JarFilePageView',
    //     'routes': ['dev/jars/:fileName'],
    //     'view': require('./lib/pages/JarFilePageView'),
    //     'paramList': ['fileName'],
    //     'mode': 'dev',
    //     'breadcrumbs': [
    //         {
    //             name: 'development',
    //             href: '#dev'
    //         },
    //         {
    //             name: 'uploaded jars',
    //             href: '#dev'
    //         },
    //         {
    //             name: function(page, fileName) {
    //                 return fileName;
    //             }
    //         }
    //     ]
    // },

    /** Jar Application Page  (an application within a jar) */
    // {
    //     'name': 'JarAppPageView',
    //     'routes': ['dev/jars/:fileName/:appName'],
    //     'view': require('./lib/pages/JarAppPageView'),
    //     'paramList': ['fileName', 'appName'],
    //     'mode': 'dev',
    //     'breadcrumbs': [
    //         {
    //             name: 'development',
    //             href: '#dev'
    //         },
    //         {
    //             name: 'uploaded jars',
    //             href: '#dev'
    //         },
    //         {
    //             name: function(page, fileName) {
    //                 return fileName;
    //             },
    //             href: function(page, fileName) {
    //                 return '#dev/jars/' + fileName;
    //             }
    //         },
    //         {
    //             name: function(page, fileName, appName) {
    //                 return appName;
    //             }
    //         }
    //     ]

    // },

    /** Add Alert Template View
    {
        'name': 'AddAlertTemplatePageView',
        'routes': ['dev/alerts/create_template'],
        'view': require('./lib/pages/AddAlertTemplatePageView'),
        'paramList': [],
        'mode': 'dev',
        'breadcrumbs': [
            // HCURL
            {
                name: 'development',
                href: '#dev'
            },
            {
                name: 'add an alert template'
            }
        ]
    },
    */

    /** Error Page */
    /* Keep this at the end of this list so it acts as a catch-all for unspecified URLs */
    {
        'name': 'ErrorPageView',
        'routes': ['*path'],
        'view': require('./lib/pages/ErrorPageView'),
        'paramList': [],
        'mode': ''
    }

];<commit_msg>re-arranged page order in pages.js<commit_after>/*
 * Copyright (c) 2013 DataTorrent, Inc. ALL Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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 text = DT.text;

/**
 * Page View Definitions
 *
 * This file contains a list of objects that
 * are definitions for every page view of the
 * UI.
 *
 * The keys on each are the following:
 * @param name         {String}           View name, should be unique from other page names (does not have to match with the view's pageName attribute).
 * @param routes       {Array}            List of one or more route expressions that should point to the page. These get extracted in NavModel.initialize.
 * @param view         {Backbone.View}    The page's backbone view. This should be a subclass of BasePageView.js.
 * @param paramList    {Array}            Specifies the key names for the pageParam object that gets injected into a page. @see PageLoaderView.
 * @param mode         {String}           Specifies the mode that the page resides in ('dev'|'ops')
 * @param breadcrumbs  {Array}            Array of objects representing an item of the breadcrumbs. Each object requires a 'name' field and optionally a 'href' field.
*/
exports = module.exports = [

    /**
     * CONFIGURATION MODE
     */
    {
        name: 'LoginPageView',
        routes: ['login','config/login','signin'],
        view: require('./lib/pages/LoginPageView'),
        paramList: [],
        mode: 'config',
        breadcrumbs: [
            {
                name: text('Log In')
            }
        ]
    },
    {
        'name': 'ConfigurationPageView',
        'routes': ['config', '/config', '/configuration'],
        'view': require('./lib/pages/ConfigPageView'),
        'paramList': [],
        'mode': 'config',
        'breadcrumbs': [
            {
                name: text('configuration')
            }
        ]
    },
    {
        'name': 'InstallWizardPageView',
        'routes': ['welcome', 'config/install-wizard'],
        'view': require('./lib/pages/InstallWizardPageView'),
        'paramList': [],
        'mode': 'config',
        'breadcrumbs': [
            {
                name: text('configuration'),
                href: '#config'
            },
            {
                name: text('Installation Wizard')
            }
        ]
    },
    {
        name: 'DiagnosticsPageView',
        routes: ['config/diagnostics'],
        view: require('./lib/pages/DiagnosticsPageView'),
        paramList: [],
        mode: 'config',
        breadcrumbs: [
            {
                name: text('configuration'),
                href: '#config'
            },
            {
                name: text('System Diagnostics')
            }
        ]
    },

    {
        name: 'LicensePageView',
        routes: ['config/license'],
        view: require('./lib/pages/LicensePageView'),
        mode: 'config',
        breadcrumbs: [
            {
                name: text('configuration'),
                href: '#config'
            },
            {
                name: text('License Information')
            }
        ]
    },

    // {
    //     name: 'ConfigPropertiesPageView',
    //     routes: ['config/properties'],
    //     view: require('./lib/pages/ConfigPropertiesPageView'),
    //     mode: 'config',
    //     breadcrumbs: [
    //         {
    //             name: text('configuration'),
    //             href: '#config'
    //         },
    //         {
    //             name: text('Properties')
    //         }
    //     ]
    // },

    /**
     * OPERATIONS MODE
     *
    */

    /** Operations View */
    {
        'name': 'OpsHomePageView',
        'routes': ['', '/', 'ops', 'ops/apps'],
        'view': require('./lib/pages/OpsHomePageView'),
        'paramList': [],
        'mode': 'ops',
        'breadcrumbs': [
            {
                name: text('ops_main_breadcrumb')
            }
        ]
    },

    /** App Instance View */
    {
        'name': 'AppInstancePageView',
        'routes': ['ops/apps/:appId'],
        'view': require('./lib/pages/AppInstancePageView'),
        'paramList': ['appId'],
        'mode': 'ops',
        'breadcrumbs': [
            // HCURL
            {
                name: text('ops_main_breadcrumb'),
                href: '#ops'
            },
            {
                name: function(page, appId) {
                    return appId;
                }
            }
        ]
    },

    /** Physical Operator View */
    {
        'name': 'PhysOpPageView',
        'routes': ['ops/apps/:appId/operators/:operatorId'],
        'view': require('./lib/pages/PhysOpPageView'),
        'paramList': ['appId', 'operatorId'],
        'mode': 'ops',
        'breadcrumbs': [
            // HCURL
            { name: text('ops_main_breadcrumb'), href: '#ops' },
            { name: function(page, appId, operatorId) {
                return appId;
            },href: function(page, appId, operatorId) {
                // HCURL
                return '#ops/apps/'+appId;
            }},
            { name: 'physical operators' },
            { name: function(page, appId, operatorId) {
                return operatorId;
            } }
        ]
    },

    /** Logical Operator View */
    {
        'name': 'LogicalOpPageView',
        'routes': ['ops/apps/:appId/logicalOperators/:logicalName'],
        'view': require('./lib/pages/LogicalOpPageView'),
        'paramList': ['appId', 'logicalName'],
        'mode': 'ops',
        'breadcrumbs': [
            { name: text('ops_main_breadcrumb'), href: '#ops' },
            { name: function(page, appId, operatorId) {
                return appId;
            },href: function(page, appId, operatorId) {
                // HCURL
                return '#ops/apps/'+appId;
            }},
            {
                name: 'logical operators'
            },
            {
                name: function(page, appId, logicalName) {
                    return logicalName;
                }
            }
        ]
    },

    /** Physical Port View */
    {
        'name': 'PortPageView',
        'routes': ['ops/apps/:appId/operators/:operatorId/ports/:portName'],
        'view': require('./lib/pages/PortPageView'),
        'paramList': ['appId', 'operatorId', 'portName'],
        'mode': 'ops',
        'breadcrumbs': [
            // HCURL
            { name: text('ops_main_breadcrumb'), href: '#ops' },
            { name: function(page, appId, operatorId) {
                return appId;
            },href: function(page, appId, operatorId) {
                // HCURL
                return '#ops/apps/'+appId;
            }},
            { name: function(page, appId, operatorId) {
                return 'operator_'+operatorId;
            },href: function(page, appId, operatorId) {
                // HCURL
                return '#ops/apps/'+appId+'/operators/'+operatorId;
            }},
            { name: function(page, appId, operatorId, portname) {
                return 'port_'+portname;
            }}
        ]
    },

    /** Stream View */
    {
        'name': 'StreamPageView',
        'routes': ['ops/apps/:appId/streams/:streamName'],
        'view': require('./lib/pages/StreamPageView'),
        'paramList': ['appId', 'streamName'],
        'mode': 'ops',
        'breadcrumbs': [
            {
                name: text('ops_main_breadcrumb'),
                // HCURL
                href: '#ops'
            },

            {
                name: function(page, appId, streamName) {
                    return appId;
                },
                href: function(page, appId, streamName) {
                    // HCURL
                    return '#ops/apps/' + appId;
                }
            },

            {
                name: function(page, appId, streamName) {
                    return 'stream ' + streamName;
                }
            }
        ]
    },

    /** Container View */
    {
        'name': 'ContainerPageView',
        'routes': ['ops/apps/:appId/containers/:containerid'],
        'view': require('./lib/pages/ContainerPageView'),
        'paramList': ['appId','containerId'],
        'mode': 'ops',
        'breadcrumbs': [
            {
                name: text('ops_main_breadcrumb'),
                // HCURL
                href: '#ops'
            },

            {
                name: function(page, appId, ctnrid) {
                    return appId;
                },
                href: function(page, appId, ctnrid) {
                    // HCURL
                    return '#ops/apps/' + appId;
                }
            },

            {
                name: function(page, appId, containerId) {
                    return containerId;
                }
            }
        ]
    },

    /** Recording View */
    {
        'name': 'RecordingPageView',
        'routes': ['ops/apps/:appId/operators/:operatorId/recordings/:startTime'],
        'view': require('./lib/pages/RecordingPageView'),
        'paramList': ['appId', 'operatorId', 'startTime'],
        'mode': 'ops',
        'breadcrumbs': [
            // HCURL
            { name: text('ops_main_breadcrumb'), href: '#ops' },
            { name: function(page, appId, operatorId) {
                return appId;
            },href: function(page, appId, operatorId) {
                // HCURL
                return '#ops/apps/'+appId;
            }},
            { name: function(page, appId, operatorId) {
                return 'operator_'+operatorId;
            },href: function(page, appId, operatorId) {
                // HCURL
                return '#ops/apps/'+appId+'/operators/'+operatorId;
            }},
            { name: function(page, appId, operatorId, starttime) {
                return 'recording_'+starttime;
            }}
        ]
    },

    /** Instance DAG View */
    {
        'name': 'DagPageView',
        'routes': ['ops/apps/:appId/dag'],
        'view': require('./lib/pages/DagPageView'),
        'paramList': ['appId'],
        'mode': 'ops',
        'breadcrumbs': [
            // HCURL
            {
                name: text('ops_main_breadcrumb'),
                href: '#ops'
            },
            {
                name: function(page, appid) {
                    return appid;
                }
            }
        ]
    },

    /** Add Alert View */
    {
        'name': 'AddAlertPageView',
        'routes': [
            'ops/apps/:appId/add_alert',
            'ops/apps/:appId/add_alert/:operatorName',
            'ops/apps/:appId/add_alert/:operatorName/:portName'
        ],
        'view': require('./lib/pages/AddAlertPageView'),
        'paramList': ['appId', 'operatorName', 'portName'],
        'mode': 'ops',
        'breadcrumbs': [
            // HCURL
            {
                name: text('ops_main_breadcrumb'),
                href: '#ops'
            },
            {
                name: function(page, appId) {
                    return appId;
                },
                href: function(page, appId, ctnrid) {
                    // HCURL
                    return '#ops/apps/' + appId;
                }
            },
            {
                name: 'add an alert'
            }
        ]
    },

    /**
     * DEVELOPMENT MODE
     *
    */

    /** Development View */
    // {
    //     'name': 'DevHomePageView',
    //     'routes': ['dev'],
    //     'view': require('./lib/pages/DevHomePageView'),
    //     'paramList': [],
    //     'mode': 'dev',
    //     'breadcrumbs': [
    //         {
    //             name: 'development'
    //         }
    //     ]
    // },

    /** Jar File Page */
    // {
    //     'name': 'JarFilePageView',
    //     'routes': ['dev/jars/:fileName'],
    //     'view': require('./lib/pages/JarFilePageView'),
    //     'paramList': ['fileName'],
    //     'mode': 'dev',
    //     'breadcrumbs': [
    //         {
    //             name: 'development',
    //             href: '#dev'
    //         },
    //         {
    //             name: 'uploaded jars',
    //             href: '#dev'
    //         },
    //         {
    //             name: function(page, fileName) {
    //                 return fileName;
    //             }
    //         }
    //     ]
    // },

    /** Jar Application Page  (an application within a jar) */
    // {
    //     'name': 'JarAppPageView',
    //     'routes': ['dev/jars/:fileName/:appName'],
    //     'view': require('./lib/pages/JarAppPageView'),
    //     'paramList': ['fileName', 'appName'],
    //     'mode': 'dev',
    //     'breadcrumbs': [
    //         {
    //             name: 'development',
    //             href: '#dev'
    //         },
    //         {
    //             name: 'uploaded jars',
    //             href: '#dev'
    //         },
    //         {
    //             name: function(page, fileName) {
    //                 return fileName;
    //             },
    //             href: function(page, fileName) {
    //                 return '#dev/jars/' + fileName;
    //             }
    //         },
    //         {
    //             name: function(page, fileName, appName) {
    //                 return appName;
    //             }
    //         }
    //     ]

    // },

    /** Add Alert Template View
    {
        'name': 'AddAlertTemplatePageView',
        'routes': ['dev/alerts/create_template'],
        'view': require('./lib/pages/AddAlertTemplatePageView'),
        'paramList': [],
        'mode': 'dev',
        'breadcrumbs': [
            // HCURL
            {
                name: 'development',
                href: '#dev'
            },
            {
                name: 'add an alert template'
            }
        ]
    },
    */

    /** Error Page */
    /* Keep this at the end of this list so it acts as a catch-all for unspecified URLs */
    {
        'name': 'ErrorPageView',
        'routes': ['*path'],
        'view': require('./lib/pages/ErrorPageView'),
        'paramList': [],
        'mode': ''
    }

];<|endoftext|>


<commit_before>angular.module('jbDatePickable', [])
.directive('jbDatePickable', jbDatePickableDirective);

function jbDatePickableDirective () {
  return {
    restrict: 'E',
    templateUrl: '../angular-date-pickable.html',
    scope: {
      startDate: '=',
      endDate: '=',
      selectedDate: '=',
      selectedDateRange: '=',
    },
    controllerAs: 'vm',
    controller: controller,
    bindToController: true,
  }

  function controller ($scope) {
    var vm = this;

    // properties
    vm.visibleDate = moment().startOf('month');

    vm.setPrevMonth = setPrevMonth;
    vm.setNextMonth = setNextMonth;

    vm.selectDate = selectDate;
    vm.generateWeeks = generateWeeks;
    vm.isInRange = isInRange;
    vm.isSelected = isSelected;

    vm.visibleMonths = 2;

    ////
    updateVisibleDates();
    updateSelectedDateRange(vm.startDate, vm.endDate);

    function updateVisibleDates () {
      vm.visibleDates = [moment(vm.visibleDate.toDate())];
      for(var i = 1; i < vm.visibleMonths; i++) {
        vm.visibleDates.push(moment(vm.visibleDate.toDate()).add(i, 'month').startOf('month'));
      }
    }

    var weeksCache = {};

    function setPrevMonth() {
      vm.visibleDate = vm.visibleDate.add(-1, 'month').startOf('month');
      updateVisibleDates();
    }

    function setNextMonth() {
      vm.visibleDate = vm.visibleDate.add(1, 'month').startOf('month');
      updateVisibleDates();
    }

    function generateWeeks (date) {
      var start = date.clone().startOf('month');
      var end   = date.clone().endOf('month');

      var cacheKey = start.format('YYYY-MM');
      // check if we have already generated the days for this month, hacky memoization
      if (weeksCache[cacheKey])
        return weeksCache[cacheKey];

      var range = moment().range(start.startOf('week'), end.endOf('week'));

      var weeks = [];
      range.by('weeks', function(week) {
        var days = [];
        moment().range(week.clone().startOf('week'), week.clone().endOf('week')).by('days', function(day) {
          days.push(day.startOf('day').toDate());
        });
        weeks.push(days);
      });

      weeksCache[cacheKey] = weeks

      return weeks;
    }

    function selectDate(date) {
      // both dates are already selected, but user clicked a new date
      // reset them both
      if (vm.startDate && vm.endDate) {
        vm.endDate = null;
        vm.startDate = null;
        vm.selectedDateRange = null;
      }

      // both dates are unselected, select the start date
      if (!vm.startDate && !vm.endDate) {
        vm.startDate = date;
        vm.selectedDate = date;
        return;
      }

      if (vm.startDate && moment(date).isBefore(vm.startDate)) {
        vm.endDate = vm.startDate;
        vm.startDate = date;
        vm.selectedDate = date;
        return;
      }

      if (vm.startDate && moment(date).isAfter(vm.startDate)) {
        vm.endDate = date;
        return;
      }

    }

    function updateSelectedDateRange (start, end) {
      if (start && end)
        vm.selectedDateRange = moment().range(
            moment(start).startOf('day'),
            moment(end).endOf('day')
          );
    }

    function isInRange (date) {
      if (!vm.selectedDateRange) return false;
      var is = false;
      var is = vm.selectedDateRange.contains(date);

      return is;
    }

    function isSelected (date) {

      if(vm.startDate && moment(vm.startDate).isSame(date, 'day'))
        return true;

      if(vm.endDate && moment(vm.endDate).isSame(date, 'day'))
        return true;

      return false;
    }

    //  Watch for start and end date changes
    $scope.$watch(
      'vm.startDate',
      function(newStartDate, oldStartDate) {
        updateSelectedDateRange(vm.startDate, vm.endDate);
      }
    );

    $scope.$watch(
      'vm.endDate',
      function(newEndDate, oldEndDate) {
        updateSelectedDateRange(vm.startDate, vm.endDate);
      }
    );
  }
}
<commit_msg>Should have seperate start and end date for selection<commit_after>angular.module('jbDatePickable', [])
.directive('jbDatePickable', jbDatePickableDirective);

function jbDatePickableDirective () {
  return {
    restrict: 'E',
    templateUrl: '../angular-date-pickable.html',
    scope: {
      startDate: '=',
      endDate: '=',
      selectedDate: '=',
      selectedDateRange: '=',
    },
    controllerAs: 'vm',
    controller: controller,
    bindToController: true,
  }

  function controller ($scope) {
    var vm = this;

    // properties
    vm.visibleDate = moment().startOf('month');
    vm.selectStartDate = moment(vm.startDate).toDate(); //  Cloned dates
    vm.selectEndDate = moment(vm.endDate).toDate();

    vm.setPrevMonth = setPrevMonth;
    vm.setNextMonth = setNextMonth;

    vm.selectDate = selectDate;
    vm.generateWeeks = generateWeeks;
    vm.isInRange = isInRange;
    vm.isSelected = isSelected;

    vm.visibleMonths = 2;

    ////
    updateVisibleDates();
    updateSelectedDateRange(vm.startDate, vm.endDate);

    function updateVisibleDates () {
      vm.visibleDates = [moment(vm.visibleDate.toDate())];
      for(var i = 1; i < vm.visibleMonths; i++) {
        vm.visibleDates.push(moment(vm.visibleDate.toDate()).add(i, 'month').startOf('month'));
      }
    }

    var weeksCache = {};

    function setPrevMonth() {
      vm.visibleDate = vm.visibleDate.add(-1, 'month').startOf('month');
      updateVisibleDates();
    }

    function setNextMonth() {
      vm.visibleDate = vm.visibleDate.add(1, 'month').startOf('month');
      updateVisibleDates();
    }

    function generateWeeks (date) {
      var start = date.clone().startOf('month');
      var end   = date.clone().endOf('month');

      var cacheKey = start.format('YYYY-MM');
      // check if we have already generated the days for this month, hacky memoization
      if (weeksCache[cacheKey])
        return weeksCache[cacheKey];

      var range = moment().range(start.startOf('week'), end.endOf('week'));

      var weeks = [];
      range.by('weeks', function(week) {
        var days = [];
        moment().range(week.clone().startOf('week'), week.clone().endOf('week')).by('days', function(day) {
          days.push(day.startOf('day').toDate());
        });
        weeks.push(days);
      });

      weeksCache[cacheKey] = weeks

      return weeks;
    }

    function selectDate(date) {
      // both dates are already selected, but user clicked a new date
      // reset them both
      if (vm.selectStartDate && vm.selectEndDate) {
        vm.selectEndDate = null;
        vm.selectStartDate = null;
        vm.selectedDateRange = null;
      }

      // both dates are unselected, select the start date
      if (!vm.selectStartDate && !vm.selectEndDate) {
        vm.selectStartDate = date;
        vm.selectedDate = date;
        return;
      }

      if (vm.selectStartDate && moment(date).isBefore(vm.selectStartDate)) {
        vm.selectEndDate = vm.selectStartDate;
        vm.selectStartDate = date;
        vm.selectedDate = date;
        updateSelectedDateRange();
        return;
      }

      if (vm.selectStartDate && moment(date).isAfter(vm.selectStartDate)) {
        vm.selectEndDate = date;
        updateSelectedDateRange();
        return;
      }

    }

    function updateSelectedDateRange () {
      if (vm.selectStartDate && vm.selectEndDate) {
        vm.selectedDateRange = moment().range(
            moment(vm.selectStartDate).startOf('day'),
            moment(vm.selectEndDate).endOf('day')
          );

        if (vm.startDate !== vm.selectStartDate)
          vm.startDate = vm.selectStartDate;

        if (vm.endDate !== vm.selectEndDate)
          vm.endDate = vm.selectEndDate;
      }
    }

    function isInRange (date) {
      if (!vm.selectedDateRange) return false;
      var is = false;
      var is = vm.selectedDateRange.contains(date);

      return is;
    }

    function isSelected (date) {

      if(vm.selectStartDate && moment(vm.selectStartDate).isSame(date, 'day'))
        return true;

      if(vm.selectEndDate && moment(vm.selectEndDate).isSame(date, 'day'))
        return true;

      return false;
    }

    //  Watch for start and end date changes
    $scope.$watch(
      'vm.startDate',
      function(newStartDate, oldStartDate) {
        if (newStartDate !== oldStartDate) {
          vm.selectStartDate = vm.startDate;
          _.debounce(updateSelectedDateRange, 100);
        }
      }
    );

    $scope.$watch(
      'vm.endDate',
      function(newEndDate, oldEndDate) {
        if (newEndDate !== oldEndDate) {
          vm.selectEndDate = vm.endDate;
          _.debounce(updateSelectedDateRange, 100)();
        }
      }
    );
  }
}
<|endoftext|>