<commit_before>'use strict';

class BackupMixin extends UniCollection.AbstractMixin {
    constructor ({
        expireAfter = false,

        backupOnRemove  = true,
        removeOnRestore = true,
        updateOnRestore = false
    } = {}) {
        super('BackupMixin');

        this.expireAfter = expireAfter;

        this.backupOnRemove  = backupOnRemove;
        this.removeOnRestore = removeOnRestore;
        this.updateOnRestore = updateOnRestore;
    }

    mount (collection) {
        collection.backupCollection = new UniCollection(collection.getCollectionName() + 'Backup');
        collection.backupCollection.create = collection.create.bind(collection);
        collection.backupCollection._validators = collection._validators;
        collection.backupCollection._universeValidators = collection._universeValidators;

        if (Meteor.isServer && this.expireAfter) {
            collection.backupCollection._ensureIndex({
                _backupAt: 1
            }, {
                expireAfterSeconds: this.expireAfter
            });
        }

        collection.methods({
            backup: (...args) => {
                this.backup(collection, ...args);
            },

            restore: (...args) => {
                this.restore(collection, ...args);
            }
        });

        collection.docHelpers({
            backup: function () {
                collection.call('backup', this._id);
            },

            restore: function (options = {}) {
                collection.call('restore', this._id, options);
            }
        });

        collection.backup = (selector = {}) => {
            collection.call('backup', selector);
        };

        collection.restore = (selector = {}, options = {}) => {
            collection.call('restore', selector, options);
        };

        if (this.backupOnRemove) {
            collection.onBeforeCall('remove', 'backup', id => collection.backup(id));
        }
    }

    backup (collection, selector = {}) {
        collection.find(selector).forEach(document => {
            collection.backupCollection.upsert(document._id, {
                ...document.toJSONValue(),
                _backupAt: new Date()
            });
        });
    }

    restore (collection, selector = {}, {
        removeOnRestore = this.removeOnRestore,
        updateOnRestore = this.updateOnRestore
    } = {}) {
        collection.backupCollection.find(selector).forEach(document => {
            const object = document.toJSONValue();
            delete object._backupAt;

            if (updateOnRestore) {
                collection.upsert(document._id, object);
            } else {
                collection.insert(object);
            }

            if (removeOnRestore) {
                document.remove();
            }
        });
    }
}

UniCollection.mixins.BackupMixin = BackupMixin;
<commit_msg>BackupMixin<commit_after>'use strict';

class BackupMixin extends UniCollection.AbstractMixin {
    constructor ({
        expireAfter = false,

        backupOnRemove  = true,
        removeOnRestore = true,
        updateOnRestore = false
    } = {}) {
        super('BackupMixin');

        this.expireAfter = expireAfter;

        this.backupOnRemove  = backupOnRemove;
        this.removeOnRestore = removeOnRestore;
        this.updateOnRestore = updateOnRestore;
    }

    mount (collection) {
        collection.backupCollection = new UniCollection(collection.getCollectionName() + 'Backup');
        collection.backupCollection.create = collection.create.bind(collection);
        collection.backupCollection._validators = collection._validators;
        collection.backupCollection._universeValidators = collection._universeValidators;

        if (Meteor.isServer && this.expireAfter) {
            collection.backupCollection._ensureIndex({
                _backupAt: 1
            }, {
                expireAfterSeconds: this.expireAfter
            });
        }

        collection.methods({
            backup: (...args) => {
                this.backup(collection, ...args);
            },

            restore: (...args) => {
                this.restore(collection, ...args);
            }
        });

        collection.docHelpers({
            backup: function () {
                collection.call('backup', this._id);
            },

            restore: function (options = {}) {
                collection.call('restore', this._id, options);
            }
        });

        collection.backup = (selector = {}) => {
            collection.call('backup', selector);
        };

        collection.restore = (selector = {}, options = {}) => {
            collection.call('restore', selector, options);
        };

        collection.onBeforeCall('remove', 'backup', (...args) => this.softRemove(collection, ...args));
    }

    backup (collection, selector = {}) {
        collection.find(selector).forEach(document => {
            collection.backupCollection.upsert(document._id, {
                ...document.toJSONValue(),
                _backupAt: new Date()
            });
        });
    }

    restore (collection, selector = {}, {
        removeOnRestore = this.removeOnRestore,
        updateOnRestore = this.updateOnRestore
    } = {}) {
        collection.backupCollection.find(selector).forEach(document => {
            var object = document.toJSONValue();
            delete object._backupAt;

            if (updateOnRestore) {
                collection.upsert(object._id, object);
            } else {
                collection.insert(object);
            }

            if (removeOnRestore) {
                document.remove();
            }
        });
    }

    softRemove (collection, id) {
        if (this.backupOnRemove) {
            collection.backup(id);
        }
    }
}

UniCollection.mixins.BackupMixin = BackupMixin;
<|endoftext|>


<commit_before>define([
	"dojo/_base/array",
	"dojo/_base/declare",
	"dijit/_Contained",
	"dijit/_Container",
	"dijit/_WidgetBase"
], function(array, declare, Contained, Container, WidgetBase){

/*=====
	var WidgetBase = dijit._WidgetBase;
=====*/

	// module:
	//		dojox/mobile/_PickerBase
	// summary:
	//		A base class for picker classes (e.g. SpinWheel, ValuePicker)

	return declare("dojox.mobile._PickerBase", [WidgetBase, Container, Contained], {
		// summary:
		//		dojox/mobile/_PickerBase

		// slotClasses: Array
		//		An array of slot classes.
		slotClasses: [],

		// slotProps: Array
		//		An array of property objects for each slot class specified in
		//		slotClasses.
		slotProps: [],

		// slotOrder: Array
		//		An array of index of slotClasses and slotProps.
		//		If there are three slots and slotOrder=[2,1,0], the slots are
		//		displayed in reverse order.
		slotOrder: [],

		buildRendering: function(){
			this.inherited(arguments);
			this.slots = [];
			for(var i = 0; i < this.slotClasses.length; i++){
				var idx = this.slotOrder.length ? this.slotOrder[i] : i;
				var slot = new this.slotClasses[idx](this.slotProps[idx]);
				this.addChild(slot);
				this.slots[idx] = slot;
			}
		},

		startup: function(){
			if(this._started){ return; }
			this.inherited(arguments);
			this.reset();
		},

		getSlots: function(){
			return this.slots.length ? this.slots :
				array.filter(this.getChildren(), function(c){
					return c.declaredClass.indexOf("Slot") !== -1;
				});
		},

		_getValuesAttr: function(){
			// summary:
			//		Returns an array of slot values.
			return array.map(this.getSlots(), function(w){
				return w.get("value");
			});
		},

		_setValuesAttr: function(/*Array*/a){
			// summary:
			//		Sets the slot values.
			array.forEach(this.getSlots(), function(w, i){
				w.set("value", a[i]);
			});
		},

		_setColorsAttr: function(/*Array*/a){
			// summary:
			//		Sets the slot colors.
			array.forEach(this.getSlots(), function(w, i){
				w.setColor && w.setColor(a[i]);
			});
		},

		reset: function(){
			// summary:
			//		Resets the picker to show the initial values.
			array.forEach(this.getSlots(), function(w){
				w.setInitialValue();
			});
		}
	});
});
<commit_msg>Fixes #15063 !strict. Fixed the setter for values to take a date in numbers in addition to strings.<commit_after>define([
	"dojo/_base/array",
	"dojo/_base/declare",
	"dijit/_Contained",
	"dijit/_Container",
	"dijit/_WidgetBase"
], function(array, declare, Contained, Container, WidgetBase){

/*=====
	var WidgetBase = dijit._WidgetBase;
=====*/

	// module:
	//		dojox/mobile/_PickerBase
	// summary:
	//		A base class for picker classes (e.g. SpinWheel, ValuePicker)

	return declare("dojox.mobile._PickerBase", [WidgetBase, Container, Contained], {
		// summary:
		//		dojox/mobile/_PickerBase

		// slotClasses: Array
		//		An array of slot classes.
		slotClasses: [],

		// slotProps: Array
		//		An array of property objects for each slot class specified in
		//		slotClasses.
		slotProps: [],

		// slotOrder: Array
		//		An array of index of slotClasses and slotProps.
		//		If there are three slots and slotOrder=[2,1,0], the slots are
		//		displayed in reverse order.
		slotOrder: [],

		buildRendering: function(){
			this.inherited(arguments);
			this.slots = [];
			for(var i = 0; i < this.slotClasses.length; i++){
				var idx = this.slotOrder.length ? this.slotOrder[i] : i;
				var slot = new this.slotClasses[idx](this.slotProps[idx]);
				this.addChild(slot);
				this.slots[idx] = slot;
			}
		},

		startup: function(){
			if(this._started){ return; }
			this.inherited(arguments);
			this.reset();
		},

		getSlots: function(){
			return this.slots.length ? this.slots :
				array.filter(this.getChildren(), function(c){
					return c.declaredClass.indexOf("Slot") !== -1;
				});
		},

		_getValuesAttr: function(){
			// summary:
			//		Returns an array of slot values.
			return array.map(this.getSlots(), function(w){
				return w.get("value");
			});
		},

		_setValuesAttr: function(/*Array*/a){
			// summary:
			//		Sets the slot values.
			array.forEach(this.getSlots(), function(w, i){
				var v = a[i];
				if(!isNaN(v)){
					var arr = [1970, 1, 1];
					arr.splice(i, 1, v - 0);
					v = w.format(new Date(arr));
				}
				w.set("value", v);
			});
		},

		_setColorsAttr: function(/*Array*/a){
			// summary:
			//		Sets the slot colors.
			array.forEach(this.getSlots(), function(w, i){
				w.setColor && w.setColor(a[i]);
			});
		},

		reset: function(){
			// summary:
			//		Resets the picker to show the initial values.
			array.forEach(this.getSlots(), function(w){
				w.setInitialValue();
			});
		}
	});
});
<|endoftext|>


<commit_before>describe("DeepCopy", function () {
    var myVect1 = me.Vector2d.extend({
        a : new me.Vector2d(0.5, 0.5),
        b : [1,2,3]
    });

    var myVect2 = myVect1.extend({
        a : new me.Vector2d(1.5, 1.5),
    });

    var vec1 = new myVect1(25, 25);
    var vec2 = new myVect2(50, 50);

    it("is an instance of me.Vector2d", function () {
        expect(vec1).toBeInstanceOf(me.Vector2d);
        expect(vec2).toBeInstanceOf(me.Vector2d);
    });

    it("is not an instance of myVect2", function () {
        expect(vec1).not.toBeInstanceOf(myVect2);
    });

    it("is an instance of myVect1", function () {
        expect(vec2).toBeInstanceOf(myVect1);
    });

    it("is not the same object", function () {
        expect(vec1.a).not.toBe(vec2.a);
        expect(vec1.b).not.toBe(vec2.b);
    });

    it("does not affect the other when changed", function () {
        vec2.b[0] = 3;

        expect(vec1.b[0]).not.toEqual(vec2.b[0]);
    });
});
<commit_msg>Add failing tests.<commit_after>describe("DeepCopy", function () {
    var myVect1 = me.Vector2d.extend({
        a : new me.Vector2d(0.5, 0.5),
        b : [1,2,3]
    });

    var myVect2 = myVect1.extend({
        a : new me.Vector2d(1.5, 1.5),
    });

    var vec1 = new myVect1(25, 25);
    var vec2 = new myVect2(50, 50);

    it("is an instance of me.Vector2d", function () {
        expect(vec1).toBeInstanceOf(me.Vector2d);
        expect(vec2).toBeInstanceOf(me.Vector2d);
    });

    it("is not an instance of myVect2", function () {
        expect(vec1).not.toBeInstanceOf(myVect2);
    });

    it("is an instance of myVect1", function () {
        expect(vec2).toBeInstanceOf(myVect1);
    });

    it("has an instance of me.Vector2d", function () {
        expect(vec1.a).toBeInstanceOf(me.Vector2d);
        expect(vec2.a).toBeInstanceOf(me.Vector2d);
    });

    it("has an instance of Array", function () {
        expect(vec1.b).toBeInstanceOf(Array);
        expect(vec2.b).toBeInstanceOf(Array);
    });

    it("is not the same object", function () {
        expect(vec1.a).not.toBe(vec2.a);
        expect(vec1.b).not.toBe(vec2.b);
    });

    it("does not affect the other when changed", function () {
        vec2.b[0] = 3;

        expect(vec1.b[0]).not.toEqual(vec2.b[0]);
    });
});
<|endoftext|>


<commit_before>// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"), require("../htmlmixed/htmlmixed"),
        require("../../addon/mode/overlay"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror", "../htmlmixed/htmlmixed",
            "../../addon/mode/overlay"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
  "use strict";

  CodeMirror.defineMode("django:inner", function() {
    var keywords = ["block", "endblock", "for", "endfor", "true", "false",
                    "loop", "none", "self", "super", "if", "endif", "as",
                    "else", "import", "with", "endwith", "without", "context", "ifequal", "endifequal",
                    "ifnotequal", "endifnotequal", "extends", "include", "load", "comment",
                    "endcomment", "empty", "url", "static", "trans", "blocktrans", "now", "regroup",
                    "lorem", "ifchanged", "endifchanged", "firstof", "debug", "cycle", "csrf_token",
                    "autoescape", "endautoescape", "spaceless", "ssi", "templatetag",
                    "verbatim", "endverbatim", "widthratio"],
        filters = ["add", "addslashes", "capfirst", "center", "cut", "date",
                   "default", "default_if_none", "dictsort",
                   "dictsortreversed", "divisibleby", "escape", "escapejs",
                   "filesizeformat", "first", "floatformat", "force_escape",
                   "get_digit", "iriencode", "join", "last", "length",
                   "length_is", "linebreaks", "linebreaksbr", "linenumbers",
                   "ljust", "lower", "make_list", "phone2numeric", "pluralize",
                   "pprint", "random", "removetags", "rjust", "safe",
                   "safeseq", "slice", "slugify", "stringformat", "striptags",
                   "time", "timesince", "timeuntil", "title", "truncatechars",
                   "truncatechars_html", "truncatewords", "truncatewords_html",
                   "unordered_list", "upper", "urlencode", "urlize",
                   "urlizetrunc", "wordcount", "wordwrap", "yesno"],
        operators = ["==", "!=", "<", ">", "<=", ">=", "in", "not", "or", "and"];

    keywords = new RegExp("^\\b(" + keywords.join("|") + ")\\b");
    filters = new RegExp("^\\b(" + filters.join("|") + ")\\b");
    operators = new RegExp("^\\b(" + operators.join("|") + ")\\b");

    // We have to return "null" instead of null, in order to avoid string
    // styling as the default, when using Django templates inside HTML
    // element attributes
    function tokenBase (stream, state) {
      // Attempt to identify a variable, template or comment tag respectively
      if (stream.match("{{")) {
        state.tokenize = inVariable;
        return "tag";
      } else if (stream.match("{%")) {
        state.tokenize = inTag;
        return "tag";
      } else if (stream.match("{#")) {
        state.tokenize = inComment;
        return "comment";
      }

      // Ignore completely any stream series that do not match the
      // Django template opening tags.
      while (stream.next() != null && !stream.match("{{", false) && !stream.match("{%", false)) {}
      return null;
    }

    // A string can be included in either single or double quotes (this is
    // the delimeter). Mark everything as a string until the start delimeter
    // occurs again.
    function inString (delimeter, previousTokenizer) {
      return function (stream, state) {
        if (!state.escapeNext && stream.eat(delimeter)) {
          state.tokenize = previousTokenizer;
        } else {
          if (state.escapeNext) {
            state.escapeNext = false;
          }

          var ch = stream.next();

          // Take into account the backslash for escaping characters, such as
          // the string delimeter.
          if (ch == "\\") {
            state.escapeNext = true;
          }
        }

        return "string";
      };
    }

    // Apply Django template variable syntax highlighting
    function inVariable (stream, state) {
      // Attempt to match a dot that precedes a property
      if (state.waitDot) {
        state.waitDot = false;

        if (stream.peek() != ".") {
          return "null";
        }

        // Dot folowed by a non-word character should be considered an error.
        if (stream.match(/\.\W+/)) {
          return "error";
        } else if (stream.eat(".")) {
          state.waitProperty = true;
          return "null";
        } else {
          throw Error ("Unexpected error while waiting for property.");
        }
      }

      // Attempt to match a pipe that precedes a filter
      if (state.waitPipe) {
        state.waitPipe = false;

        if (stream.peek() != "|") {
          return "null";
        }

        // Pipe folowed by a non-word character should be considered an error.
        if (stream.match(/\.\W+/)) {
          return "error";
        } else if (stream.eat("|")) {
          state.waitFilter = true;
          return "null";
        } else {
          throw Error ("Unexpected error while waiting for filter.");
        }
      }

      // Highlight properties
      if (state.waitProperty) {
        state.waitProperty = false;
        if (stream.match(/\b(\w+)\b/)) {
          state.waitDot = true;  // A property can be followed by another property
          state.waitPipe = true;  // A property can be followed by a filter
          return "property";
        }
      }

      // Highlight filters
      if (state.waitFilter) {
          state.waitFilter = false;
        if (stream.match(filters)) {
          return "variable-2";
        }
      }

      // Ignore all white spaces
      if (stream.eatSpace()) {
        state.waitProperty = false;
        return "null";
      }

      // Identify numbers
      if (stream.match(/\b\d+(\.\d+)?\b/)) {
        return "number";
      }

      // Identify strings
      if (stream.match("'")) {
        state.tokenize = inString("'", state.tokenize);
        return "string";
      } else if (stream.match('"')) {
        state.tokenize = inString('"', state.tokenize);
        return "string";
      }

      // Attempt to find the variable
      if (stream.match(/\b(\w+)\b/) && !state.foundVariable) {
        state.waitDot = true;
        state.waitPipe = true;  // A property can be followed by a filter
        return "variable";
      }

      // If found closing tag reset
      if (stream.match("}}")) {
        state.waitProperty = null;
        state.waitFilter = null;
        state.waitDot = null;
        state.waitPipe = null;
        state.tokenize = tokenBase;
        return "tag";
      }

      // If nothing was found, advance to the next character
      stream.next();
      return "null";
    }

    function inTag (stream, state) {
      // Attempt to match a dot that precedes a property
      if (state.waitDot) {
        state.waitDot = false;

        if (stream.peek() != ".") {
          return "null";
        }

        // Dot folowed by a non-word character should be considered an error.
        if (stream.match(/\.\W+/)) {
          return "error";
        } else if (stream.eat(".")) {
          state.waitProperty = true;
          return "null";
        } else {
          throw Error ("Unexpected error while waiting for property.");
        }
      }

      // Attempt to match a pipe that precedes a filter
      if (state.waitPipe) {
        state.waitPipe = false;

        if (stream.peek() != "|") {
          return "null";
        }

        // Pipe folowed by a non-word character should be considered an error.
        if (stream.match(/\.\W+/)) {
          return "error";
        } else if (stream.eat("|")) {
          state.waitFilter = true;
          return "null";
        } else {
          throw Error ("Unexpected error while waiting for filter.");
        }
      }

      // Highlight properties
      if (state.waitProperty) {
        state.waitProperty = false;
        if (stream.match(/\b(\w+)\b/)) {
          state.waitDot = true;  // A property can be followed by another property
          state.waitPipe = true;  // A property can be followed by a filter
          return "property";
        }
      }

      // Highlight filters
      if (state.waitFilter) {
          state.waitFilter = false;
        if (stream.match(filters)) {
          return "variable-2";
        }
      }

      // Ignore all white spaces
      if (stream.eatSpace()) {
        state.waitProperty = false;
        return "null";
      }

      // Identify numbers
      if (stream.match(/\b\d+(\.\d+)?\b/)) {
        return "number";
      }

      // Identify strings
      if (stream.match("'")) {
        state.tokenize = inString("'", state.tokenize);
        return "string";
      } else if (stream.match('"')) {
        state.tokenize = inString('"', state.tokenize);
        return "string";
      }

      // Attempt to match an operator
      if (stream.match(operators)) {
        return "operator";
      }

      // Attempt to match a keyword
      var keywordMatch = stream.match(keywords);
      if (keywordMatch) {
        if (keywordMatch[0] == "comment") {
          state.blockCommentTag = true;
        }
        return "keyword";
      }

      // Attempt to match a variable
      if (stream.match(/\b(\w+)\b/)) {
        state.waitDot = true;
        state.waitPipe = true;  // A property can be followed by a filter
        return "variable";
      }

      // If found closing tag reset
      if (stream.match("%}")) {
        state.waitProperty = null;
        state.waitFilter = null;
        state.waitDot = null;
        state.waitPipe = null;
        // If the tag that closes is a block comment tag, we want to mark the
        // following code as comment, until the tag closes.
        if (state.blockCommentTag) {
          state.blockCommentTag = false;  // Release the "lock"
          state.tokenize = inBlockComment;
        } else {
          state.tokenize = tokenBase;
        }
        return "tag";
      }

      // If nothing was found, advance to the next character
      stream.next();
      return "null";
    }

    // Mark everything as comment inside the tag and the tag itself.
    function inComment (stream, state) {
      if (stream.match("#}")) {
        state.tokenize = tokenBase;
      }
      return "comment";
    }

    // Mark everything as a comment until the `blockcomment` tag closes.
    function inBlockComment (stream, state) {
      if (stream.match(/\{%\s*endcomment\s*%\}/, false)) {
        state.tokenize = inTag;
        stream.match("{%");
        return "tag";
      } else {
        stream.next();
        return "comment";
      }
    }

    return {
      startState: function () {
        return {tokenize: tokenBase};
      },
      token: function (stream, state) {
        return state.tokenize(stream, state);
      },
      blockCommentStart: "{% comment %}",
      blockCommentEnd: "{% endcomment %}"
    };
  });

  CodeMirror.defineMode("django", function(config) {
    var htmlBase = CodeMirror.getMode(config, "text/html");
    var djangoInner = CodeMirror.getMode(config, "django:inner");
    return CodeMirror.overlayMode(htmlBase, djangoInner);
  });

  CodeMirror.defineMIME("text/x-django", "django");
});
<commit_msg>[django mode] Added template tag keywords<commit_after>// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"), require("../htmlmixed/htmlmixed"),
        require("../../addon/mode/overlay"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror", "../htmlmixed/htmlmixed",
            "../../addon/mode/overlay"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
  "use strict";

  CodeMirror.defineMode("django:inner", function() {
    var keywords = ["block", "endblock", "for", "endfor", "true", "false", "filter", "endfilter",
                    "loop", "none", "self", "super", "if", "elif", "endif", "as", "else", "import",
                    "with", "endwith", "without", "context", "ifequal", "endifequal", "ifnotequal",
                    "endifnotequal", "extends", "include", "load", "comment", "endcomment",
                    "empty", "url", "static", "trans", "blocktrans", "endblocktrans", "now",
                    "regroup", "lorem", "ifchanged", "endifchanged", "firstof", "debug", "cycle",
                    "csrf_token", "autoescape", "endautoescape", "spaceless", "endspaceless",
                    "ssi", "templatetag", "verbatim", "endverbatim", "widthratio"],
        filters = ["add", "addslashes", "capfirst", "center", "cut", "date",
                   "default", "default_if_none", "dictsort",
                   "dictsortreversed", "divisibleby", "escape", "escapejs",
                   "filesizeformat", "first", "floatformat", "force_escape",
                   "get_digit", "iriencode", "join", "last", "length",
                   "length_is", "linebreaks", "linebreaksbr", "linenumbers",
                   "ljust", "lower", "make_list", "phone2numeric", "pluralize",
                   "pprint", "random", "removetags", "rjust", "safe",
                   "safeseq", "slice", "slugify", "stringformat", "striptags",
                   "time", "timesince", "timeuntil", "title", "truncatechars",
                   "truncatechars_html", "truncatewords", "truncatewords_html",
                   "unordered_list", "upper", "urlencode", "urlize",
                   "urlizetrunc", "wordcount", "wordwrap", "yesno"],
        operators = ["==", "!=", "<", ">", "<=", ">=", "in", "not", "or", "and"];

    keywords = new RegExp("^\\b(" + keywords.join("|") + ")\\b");
    filters = new RegExp("^\\b(" + filters.join("|") + ")\\b");
    operators = new RegExp("^\\b(" + operators.join("|") + ")\\b");

    // We have to return "null" instead of null, in order to avoid string
    // styling as the default, when using Django templates inside HTML
    // element attributes
    function tokenBase (stream, state) {
      // Attempt to identify a variable, template or comment tag respectively
      if (stream.match("{{")) {
        state.tokenize = inVariable;
        return "tag";
      } else if (stream.match("{%")) {
        state.tokenize = inTag;
        return "tag";
      } else if (stream.match("{#")) {
        state.tokenize = inComment;
        return "comment";
      }

      // Ignore completely any stream series that do not match the
      // Django template opening tags.
      while (stream.next() != null && !stream.match("{{", false) && !stream.match("{%", false)) {}
      return null;
    }

    // A string can be included in either single or double quotes (this is
    // the delimeter). Mark everything as a string until the start delimeter
    // occurs again.
    function inString (delimeter, previousTokenizer) {
      return function (stream, state) {
        if (!state.escapeNext && stream.eat(delimeter)) {
          state.tokenize = previousTokenizer;
        } else {
          if (state.escapeNext) {
            state.escapeNext = false;
          }

          var ch = stream.next();

          // Take into account the backslash for escaping characters, such as
          // the string delimeter.
          if (ch == "\\") {
            state.escapeNext = true;
          }
        }

        return "string";
      };
    }

    // Apply Django template variable syntax highlighting
    function inVariable (stream, state) {
      // Attempt to match a dot that precedes a property
      if (state.waitDot) {
        state.waitDot = false;

        if (stream.peek() != ".") {
          return "null";
        }

        // Dot folowed by a non-word character should be considered an error.
        if (stream.match(/\.\W+/)) {
          return "error";
        } else if (stream.eat(".")) {
          state.waitProperty = true;
          return "null";
        } else {
          throw Error ("Unexpected error while waiting for property.");
        }
      }

      // Attempt to match a pipe that precedes a filter
      if (state.waitPipe) {
        state.waitPipe = false;

        if (stream.peek() != "|") {
          return "null";
        }

        // Pipe folowed by a non-word character should be considered an error.
        if (stream.match(/\.\W+/)) {
          return "error";
        } else if (stream.eat("|")) {
          state.waitFilter = true;
          return "null";
        } else {
          throw Error ("Unexpected error while waiting for filter.");
        }
      }

      // Highlight properties
      if (state.waitProperty) {
        state.waitProperty = false;
        if (stream.match(/\b(\w+)\b/)) {
          state.waitDot = true;  // A property can be followed by another property
          state.waitPipe = true;  // A property can be followed by a filter
          return "property";
        }
      }

      // Highlight filters
      if (state.waitFilter) {
          state.waitFilter = false;
        if (stream.match(filters)) {
          return "variable-2";
        }
      }

      // Ignore all white spaces
      if (stream.eatSpace()) {
        state.waitProperty = false;
        return "null";
      }

      // Identify numbers
      if (stream.match(/\b\d+(\.\d+)?\b/)) {
        return "number";
      }

      // Identify strings
      if (stream.match("'")) {
        state.tokenize = inString("'", state.tokenize);
        return "string";
      } else if (stream.match('"')) {
        state.tokenize = inString('"', state.tokenize);
        return "string";
      }

      // Attempt to find the variable
      if (stream.match(/\b(\w+)\b/) && !state.foundVariable) {
        state.waitDot = true;
        state.waitPipe = true;  // A property can be followed by a filter
        return "variable";
      }

      // If found closing tag reset
      if (stream.match("}}")) {
        state.waitProperty = null;
        state.waitFilter = null;
        state.waitDot = null;
        state.waitPipe = null;
        state.tokenize = tokenBase;
        return "tag";
      }

      // If nothing was found, advance to the next character
      stream.next();
      return "null";
    }

    function inTag (stream, state) {
      // Attempt to match a dot that precedes a property
      if (state.waitDot) {
        state.waitDot = false;

        if (stream.peek() != ".") {
          return "null";
        }

        // Dot folowed by a non-word character should be considered an error.
        if (stream.match(/\.\W+/)) {
          return "error";
        } else if (stream.eat(".")) {
          state.waitProperty = true;
          return "null";
        } else {
          throw Error ("Unexpected error while waiting for property.");
        }
      }

      // Attempt to match a pipe that precedes a filter
      if (state.waitPipe) {
        state.waitPipe = false;

        if (stream.peek() != "|") {
          return "null";
        }

        // Pipe folowed by a non-word character should be considered an error.
        if (stream.match(/\.\W+/)) {
          return "error";
        } else if (stream.eat("|")) {
          state.waitFilter = true;
          return "null";
        } else {
          throw Error ("Unexpected error while waiting for filter.");
        }
      }

      // Highlight properties
      if (state.waitProperty) {
        state.waitProperty = false;
        if (stream.match(/\b(\w+)\b/)) {
          state.waitDot = true;  // A property can be followed by another property
          state.waitPipe = true;  // A property can be followed by a filter
          return "property";
        }
      }

      // Highlight filters
      if (state.waitFilter) {
          state.waitFilter = false;
        if (stream.match(filters)) {
          return "variable-2";
        }
      }

      // Ignore all white spaces
      if (stream.eatSpace()) {
        state.waitProperty = false;
        return "null";
      }

      // Identify numbers
      if (stream.match(/\b\d+(\.\d+)?\b/)) {
        return "number";
      }

      // Identify strings
      if (stream.match("'")) {
        state.tokenize = inString("'", state.tokenize);
        return "string";
      } else if (stream.match('"')) {
        state.tokenize = inString('"', state.tokenize);
        return "string";
      }

      // Attempt to match an operator
      if (stream.match(operators)) {
        return "operator";
      }

      // Attempt to match a keyword
      var keywordMatch = stream.match(keywords);
      if (keywordMatch) {
        if (keywordMatch[0] == "comment") {
          state.blockCommentTag = true;
        }
        return "keyword";
      }

      // Attempt to match a variable
      if (stream.match(/\b(\w+)\b/)) {
        state.waitDot = true;
        state.waitPipe = true;  // A property can be followed by a filter
        return "variable";
      }

      // If found closing tag reset
      if (stream.match("%}")) {
        state.waitProperty = null;
        state.waitFilter = null;
        state.waitDot = null;
        state.waitPipe = null;
        // If the tag that closes is a block comment tag, we want to mark the
        // following code as comment, until the tag closes.
        if (state.blockCommentTag) {
          state.blockCommentTag = false;  // Release the "lock"
          state.tokenize = inBlockComment;
        } else {
          state.tokenize = tokenBase;
        }
        return "tag";
      }

      // If nothing was found, advance to the next character
      stream.next();
      return "null";
    }

    // Mark everything as comment inside the tag and the tag itself.
    function inComment (stream, state) {
      if (stream.match("#}")) {
        state.tokenize = tokenBase;
      }
      return "comment";
    }

    // Mark everything as a comment until the `blockcomment` tag closes.
    function inBlockComment (stream, state) {
      if (stream.match(/\{%\s*endcomment\s*%\}/, false)) {
        state.tokenize = inTag;
        stream.match("{%");
        return "tag";
      } else {
        stream.next();
        return "comment";
      }
    }

    return {
      startState: function () {
        return {tokenize: tokenBase};
      },
      token: function (stream, state) {
        return state.tokenize(stream, state);
      },
      blockCommentStart: "{% comment %}",
      blockCommentEnd: "{% endcomment %}"
    };
  });

  CodeMirror.defineMode("django", function(config) {
    var htmlBase = CodeMirror.getMode(config, "text/html");
    var djangoInner = CodeMirror.getMode(config, "django:inner");
    return CodeMirror.overlayMode(htmlBase, djangoInner);
  });

  CodeMirror.defineMIME("text/x-django", "django");
});
<|endoftext|>


<commit_before>const Application = require('spectron').Application
const assert = require('assert')
const electronPath = require('electron') // Require Electron from the binaries included in node_modules.
const path = require('path')

describe('Application launch', function () {
  this.timeout(10000)

  beforeEach(function () {
    this.app = new Application({
      path: electronPath,
      args: [path.join(__dirname, '../..')],
      requireName: 'electronRequire'
    })
    return this.app.start()
  })

  afterEach(function () {
    if (this.app && this.app.isRunning()) {
      return this.app.stop()
    }
  })

  it('shows an initial window', function () {
    return this.app.client.getWindowCount().then(function (count) {
      assert.equal(count, 1)
    })
  })
})
<commit_msg>Increase timeout<commit_after>const Application = require('spectron').Application
const assert = require('assert')
const electronPath = require('electron') // Require Electron from the binaries included in node_modules.
const path = require('path')

describe('Application launch', function () {
  this.timeout(30000)

  beforeEach(function () {
    this.app = new Application({
      path: electronPath,
      args: [path.join(__dirname, '../..')],
      requireName: 'electronRequire'
    })
    return this.app.start()
  })

  afterEach(function () {
    if (this.app && this.app.isRunning()) {
      return this.app.stop()
    }
  })

  it('shows an initial window', function () {
    return this.app.client.getWindowCount().then(function (count) {
      assert.equal(count, 1)
    })
  })
})
<|endoftext|>


<commit_before>var collection = new Meteor.Collection("test_collection_for_find_findone_userid");

var beforeFindUserId, afterFindUserId, beforeFindOneUserId, afterFindOneUserId;

// Don't declare hooks in publish method, as it is problematic
collection.before.find(function (userId, selector, options) {
  if (options && options.test) { // ignore other calls to find (caused by insert/update)
    beforeFindUserId = userId;
  }
});

collection.after.find(function (userId, selector, options, result) {
  if (options && options.test) { // ignore other calls to find (caused by insert/update)
    afterFindUserId = userId;
  }
});

collection.before.findOne(function (userId, selector, options) {
  if (options && options.test) { // ignore other calls to find (caused by insert/update)
    beforeFindOneUserId = userId;
  }
});

collection.after.findOne(function (userId, selector, options, result) {
  if (options && options.test) { // ignore other calls to find (caused by insert/update)
    afterFindOneUserId = userId;
  }
});

if (Meteor.isServer) {
  Meteor.publish("test_publish_for_find_findone_userid", function () {
    console.log("PUBLISHING");

    beforeFindUserId = null;
    afterFindUserId = null;
    beforeFindOneUserId = null;
    afterFindOneUserId = null;

    // Trigger hooks
    collection.find({}, {test: 1});
    collection.findOne({}, {test: 1});

    // TODO: reloading the browser will break these tests, because duplicate names are generated.

    Tinytest.add("find - userId available to before find hook when within publish context", function (test) {
      test.notEqual(beforeFindUserId, null);
    });

    Tinytest.add("find - userId available to after find hook when within publish context", function (test) {
      test.notEqual(afterFindUserId, null);
    });

    Tinytest.add("findone - userId available to before findOne hook when within publish context", function (test) {
      test.notEqual(beforeFindOneUserId, null);
    });

    Tinytest.add("findone - userId available to after findOne hook when within publish context", function (test) {
      test.notEqual(afterFindOneUserId, null);
    });

    return;
  });
}

if (Meteor.isClient) {
  beforeFindUserId = null;
  afterFindUserId = null;
  beforeFindOneUserId = null;
  afterFindOneUserId = null;

  // Trigger hooks
  collection.find({}, {test: 1});
  collection.findOne({}, {test: 1});

  // Run client tests.
  // TODO: Somehow, Tinytest.add / addAsync doesn't work inside InsecureLogin.ready().

  Tinytest.add("find - userId available to before find hook", function(test) {
    test.notEqual(beforeFindUserId, null);
  });

  Tinytest.add("find - userId available to after find hook", function(test) {
    test.notEqual(afterFindUserId, null);
  });

  Tinytest.add("findone - userId available to before findOne hook", function(test) {
    test.notEqual(beforeFindOneUserId, null);
  });

  Tinytest.add("findone - userId available to after findOne hook", function(test) {
    test.notEqual(afterFindOneUserId, null);
  });

  InsecureLogin.ready(function () {
    console.log("TRIGGERING SERVER FIND TESTS");
    // Run server tests
    Meteor.subscribe("test_publish_for_find_findone_userid");
  });
}
<commit_msg>prevent server tests from being re-added in find userid tests<commit_after>var collection = new Meteor.Collection("test_collection_for_find_findone_userid");

var beforeFindUserId, afterFindUserId, beforeFindOneUserId, afterFindOneUserId;

// Don't declare hooks in publish method, as it is problematic
collection.before.find(function (userId, selector, options) {
  if (options && options.test) { // ignore other calls to find (caused by insert/update)
    beforeFindUserId = userId;
  }
});

collection.after.find(function (userId, selector, options, result) {
  if (options && options.test) { // ignore other calls to find (caused by insert/update)
    afterFindUserId = userId;
  }
});

collection.before.findOne(function (userId, selector, options) {
  if (options && options.test) { // ignore other calls to find (caused by insert/update)
    beforeFindOneUserId = userId;
  }
});

collection.after.findOne(function (userId, selector, options, result) {
  if (options && options.test) { // ignore other calls to find (caused by insert/update)
    afterFindOneUserId = userId;
  }
});

if (Meteor.isServer) {
  var serverTestsAdded = false;

  Meteor.publish("test_publish_for_find_findone_userid", function () {
    console.log("PUBLISHING");

    beforeFindUserId = null;
    afterFindUserId = null;
    beforeFindOneUserId = null;
    afterFindOneUserId = null;

    // Trigger hooks
    collection.find({}, {test: 1});
    collection.findOne({}, {test: 1});

    if (!serverTestsAdded) {
      serverTestsAdded = true;

      Tinytest.add("find - userId available to before find hook when within publish context", function (test) {
        test.notEqual(beforeFindUserId, null);
      });

      Tinytest.add("find - userId available to after find hook when within publish context", function (test) {
        test.notEqual(afterFindUserId, null);
      });

      Tinytest.add("findone - userId available to before findOne hook when within publish context", function (test) {
        test.notEqual(beforeFindOneUserId, null);
      });

      Tinytest.add("findone - userId available to after findOne hook when within publish context", function (test) {
        test.notEqual(afterFindOneUserId, null);
      });
    }

    return;
  });
}

if (Meteor.isClient) {
  beforeFindUserId = null;
  afterFindUserId = null;
  beforeFindOneUserId = null;
  afterFindOneUserId = null;

  // Trigger hooks
  collection.find({}, {test: 1});
  collection.findOne({}, {test: 1});

  // Run client tests.
  // TODO: Somehow, Tinytest.add / addAsync doesn't work inside InsecureLogin.ready().

  Tinytest.add("find - userId available to before find hook", function(test) {
    test.notEqual(beforeFindUserId, null);
  });

  Tinytest.add("find - userId available to after find hook", function(test) {
    test.notEqual(afterFindUserId, null);
  });

  Tinytest.add("findone - userId available to before findOne hook", function(test) {
    test.notEqual(beforeFindOneUserId, null);
  });

  Tinytest.add("findone - userId available to after findOne hook", function(test) {
    test.notEqual(afterFindOneUserId, null);
  });

  InsecureLogin.ready(function () {
    console.log("TRIGGERING SERVER FIND TESTS");
    // Run server tests
    Meteor.subscribe("test_publish_for_find_findone_userid");
  });
}
<|endoftext|>


<commit_before>/**
 * A new JSON-based audio player for Full Screen Mario.
 * Influenced by Cody Lundquist: https://github.com/meenie/band.js
 * Pink noise measurements: http://www.firstpr.com.au/dsp/pink-noise/
 * GameBoy sound table: http://www.devrs.com/gb/files/sndtab.html
 * Note frequencies: http://www.phy.mtu.edu/~suits/notefreqs.html
 */
function AudioPlayr(settings) {
    "use strict";
    if(!this || this === window) {
        return new AudioPlayr(settings);
    }
    var self = this,

        // The AudioContext this is streaming to
        context,

        // The transforms being applied to the AudioContext output
        transforms,

        // The final transform, which is a gainNode to control volume
        volumeControl,

        // ???
        library,

        // ???
        collections,

        // Currently playing sounds
        currentSounds,

        // Lookup table of String note names to their frequency Numbers
        noteFrequencies,

        // Storage container for settings like volume and muted status
        StatsHolder,

        // Lookup table of Strings to generator Functions
        generatorNames = {
            "Oscillator": OscillatorGenerator,
            "WhiteNoise": WhiteNoiseGenerator,
            "PinkNoise": PinkNoiseGenerator,
            "BrownianNoise": BrownianNoiseGenerator
        },

        // Lookup table for playComponent actions
        playComponentActions = {
            "notes": playComponentNotes,
            "rest": playComponentRest,
            "repeat": playComponentRepeat
        };

    /**
     *
     */
    self.reset = function (settings) {
        context = new AudioContext();

        noteFrequencies = settings.noteFrequencies;

        resetTransforms(settings.transforms || []);

        if(settings.library) {
            library = settings.library;
            collections = self.processLibrary(library);
        } else {
            library = {};
            collections = {};
        }

        currentSounds = {};

        StatsHolder = new StatsHoldr(settings.statistics);

        self.setVolume(StatsHolder.get("volume"));
        self.setMuted(StatsHolder.get("muted"));
    };

    /**
     *
     */
    function resetTransforms(transformsRaw) {
        var i;

        // The internal transforms are a copy of the given transforms...
        transforms = transformsRaw.slice();

        // ...except also with a volumeControl at the end
        volumeControl = context.createGain();
        transforms.push(volumeControl);

        // Each transform then points to the next one...
        for(i = 0; i < transforms.length - 1; i += 1) {
            transforms[i].connect(transforms[i + 1].destination);
        }

        // ...which points to the final context
        transforms[i].connect(context.destination);
    }

    /* Storage modifiers
    */

    /**
     *
     */
    self.getLibrary = function () {
        return library;
    };

    /**
     *
     */
    self.setLibrary = function (libraryNew) {
        library = libraryNew;
    };

    /**
     *
     */
    self.getCollections = function () {
        return collections;
    };

    /**
     *
     */
    self.getCollection = function (key) {
        return collections[key];
    };

    /**
     *
     */
    self.getCurrentSounds = function () {
        return currentSounds;
    };

    /* Playback modifiers
    */

    /**
     *
     */
    self.setVolume = function (volume) {
        volumeControl.gain.value = volume;
        StatsHolder.set("volume", volume);
    };

    /**
     *
     */
    self.getVolume = function () {
        return StatsHolder.get("volume");
    };

    /**
     *
     */
    self.setMuted = function (muted) {
        if(muted) {
            volumeControl.gain.value = 0;
        } else {
            volumeControl.gain.value = self.getVolume();
        }

        StatsHolder.set("muted", muted);
    }

    /* Playback
    */

    /**
     *
     */
    self.play = function (key) {
        var collection = collections[key];

        if(!collection) {
            throw new Error("Unknown key given to AudioPlayr.play: '" + key + "'.");
        }

        currentSounds[key] = playCollection(collection);
    };

    /**
     *
     */
    function playCollection(collection) {
        var components = collection.components,
            component, instructions, i;

        for(i in components) {
            playComponent(components[i], collection);
        }
    }

    /**
     * Move to core?
     * doesn't check for rest.
     */
    function playComponent(component, collection) {
        var instruction = component.instructions[component.index];
        playComponentActions[instruction.type](instruction, component, collection);
    }

    /**
     *
     */
    function getBeatsPerLength(instruction, collection) {
        return instruction.length * collection.beatsPer.second * 166.6666667;
    }

    /**
     *
     */
    function playComponentNotes(instruction, component, collection) {
        var length = getBeatsPerLength(instruction, collection),
            players = instruction.notes.map(createPlayer.bind(undefined, component, instruction)),
            i;

        for(i = 0; i < players.length; i += 1) {
            players[i].play();
        }

        setTimeout(function () {
            for(i = 0; i < players.length; i += 1) {
                players[i].stop();
            }
            continueComponent(component, collection);
        }, length);
    }

    /**
     *
     */
    function playComponentRest(instruction, component, collection) {
        var length = getBeatsPerLength(instruction, collection);
        setTimeout(function () {
            continueComponent(component, collection);
        }, length);
    }

    /**
     *
     */
    function playComponentRepeat(instruction, component, collection) {
        switch(instruction.action) {
            case "start":
                playComponentRepeatStart(instruction, component, collection);
                break;
            case "play":
                playComponentRepeatPlay(instruction, component, collection);
                break;
        }

        continueComponent(component, collection);
    }

    /**
     *
     */
    function playComponentRepeatStart(instruction, component, collection) {
        component.repeatStack.push({
            "index": component.index,
            "repeated": 0
        });
    }

    /**
     *
     */
    function playComponentRepeatPlay(instruction, component, collection) {
        var repeater = component.repeatStack[component.repeatStack.length - 1];

        if(repeater.repeated >= instruction.times) {
            component.repeatStack.pop();
            return;
        }

        component.index = repeater.index;
        repeater.repeated += 1;
    }

    /**
     *
     */
    function continueComponent(component, collection) {
        component.index += 1;

        if(component.index < component.instructions.length) {
            playComponent(component, collection);
        }
    }

    /**
     * Move to core?
     */
    function createPlayer(component, instruction, note) {
        return new component.generatorConstructor(component.settings, {
            "frequency": note.constructor === String ? noteFrequencies[note] : note
        });
    }

    /**
     *
     */
    self.pause = function () {

    };

    /**
     *
     */
    self.resume = function () {

    };

    /* Core processing
    */

    /**
     *
     */
    self.processLibrary = function (library) {
        var output = {},
            key;

        for(key in library) {
            output[key] = self.processAudio(library[key]);
        }

        return output;
    }

    /**
     *
     */
    self.addAudio = function (key, settings) {
        library[key] = settings;
        processed[key] = self.processAudio(settings);
    };

    /**
     *
     */
    self.processAudio = function (settings) {
        return new AudioContainer(settings);
    }

    /**
     *
     */
    function AudioContainer(settings) {
        var components = this.components = {},
            i;

        for(i in settings.components) {
            components[i] = new AudioComponent(settings.components[i]);
        }

        this.beatsPer = {
            "minute": settings.bpm,
            "second": (settings.bpm / 60)
        };

        this.playing = false;
    };

    /**
     *
     */
    function AudioComponent(settings) {
        this.generatorConstructor = generatorNames[settings.generator];
        this.settings = settings.settings;
        this.instructions = settings.instructions;
        this.timeout = undefined;
        this.repeatStack = [];
        this.index = 0;
        this.playing = false;
    }

    /* Oscillator generator
    */

    /**
     *
     */
    function OscillatorGenerator() {
        var settings, i;

        this.oscillator = context.createOscillator();
        this.oscillator.connect(transforms[0])

        for(i = arguments.length - 1; i >= 0; i -= 1) {
            settings = arguments[i];
            if(typeof(settings.frequency) !== "undefined") {
                this.oscillator.frequency.value = settings.frequency;
            }
            if(typeof(settings.detune) !== "undefined") {
                this.oscillator.detune.value = settings.detune;
            }
            if(typeof(settings.type) !== "undefined") {
                this.oscillator.type = settings.type;
            }
        }
    }

    /**
     *
     */
    OscillatorGenerator.prototype.play = function (time) {
        this.oscillator.start(time | 0);
    };

    /**
     *
     */
    OscillatorGenerator.prototype.stop = function (time) {
        this.oscillator.stop(time | 0);
    };

    /**
     *
     */
    OscillatorGenerator.prototype.getEngine = function () {
        return this.oscillator;
    };

    /* Noise generators
    */

    /**
     *
     */
    var AbstractNoiseGenerator = {
        "preSetup": function (settings) {
            this.bufferSize = 2 * context.sampleRate;
            this.noiseBuffer = context.createBuffer(1, this.bufferSize, context.sampleRate);
            this.output = this.noiseBuffer.getChannelData(0);

            this.noise = context.createBufferSource();
            this.noise.buffer = this.noiseBuffer;
            this.noise.loop = true;
        },
        "postSetup": function (settings) {
            this.noise.connect(transforms[0])
        },
        "play": function (time) {
            this.noise.start(time | 0);
        },
        "stop": function (time) {
            this.noise.stop(time | 0);
        },
        "getEngine": function () {
            return this.noise;
        }
    };

    /**
     *
     */
    function WhiteNoiseGenerator(settings) {
        debugger;
        this.preSetup();

        for(var i = 0; i < this. output.length; i += 1) {
            this.output[i] = Math.random() * 2 - 1;
        }

        this.postSetup();
    }

    WhiteNoiseGenerator.prototype = AbstractNoiseGenerator;

    /**
     *
     */
    function PinkNoiseGenerator(settings) {
        var b0 = 0.0,
            b1 = 0.0,
            b2 = 0.0,
            b3 = 0.0,
            b4 = 0.0,
            b5 = 0.0,
            b6 = 0.0,
            white, i;

        this.preSetup();

        for(i = 0; i < this.bufferSize; ++i) {
            white = Math.random() * 2 - 1;
            b0 = 0.99886 * b0 + white * 0.0555179;
            b1 = 0.99332 * b1 + white * 0.0750759;
            b2 = 0.96900 * b2 + white * 0.1538520;
            b3 = 0.86650 * b3 + white * 0.3104856;
            b4 = 0.55000 * b4 + white * 0.5329522;
            b5 = -0.7616 * b5 - white * 0.0168980;
            b6 = white * 0.115926;
            this.output[i] = (b0 + b1 + b2 + b3 + b4 + b5 + b6 + white * 0.5362) * .11;
        }

        this.postSetup();
    }

    PinkNoiseGenerator.prototype = AbstractNoiseGenerator;

    /**
     *
     */
    function BrownianNoiseGenerator(settings) {
        var record = 0,
            i;

        this.preSetup();

        for(i = 0; i < this.bufferSize; ++i) {
            this.output[i] = (record + (Math.random() * .04 - 1)) / 1.02;
            record = this.output[i];
            this.output[i] *= 3.5;
        }

        this.postSetup();
    }

    BrownianNoiseGenerator.prototype = AbstractNoiseGenerator;

    self.reset(settings || {});
}<commit_msg>Re-usable NoiseGenerators and Oscillators<commit_after>/**
 * A new JSON-based audio player for Full Screen Mario.
 * Influenced by Cody Lundquist: https://github.com/meenie/band.js
 * Pink noise measurements: http://www.firstpr.com.au/dsp/pink-noise/
 * GameBoy sound table: http://www.devrs.com/gb/files/sndtab.html
 * Note frequencies: http://www.phy.mtu.edu/~suits/notefreqs.html
 */
function AudioPlayr(settings) {
    "use strict";
    if(!this || this === window) {
        return new AudioPlayr(settings);
    }
    var self = this,

        // The AudioContext this is streaming to
        context,

        // The transforms being applied to the AudioContext output
        transforms,

        // The final transform, which is a gainNode to control volume
        volumeControl,

        // ???
        library,

        // ???
        collections,

        // Currently playing sounds
        currentSounds,

        // Lookup table of String note names to their frequency Numbers
        noteFrequencies,

        // Storage container for settings like volume and muted status
        StatsHolder,

        // Lookup table of Strings to generator Functions
        generatorNames = {
            "Oscillator": OscillatorGenerator,
            "WhiteNoise": NoiseGenerator.bind(undefined, "White"),
            "PinkNoise": NoiseGenerator.bind(undefined, "Pink"),
            "BrownianNoise": NoiseGenerator.bind(undefined, "Brownian")
        },

        // Lookup table for playComponent actions
        playComponentActions = {
            "notes": playComponentNotes,
            "rest": playComponentRest,
            "repeat": playComponentRepeat
        };

    /**
     *
     */
    self.reset = function (settings) {
        context = new AudioContext();

        noteFrequencies = settings.noteFrequencies;

        resetTransforms(settings.transforms || []);

        if(settings.library) {
            library = settings.library;
            collections = self.processLibrary(library);
        } else {
            library = {};
            collections = {};
        }

        currentSounds = {};

        StatsHolder = new StatsHoldr(settings.statistics);

        self.setVolume(StatsHolder.get("volume"));
        self.setMuted(StatsHolder.get("muted"));
    };

    /**
     *
     */
    function resetTransforms(transformsRaw) {
        var i;

        // The internal transforms are a copy of the given transforms...
        transforms = transformsRaw.slice();

        // ...except also with a volumeControl at the end
        volumeControl = context.createGain();
        transforms.push(volumeControl);

        // Each transform then points to the next one...
        for(i = 0; i < transforms.length - 1; i += 1) {
            transforms[i].connect(transforms[i + 1].destination);
        }

        // ...which points to the final context
        transforms[i].connect(context.destination);
    }

    /* Storage modifiers
    */

    /**
     *
     */
    self.getLibrary = function () {
        return library;
    };

    /**
     *
     */
    self.setLibrary = function (libraryNew) {
        library = libraryNew;
    };

    /**
     *
     */
    self.getCollections = function () {
        return collections;
    };

    /**
     *
     */
    self.getCollection = function (key) {
        return collections[key];
    };

    /**
     *
     */
    self.getCurrentSounds = function () {
        return currentSounds;
    };

    /* Playback modifiers
    */

    /**
     *
     */
    self.setVolume = function (volume) {
        volumeControl.gain.value = volume;
        StatsHolder.set("volume", volume);
    };

    /**
     *
     */
    self.getVolume = function () {
        return StatsHolder.get("volume");
    };

    /**
     *
     */
    self.setMuted = function (muted) {
        if(muted) {
            volumeControl.gain.value = 0;
        } else {
            volumeControl.gain.value = self.getVolume();
        }

        StatsHolder.set("muted", muted);
    }

    /* Playback
    */

    /**
     *
     */
    self.play = function (key) {
        var collection = collections[key];

        if(!collection) {
            throw new Error("Unknown key given to AudioPlayr.play: '" + key + "'.");
        }

        currentSounds[key] = playCollection(collection);
    };

    /**
     *
     */
    function playCollection(collection) {
        var components = collection.components,
            component, instructions, i;

        collection.playing = true;

        for(i in components) {
            playComponent(components[i], collection);
        }
    }

    /**
     * Move to core?
     * doesn't check for rest.
     */
    function playComponent(component, collection) {
        var instruction = component.instructions[component.index];
        playComponentActions[instruction.type](instruction, component, collection);

        component.playing = true;
    }

    /**
     *
     */
    function getBeatsPerLength(instruction, collection) {
        return instruction.length * collection.beatsPer.second * 166.6666667;
    }

    /**
     *
     */
    function playComponentNotes(instruction, component, collection) {
        var length = getBeatsPerLength(instruction, collection),
            players = instruction.notes.map(createPlayer.bind(undefined, component, instruction)),
            i;

        for(i = 0; i < players.length; i += 1) {
            players[i].play();
        }

        component.timeout = setTimeout(function () {
            for(i = 0; i < players.length; i += 1) {
                players[i].stop();
            }
            continueComponent(component, collection);
        }, length);
    }

    /**
     *
     */
    function playComponentRest(instruction, component, collection) {
        var length = getBeatsPerLength(instruction, collection);
        setTimeout(function () {
            continueComponent(component, collection);
        }, length);
    }

    /**
     *
     */
    function playComponentRepeat(instruction, component, collection) {
        switch(instruction.action) {
            case "start":
                playComponentRepeatStart(instruction, component, collection);
                break;
            case "play":
                playComponentRepeatPlay(instruction, component, collection);
                break;
        }

        continueComponent(component, collection);
    }

    /**
     *
     */
    function playComponentRepeatStart(instruction, component, collection) {
        component.repeatStack.push({
            "index": component.index,
            "repeated": 0
        });
    }

    /**
     *
     */
    function playComponentRepeatPlay(instruction, component, collection) {
        var repeater = component.repeatStack[component.repeatStack.length - 1];

        if(repeater.repeated >= instruction.times) {
            component.repeatStack.pop();
            return;
        }

        component.index = repeater.index;
        repeater.repeated += 1;
    }

    /**
     *
     */
    function continueComponent(component, collection) {
        component.index += 1;

        if(component.index < component.instructions.length) {
            playComponent(component, collection);
        }
    }

    /**
     * Move to core?
     */
    function createPlayer(component, instruction, note) {
        return new component.generatorConstructor(component.settings, {
            "frequency": note.constructor === String ? noteFrequencies[note] : note
        });
    }

    /**
     *
     */
    self.pause = function () {

    };

    /**
     *
     */
    self.resume = function () {

    };

    /* Core processing
    */

    /**
     *
     */
    self.processLibrary = function (library) {
        var output = {},
            key;

        for(key in library) {
            output[key] = self.processAudio(library[key]);
        }

        return output;
    }

    /**
     *
     */
    self.addAudio = function (key, settings) {
        library[key] = settings;
        processed[key] = self.processAudio(settings);
    };

    /**
     *
     */
    self.processAudio = function (settings) {
        return new AudioContainer(settings);
    }

    /**
     *
     */
    function AudioContainer(settings) {
        var components = this.components = {},
            i;

        for(i in settings.components) {
            components[i] = new AudioComponent(settings.components[i]);
        }

        this.beatsPer = {
            "minute": settings.bpm,
            "second": (settings.bpm / 60)
        };

        this.playing = false;
    };

    /**
     *
     */
    function AudioComponent(settings) {
        this.generatorConstructor = generatorNames[settings.generator];
        this.settings = settings.settings;
        this.instructions = settings.instructions;
        this.timeout = undefined;
        this.repeatStack = [];
        this.index = 0;
        this.playing = false;
    }

    /* Oscillator generator
    */

    var AbstractOscillatorGenerator = {
        /**
         *
         */
        "recreate": function () {
            this.oscillator = context.createOscillator();
            this.oscillator.connect(transforms[0]);

            if(this.frequency) {
                this.oscillator.frequency.value = this.frequency;
            }
            if(this.settings) {
                this.oscillator.detune.value = this.detune;
            }
            if(this.type) {
                this.oscillator.type = this.type;
            }
        },

        /**
         *
         */
        "play": function (time) {
            this.oscillator.start(time | 0);
        },

        /**
         *
         */
        "stop": function (time) {
            this.oscillator.stop(time | 0);
            this.recreate();
        },

        /**
         *
         */
        "getEngine": function () {
            return this.oscillator;
        }
    };

    /**
     *
     */
    function OscillatorGenerator() {
        var settings, i;

        for(i = arguments.length - 1; i >= 0; i -= 1) {
            settings = arguments[i];
            if(typeof(settings.frequency) !== "undefined") {
                this.frequency = settings.frequency;
            }
            if(typeof(settings.detune) !== "undefined") {
                this.detune = settings.detune;
            }
            if(typeof(settings.type) !== "undefined") {
                this.type = settings.type;
            }
        }

        this.recreate();
    }

    OscillatorGenerator.prototype = AbstractOscillatorGenerator;

    self.getThing = function () {
        return new OscillatorGenerator();
    }

    /* Noise generators
    */

    /**
     *
     */
    var AbstractNoiseGenerator = {
        /**
         *
         */
        "preSetup": function (settings) {
            this.bufferSize = 2 * context.sampleRate;
            this.noiseBuffer = context.createBuffer(1, this.bufferSize, context.sampleRate);
            this.output = this.noiseBuffer.getChannelData(0);

            this.noise = context.createBufferSource();
            this.noise.buffer = this.noiseBuffer;
            this.noise.loop = true;
        },

        /**
         *
         */
        "postSetup": function (settings) {
            this.noise.connect(transforms[0])
        },

        /**
         *
         */
        "play": function () {
            this.noise.start();
        },

        /**
         *
         */
        "stop": function () {
            this.noise.stop();
            this.recreate(this.type);
        },

        /**
         *
         */
        "recreate": function () {
            this.preSetup();
            this.generators[this.type].call(this, settings);
            this.postSetup();
        },

        /**
         *
         */
        "getEngine": function () {
            return this.noise;
        },

        "generators": {
            /**
             *
             */
            "white": function () {
                for(var i = 0; i < this. output.length; i += 1) {
                    this.output[i] = Math.random() * 2 - 1;
                }
            },

            /**
             *
             */
            "pink": function () {
                var b0 = 0.0,
                    b1 = 0.0,
                    b2 = 0.0,
                    b3 = 0.0,
                    b4 = 0.0,
                    b5 = 0.0,
                    b6 = 0.0,
                    white, i;

                for(i = 0; i < this.bufferSize; ++i) {
                    white = Math.random() * 2 - 1;
                    b0 = 0.99886 * b0 + white * 0.0555179;
                    b1 = 0.99332 * b1 + white * 0.0750759;
                    b2 = 0.96900 * b2 + white * 0.1538520;
                    b3 = 0.86650 * b3 + white * 0.3104856;
                    b4 = 0.55000 * b4 + white * 0.5329522;
                    b5 = -0.7616 * b5 - white * 0.0168980;
                    b6 = white * 0.115926;
                    this.output[i] = (b0 + b1 + b2 + b3 + b4 + b5 + b6 + white * 0.5362) * .11;
                }
            },

            /**
             *
             */
            "brownian": function () {
                var record = 0,
                    i;

                for(i = 0; i < this.bufferSize; ++i) {
                    this.output[i] = (record + (Math.random() * .04 - 1)) / 1.02;
                    record = this.output[i];
                    this.output[i] *= 3.5;
                }
            }
        }
    };

    /**
     *
     */
    function NoiseGenerator(type) {
        this.type = type;
        this.recreate();
    }

    NoiseGenerator.prototype = AbstractNoiseGenerator;

    self.reset(settings || {});
}<|endoftext|>


<commit_before>import React, { PropTypes, Component } from 'react';
import { connect } from 'react-redux';
import CommentBox from './CommentBox';
/* eslint-disable */
import traverseDF from '../produceCommentGraph';
/* eslint-enable */

// function sortByTime(order) {
//   // Loop through the order array and update and bucketized neighbors in same array if of the same depth
//   // Sort each of the sub arrays in the big array in probably O(nlgn) time
//   // Flatten the newly sorted array to obtain array sorted by most recent!
//
//
//   order.map((node, i) => {
//     const date = node.createDate;
//
//     return 5;
//   });
//   return 0;
// }

class Comments extends Component {
  constructor(props) {
    super(props);
    console.log(props.replies);
  }

// Connect this to comment id -- rerender --> compute order in the action
  render() {
    const order = traverseDF(this.props.replies, () => {

    });

    // const newOrder = sortByTime(order);

    console.log('Posting ordering!');
    // console.log(newOrder);
    return (

        {order.map((node, i) => {
          return (
            <CommentBox
              ordering={order}
              node={node}
              key={node._id}
              dispatch={this.props.dispatch}
              id={i}
            />);
        })}

    );
  }
}

/* eslint-disable */

Comments.propTypes = {
  replies: PropTypes.array.isRequired,
  dispatch: PropTypes.func.isRequired,
};

/* eslint-enable */

export default connect()(Comments);
<commit_msg>Pseudocode for sorting algorithm posted<commit_after>import React, { PropTypes, Component } from 'react';
import { connect } from 'react-redux';
import CommentBox from './CommentBox';
/* eslint-disable */
import traverseDF from '../produceCommentGraph';
/* eslint-enable */

function sortByTime(order) {
  // Loop through the order array and update and bucketized neighbors in same array if of the same depth
  // Sort each of the sub arrays in the big array in probably O(nlgn) time
  // Flatten the newly sorted array to obtain array sorted by most recent!

  // 1 Divide into sub arrays
  for elem in ordering:

    if (ordering.length < 2) { //Array is only one element -- already sorted
      return;
    }

    if (i == ordering.length - 2) { //Don't go out of bounds of the array
      break;
    }

    a = new Array[];

    if (ordering[i].depth == ordering[i+1].depth)
      a.push;

// 2 // Sort sub arrays
for (elem in a) {
  if (!(elem.length < 2)) {
    elem = sort(elem);
  }
}

// 3 Flatten Array
  var merged = [].concat([a]);

  order.map((node, i) => {
    const date = node.createDate;

    return 5;
  });
  return 0;
}

class Comments extends Component {
  constructor(props) {
    super(props);
    console.log(props.replies);
  }

// Connect this to comment id -- rerender --> compute order in the action
  render() {
    const order = traverseDF(this.props.replies, () => {

    });

    // const newOrder = sortByTime(order);

    console.log('Posting ordering!');
    // console.log(newOrder);
    return (

        {order.map((node, i) => {
          return (
            <CommentBox
              ordering={order}
              node={node}
              key={node._id}
              dispatch={this.props.dispatch}
              id={i}
            />);
        })}

    );
  }
}

/* eslint-disable */

Comments.propTypes = {
  replies: PropTypes.array.isRequired,
  dispatch: PropTypes.func.isRequired,
};

/* eslint-enable */

export default connect()(Comments);
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import treeData from './../AnimationData/treeStructure';

// Tree and Link are two new components used by HalfwayFinishedStructureAnimation.
import Tree from './Tree';
import Link from './Link';

var d3 = require('d3');
var ReactDOM = require('react-dom');

// My goal in creating HalfwayFinishedStructureAnimation was to make React responsible for DOM structure (adding and removing elements) and to make D3 responsible for styling, as described in this blog post:
// https://medium.com/@sxywu/on-d3-react-and-a-little-bit-of-flux-88a226f328f3#.ztcxqykek

// We still need to handle window resizes. Here are some useful resources:
// http://eyeseast.github.io/visible-data/2013/08/28/responsive-charts-with-d3/
// http://bl.ocks.org/mbostock/3019563

export default class HalfwayFinishedStructureAnimation extends Component {

  constructor(props) {
    super(props);
    this.state = {
      treeData: props.initialTreeData,
      margin: props.initialMargin,
      treeHeight: props.initialTreeHeight,
      treeWidth: props.initialTreeWidth
    }
  }

  // This function is called after all the Tree and Link componentDidMount functions have been called.
  componentDidMount() {
    ipcRenderer.on('direc-schema', (e,arg)=>{
      this.updateTreeData(arg);
    })

    // Reset the tree height and width if needed?
    // Would it be better to use a ref rather than an id?
  }

  updateTreeData(newSchema) {
    this.setState({
      treeData: newSchema
    });
  }

  render() {
    var duration = 450; // We may want to make this a prop.

    // Create a tree layout.
    var tree = d3.layout.tree()
    // The first argument below is the maximum x-coordinate D3 will assign.
    // The second argument is the maximum y-coordinate.
    // We're switching width and height here because d3 by default makes trees that branch vertically, and we want a tree that branches horizontally.
    // In other words, nodes that are on the same level will have the same y-coordinate but different x-coordinates.
      .size([this.state.treeHeight, this.state.treeWidth]);

    // Create a diagonal generator, a type of path data generator.
    var diagonal = d3.svg.diagonal()
    // Isaac: I don't completely understand the projection yet.
      .projection(function(d) { return [d.y, d.x]; });

    // We know that the first node in the array is the root of the tree. Let's designate its initial coordinates - where it should enter.
    var root = this.state.treeData[0];
    root.x0 = this.state.treeHeight / 2;
    root.y0 = 0;

    // The next line creates and returns an array of nodes associated with the specified root node. (The returned array is basically a flattened version of treeData.)
    // D3 tree nodes always have parent, child, depth, x, and y properties.
    // Before the next line runs, each node has children, level, name, and value properties.
    // After the next line runs, each node also has parent, depth, x, and y properties.
    // We will pass one node from this array to each Tree as props.data.
    // ***Do we want to end the next line with reverse to put the root node at the end?
    var nodes = tree.nodes(root),
      // This line creates and returns an array of objects representing all parent-child links in the nodes array we just created.
      linkSelection = tree.links(nodes);

    // Determine how many levels the tree contains.
    for (var currentNode = root, maxDepth = 0;
      currentNode.children;
      currentNode = currentNode.children[0], maxDepth ++);

    nodes.forEach(function(d) {
      // The default y-coordinates provided by d3.tree will make the tree stretch all the way across the screen.
      // We want to compress the tree a bit so that there's room for file/directory names to the right of the deepest level.
      d.y *= .8;

      // We could scale d.x too to prevent the svg from cutting off notes at the top and bottom of a node column.

      // If the node has a parent, set the node's initial coordinates to the parent's initial coordinates.
      // *** Does this make sense?
      if (d.parent) {
        d.x0 = d.parent.x0;
        d.y0 = d.parent.y0;
      }
    });

    // I think it makes sense to the use target.name as an id, because no two links should ever point to the same target.
    // If needed, though, we could use {link.source.name + '/'  link.target.name} instead.
    var links = linkSelection && linkSelection.map((link) => {
      return (<Link key={link.target.name} data={link} diagonal={diagonal} duration={duration} />)
    });

    var trees = nodes && nodes.map((node) => {
      return (<Tree key={node.name} data={node} duration={duration} />);
    });

    console.log('Rendering. Latest update: d.y *= .8');

    var translationValue = `translate(${this.state.margin.left}, ${this.state.margin.top})`;

    // Do I need to set SVG height below? Is that even possible? Or will the SVG resize to fit the inner g's inside it? (It doesn't look like it's expanding to fit the tree layout.)
    // This StackOverflow response may help:
    // http://stackoverflow.com/questions/8919076/how-to-make-a-svg-element-expand-or-contract-to-its-parent-container
    return(

        <svg width='100%' height='100%' viewBox='0 0 660 200' preserveAspectRatio='none'>
          <g transform={translationValue}>
            {links}
            {trees}
          </g>
        </svg>

    )
  }
}

HalfwayFinishedStructureAnimation.defaultProps = {
  initialTreeData: treeData, // To start with an empty tree: [{}]
  initialMargin: {top: 0, right: 20, bottom: 0, left: 90},
  initialTreeHeight: 200,
  initialTreeWidth: 550
}
<commit_msg>SVG sizes correctly on initial load. Paths and trees are currently commented out.<commit_after>import React, {Component} from 'react';
import treeData from './../AnimationData/treeStructure';

// Tree and Link are two new components used by HalfwayFinishedStructureAnimation.
import Tree from './Tree';
import Link from './Link';

var d3 = require('d3');
var ReactDOM = require('react-dom');

// My goal in creating HalfwayFinishedStructureAnimation was to make React responsible for DOM structure (adding and removing elements) and to make D3 responsible for styling, as described in this blog post:
// https://medium.com/@sxywu/on-d3-react-and-a-little-bit-of-flux-88a226f328f3#.ztcxqykek

// We still need to handle window resizes. Here are some useful resources:
// http://eyeseast.github.io/visible-data/2013/08/28/responsive-charts-with-d3/
// http://bl.ocks.org/mbostock/3019563

export default class HalfwayFinishedStructureAnimation extends Component {

  constructor(props) {
    super(props);
    this.state = {
      treeData: props.initialTreeData,
      margin: props.initialMargin,
      treeWidth: props.initialTreeWidth,
      treeHeight: props.initialTreeHeight,
      windowWidth: props.initialWindowWidth,
      windowHeight: props.initialWindowHeight
    }
  }

  // This function is called after all the Tree and Link componentDidMount functions have been called.
  componentDidMount() {
    ipcRenderer.on('direc-schema', (e,arg)=>{
      this.updateTreeData(arg);
    })

    // Reset the tree height and width if needed?
    // Would it be better to use a ref rather than an id?
  }

  updateTreeData(newSchema) {
    this.setState({
      treeData: newSchema
    });
  }

  render() {
    var duration = 450; // We may want to make this a prop.

    // Create a tree layout.
    var tree = d3.layout.tree()
    // The first argument below is the maximum x-coordinate D3 will assign.
    // The second argument is the maximum y-coordinate.
    // We're switching width and height here because d3 by default makes trees that branch vertically, and we want a tree that branches horizontally.
    // In other words, nodes that are on the same level will have the same y-coordinate but different x-coordinates.
      .size([this.state.treeHeight, this.state.treeWidth]);

    // Create a diagonal generator, a type of path data generator.
    var diagonal = d3.svg.diagonal()
    // Isaac: I don't completely understand the projection yet.
      .projection(function(d) { return [d.y, d.x]; });

    // We know that the first node in the array is the root of the tree. Let's designate its initial coordinates - where it should enter.
    var root = this.state.treeData[0];
    root.x0 = this.state.treeHeight / 2;
    root.y0 = 0;

    // The next line creates and returns an array of nodes associated with the specified root node. (The returned array is basically a flattened version of treeData.)
    // D3 tree nodes always have parent, child, depth, x, and y properties.
    // Before the next line runs, each node has children, level, name, and value properties.
    // After the next line runs, each node also has parent, depth, x, and y properties.
    // We will pass one node from this array to each Tree as props.data.
    // ***Do we want to end the next line with reverse to put the root node at the end?
    var nodes = tree.nodes(root),
      // This line creates and returns an array of objects representing all parent-child links in the nodes array we just created.
      linkSelection = tree.links(nodes);

    nodes.forEach(function(d) {
      // The default y-coordinates provided by d3.tree will make the tree stretch all the way across the screen.
      // We want to compress the tree a bit so that there's room for file/directory names to the right of the deepest level.
      d.y *= .8;

      // We could scale d.x too to prevent the svg from cutting off notes at the top and bottom of a node column.

      // If the node has a parent, set the node's initial coordinates to the parent's initial coordinates.
      // *** Does this make sense?
      if (d.parent) {
        d.x0 = d.parent.x0;
        d.y0 = d.parent.y0;
      }
    });

    // I think it makes sense to the use target.name as an id, because no two links should ever point to the same target.
    // If needed, though, we could use {link.source.name + '/'  link.target.name} instead.
    var links = linkSelection && linkSelection.map((link) => {
      return (<Link key={link.target.name} data={link} diagonal={diagonal} duration={duration} />)
    });

    var trees = nodes && nodes.map((node) => {
      return (<Tree key={node.name} data={node} duration={duration} />);
    });

    console.log('Rendering. Latest update: I think I want to save this.');
    // I need to size the SVG so that it fits the desired space.
    // Then I need to size the tree to fit the SVG.

    var viewBoxWidth = this.state.windowWidth * 7 / 12; // was 660
    var viewBoxHeight = this.state.windowHeight * 7 / 24; // was 300
    var viewBoxString = `0 0 ${viewBoxWidth} ${viewBoxHeight}`;
    console.log('viewBoxString', viewBoxString);

    var translationValue = `translate(${this.state.margin.left}, ${this.state.margin.top})`;

    // Removed links and trees.
    return(

        <svg viewBox={viewBoxString}>
          <g transform={translationValue}>
            <rect x='0' y='0' width={viewBoxWidth - this.state.margin.left} height={viewBoxHeight} rx='15' ry='15'/>
          </g>
        </svg>

    )
  }
}

HalfwayFinishedStructureAnimation.defaultProps = {
  initialTreeData: treeData, // To start with an empty tree: [{}]
  initialMargin: {top: 0, right: 20, bottom: 0, left: 90},
  initialTreeWidth: 660 * .9, // was 550
  initialTreeHeight: 300 * .9, // was 200
  // The initial window dimensions are specified in app.on('ready') in main.js.
  initialWindowWidth: 1200,
  initialWindowHeight: 700
}
<|endoftext|>


<commit_before>Ext.define('devilry.statistics.FilterEditor', {
    extend: 'Ext.tab.Panel',
    alias: 'widget.statistics-filtereditor',
    requires: [
        'devilry.statistics.MustPassEditor',
        'devilry.statistics.PointSpecEditor'
    ],

    config: {
        assignment_store: undefined
    },

    constructor: function(config) {
        this.callParent([config]);
        this.initConfig(config);
    },

    initComponent: function() {
        Ext.apply(this, {
            items: [{
                xtype: 'statistics-mustpasseditor',
                title: 'Must pass',
                assignment_store: this.assignment_store
            }, {
                xtype: 'statistics-pointspeceditor',
                title: 'Must have points',
                assignment_store: this.assignment_store
            }],

            bbar: ['->', {
                xtype: 'button',
                text: 'Save label',
                iconCls: 'icon-save-32',
                scale: 'large'
            }]
        });
        this.callParent(arguments);
    }
});
<commit_msg>apps.statistics: Minor changes<commit_after>Ext.define('devilry.statistics.FilterEditor', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.statistics-filtereditor',
    requires: [
        'devilry.statistics.MustPassEditor',
        'devilry.statistics.PointSpecEditor'
    ],

    config: {
        assignment_store: undefined
    },

    constructor: function(config) {
        this.callParent([config]);
        this.initConfig(config);
    },

    initComponent: function() {
        Ext.apply(this, {
            items: [{
                xtype: 'box',
                html: 'Test'
            }, {
                xtype: 'tabpanel',
                items: [{
                    xtype: 'statistics-mustpasseditor',
                    title: 'Must pass',
                    assignment_store: this.assignment_store
                }, {
                    xtype: 'statistics-pointspeceditor',
                    title: 'Must have points',
                    assignment_store: this.assignment_store
                }]
            }],

            bbar: ['->', {
                xtype: 'button',
                text: 'Save label',
                iconCls: 'icon-save-32',
                scale: 'large'
            }]
        });
        this.callParent(arguments);
    }
});
<|endoftext|>


<commit_before>angular.module('leukemiapp').controller('pdfController', PdfViewerController);

function PdfViewerController($scope, $reactive, $ionicPopup) {
   $reactive(this).attach($scope);
   var vm = this;

   vm.clickTester = () => {
      console.log('Click registered.');
   };

   vm.openUrl = (url) => {
      if (Meteor.isCordova) {
         $ionicPopup.alert({
            title: 'Funktion ikke tilgængelig',
            content: 'Denne funktion er kun tilgængelig på leukemia.meteorapp.com'
         });
      } else {
         window.open(url, "_blank");
      }
   }
}<commit_msg>Changed popup text<commit_after>angular.module('leukemiapp').controller('pdfController', PdfViewerController);

function PdfViewerController($scope, $reactive, $ionicPopup) {
   $reactive(this).attach($scope);
   var vm = this;

   vm.clickTester = () => {
      console.log('Click registered.');
   };

   vm.openUrl = (url) => {
      if (Meteor.isCordova) {
         $ionicPopup.alert({
            title: 'Funktion ikke tilgængelig',
            content: 'Denne funktion er kun tilgængelig på howryou.meteorapp.com'
         });
      } else {
         window.open(url, "_blank");
      }
   }
}<|endoftext|>


<commit_before>
import React from "react-native";

const {
  View,
  Text,
  StyleSheet,
  Navigator,
  TouchableOpacity,
  ScrollView,
  ListView
} = React;

class StartClassView extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      classes: [{id: 1, name:'Quick Class'}, {id:2, name:'CS 101'}, {id:3, name: 'CS 201'}],
    };
  }

  selectClass(classId) {
    api.getLessons(classId)
    .then((response) => {
      if(response.status === 500){
        console.error('err getting class data');
      } else if(response.status === 200) {
        var lessons = JSON.parse(response._bodyText);

        this.socket = io(server, {jsonp: false});
        this.socket.emit('teacherConnect' , {classId: classId});

        this.props.navigator.push({
          component: SelectLessonView,
          classId: classId,
          lessons: lessons,
          socket: this.socket,
          sceneConfig: {
            ...Navigator.SceneConfigs.FloatFromRight,
            gestures: {}
          }
        });
      }
    })
    .catch((err) => {
      console.error(err);
    });
  }

  renderClasses(classes) {
    return classes.map((cls, index) => {
      return (
        <View style={styles.buttonContainer} key={index}>
          <TouchableOpacity onPress={this.selectClass.bind(this, cls.id)} style={styles.button}>
            <Text style={styles.buttonText}> {cls.name} </Text>
          </TouchableOpacity>
        </View>
      )
    })
  }

  render() {
    return (
      <View style={{flex: 1, backgroundColor: '#ededed'}}>
        <View style={styles.viewContainer}>
          <View style={styles.titleContainer}>
            <Text style={styles.pageText}> Your classes </Text>
          </View>
          <ScrollView>
            <View style={styles.buttonsContainer}>
              {this.renderClasses(this.state.classes)}
            </View>
          </ScrollView>
        </View>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  viewContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  pageText: {
    fontSize: 20
  },
  buttonsContainer: {
    padding: 20
  },
  buttonContainer: {
    margin: 20
  },
  button: {

  },
  buttonText: {
    fontSize: 20
  }
});<commit_msg>Use fafafa for background white<commit_after>
import React from "react-native";

const {
  View,
  Text,
  StyleSheet,
  Navigator,
  TouchableOpacity,
  ScrollView,
  ListView
} = React;

class StartClassView extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      classes: [{id: 1, name:'Quick Class'}, {id:2, name:'CS 101'}, {id:3, name: 'CS 201'}],
    };
  }

  selectClass(classId) {
    api.getLessons(classId)
    .then((response) => {
      if(response.status === 500){
        console.error('err getting class data');
      } else if(response.status === 200) {
        var lessons = JSON.parse(response._bodyText);

        this.socket = io(server, {jsonp: false});
        this.socket.emit('teacherConnect' , {classId: classId});

        this.props.navigator.push({
          component: SelectLessonView,
          classId: classId,
          lessons: lessons,
          socket: this.socket,
          sceneConfig: {
            ...Navigator.SceneConfigs.FloatFromRight,
            gestures: {}
          }
        });
      }
    })
    .catch((err) => {
      console.error(err);
    });
  }

  renderClasses(classes) {
    return classes.map((cls, index) => {
      return (
        <View style={styles.buttonContainer} key={index}>
          <TouchableOpacity onPress={this.selectClass.bind(this, cls.id)} style={styles.button}>
            <Text style={styles.buttonText}> {cls.name} </Text>
          </TouchableOpacity>
        </View>
      )
    })
  }

  render() {
    return (
      <View style={{flex: 1, backgroundColor: '#ededed'}}>
        <View style={styles.viewContainer}>
          <View style={styles.titleContainer}>
            <Text style={styles.pageText}> Your classes </Text>
          </View>
          <ScrollView>
            <View style={styles.buttonsContainer}>
              {this.renderClasses(this.state.classes)}
            </View>
          </ScrollView>
        </View>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  viewContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fafafa',
  },
  pageText: {
    fontSize: 20
  },
  buttonsContainer: {
    padding: 20
  },
  buttonContainer: {
    margin: 20
  },
  button: {

  },
  buttonText: {
    fontSize: 20
  }
});<|endoftext|>


<commit_before>angular.module('authController', ['ngStorage'])
.controller('LoginCtrl', ['$scope', '$http', '$localStorage', 'authFactory', function($scope, $http, $localStorage, authFactory){
    $scope.userData = {};
    $scope.skillData = {};
    $scope.loginData = {};

    var profileData = {user: $scope.userData, skills: $scope.skillData};

    $scope.signup = function () {
      authFactory.signup(profileData)
      .success(signupSuccessCallback)
      .error(signupErrorCallback);
    };

    function signupSuccessCallback (data, status, headers, config) {
      $localStorage.user = data.user;
      $localStorage.token = data.token;
    }

    function signupErrorCallback (data, status, headers, config) {
      console.log('error:', status);
    }

    $scope.login = function(){
      authFactory.login($scope.loginData)
      .success(loginSuccessCallback)
      .error(loginErrorCallback);
    };

    function loginSuccessCallback (data, status, headers, config){
      console.log(data);
    }
    function loginErrorCallback (data, status, headers, config) {
      console.log('error:', status);
    }

    // Landing Page Tab Controls
    $scope.tabData = {
      selectedIndex : 0,
      signupTabIndex : 0
    };

    $scope.nextTab = function() {
      $scope.tabData.selectedIndex = Math.min($scope.tabData.selectedIndex + 1, 2) ;
    };
    $scope.previousTab = function() {
      $scope.tabData.selectedIndex = Math.max($scope.tabData.selectedIndex - 1, 0);
    };

    $scope.nextInnerTab = function() {
      $scope.tabData.signupTabIndex = Math.min($scope.tabData.signupTabIndex + 1, 2) ;
    };
    $scope.previousInnerTab = function() {
      $scope.tabData.signupTabIndex = Math.max($scope.tabData.signupTabIndex - 1, 0);
    };
}]);<commit_msg>removes ngstorage dependency from authcontroller<commit_after>angular.module('authController', [])
.controller('LoginCtrl', ['$scope', '$http', '$localStorage', 'authFactory', function($scope, $http, $localStorage, authFactory){
    $scope.userData = {};
    $scope.skillData = {};
    $scope.loginData = {};

    var profileData = {user: $scope.userData, skills: $scope.skillData};

    $scope.signup = function () {
      authFactory.signup(profileData)
      .success(signupSuccessCallback)
      .error(signupErrorCallback);
    };

    function signupSuccessCallback (data, status, headers, config) {
      $localStorage.user = data.user;
      $localStorage.token = data.token;
    }

    function signupErrorCallback (data, status, headers, config) {
      console.log('error:', status);
    }

    $scope.login = function(){
      authFactory.login($scope.loginData)
      .success(loginSuccessCallback)
      .error(loginErrorCallback);
    };

    function loginSuccessCallback (data, status, headers, config){
      console.log(data);
    }
    function loginErrorCallback (data, status, headers, config) {
      console.log('error:', status);
    }

    // Landing Page Tab Controls
    $scope.tabData = {
      selectedIndex : 0,
      signupTabIndex : 0
    };

    $scope.nextTab = function() {
      $scope.tabData.selectedIndex = Math.min($scope.tabData.selectedIndex + 1, 2) ;
    };
    $scope.previousTab = function() {
      $scope.tabData.selectedIndex = Math.max($scope.tabData.selectedIndex - 1, 0);
    };

    $scope.nextInnerTab = function() {
      $scope.tabData.signupTabIndex = Math.min($scope.tabData.signupTabIndex + 1, 2) ;
    };
    $scope.previousInnerTab = function() {
      $scope.tabData.signupTabIndex = Math.max($scope.tabData.signupTabIndex - 1, 0);
    };
}]);<|endoftext|>