<commit_before>require('should');

describe('synth-di', function () {
  var DI = require('../');
  var di;

  beforeEach(function () {
    di = new DI();
  });

  describe('#register', function () {
    it('registers services with name given as string', function () {
      di.register('aService', function () {});
      di.services[0].name.should.eql('aService');
    });

    it('registers services with name taken from function', function () {
      di.register(function aService () {});
      di.register(function anotherService(params) { return "stuff"; });
      di.services[0].name.should.eql('aService');
      di.services[1].name.should.eql('anotherService');
    });
  });

  describe('#exec', function () {
    var di;
    beforeEach(function () {
      di = new DI();
      di.register(function truth () { return true; });
      di.register(function justice() { return 'just'; });
      di.register(function superman(truth, justice) {
        return truth + ' and ' + justice;
      });
    });

    it('uses registered services', function () {
      return di.exec('superman').then(function (res) {
        res.should.eql('true and just');
      });
    });

    it('uses given services when executed', function () {
      return di.exec('superman', {
        justice: 'just and undocumented American'
      }).then(function (res) {
        res.should.eql('true and just and undocumented American');
      });
    });

    it('calls a given service only once', function () {
      var batarangs = 0;
      di.register(function smokePellet (batarang) {
        return batarang;
      });
      di.register(function batarang () {
        batarangs++;
        return "Bang";
      });
      return di.exec(function batman (batarang, smokePellet) {
        return batarang + " " + smokePellet;
      }).then(function (res) {
        res.should.eql("Bang Bang");
        batarangs.should.eql(1);
      });
    });

    it('throws when cycle occurs', function () {
      di.register(function justice (truth) { return 'just'; });
      di.register(function truth (justice) { return true; });
      (function () {
        di.exec('superman');
      }).should.throw("Maximum call stack size exceeded");
    });
  });
});
<commit_msg>Add missing promises spec<commit_after>require('should');

describe('synth-di', function () {
  var DI = require('../');
  var di;

  beforeEach(function () {
    di = new DI();
  });

  describe('#register', function () {
    it('registers services with name given as string', function () {
      di.register('aService', function () {});
      di.services[0].name.should.eql('aService');
    });

    it('registers services with name taken from function', function () {
      di.register(function aService () {});
      di.register(function anotherService(params) { return "stuff"; });
      di.services[0].name.should.eql('aService');
      di.services[1].name.should.eql('anotherService');
    });
  });

  describe('#exec', function () {
    var di;
    beforeEach(function () {
      di = new DI();
      di.register(function truth () { return true; });
      di.register(function justice() { return 'just'; });
      di.register(function superman(truth, justice) {
        return truth + ' and ' + justice;
      });
    });

    it('uses registered services', function () {
      return di.exec('superman').then(function (res) {
        res.should.eql('true and just');
      });
    });

    it('uses given services when executed', function () {
      return di.exec('superman', {
        justice: 'just and undocumented American'
      }).then(function (res) {
        res.should.eql('true and just and undocumented American');
      });
    });

    it('calls a given service only once', function () {
      var batarangs = 0;
      di.register(function smokePellet (batarang) {
        return batarang;
      });
      di.register(function batarang () {
        batarangs++;
        return "Bang";
      });
      return di.exec(function batman (batarang, smokePellet) {
        return batarang + " " + smokePellet;
      }).then(function (res) {
        res.should.eql("Bang Bang");
        batarangs.should.eql(1);
      });
    });

    it.only('works with promises', function () {
      var Promise = require('bluebird');

      return di.exec(function (justice, truth) {
        return Promise.delay(truth + " and " + justice, 0);
      }).then(function (res) {
        res.should.eql("true and just");
      });
    });

    it('throws when cycle occurs', function () {
      di.register(function justice (truth) { return 'just'; });
      di.register(function truth (justice) { return true; });
      (function () {
        di.exec('superman');
      }).should.throw("Maximum call stack size exceeded");
    });
  });
});
<|endoftext|>


<commit_before>
/*********************************
 * GENERATING REGEXPS AND INPUTS *
 *********************************/

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

// The basic data structure returned by most of the regex* functions is a tuple:
//   [ regex string, array of potential matches ]
// For example:
//   ["a|b*", ["a", "b", "bbbb", "", "c"]]
// These functions work together recursively to build up a regular expression
// along with input strings.

// This paradigm works well for the recursive nature of most regular expression components,
// but breaks down when we encounter lookahead assertions or backrefs (\1).

// How many potential matches to create per regexp
var POTENTIAL_MATCHES = 10;

// Stored captures
var backrefHack = [];
for (var i = 0; i < POTENTIAL_MATCHES; ++i) {
  backrefHack[i] = "";
}

function regexNumberOfMatches()
{
  if (rnd(10))
    return rnd(5);
  return Math.pow(2, rnd(40)) + rnd(3) - 1;
}

function regexPattern(depth, parentWasQuantifier)
{
  if (depth == 0 || (rnd(depth) == 0))
    return regexTerm();

  var dr = depth - 1;

  var index = rnd(regexMakers.length);
  if (parentWasQuantifier && rnd(30)) index = rnd(regexMakers.length - 1) + 1; // avoid double quantifiers
  return (Random.index(regexMakers[index]))(dr);
}

var regexMakers =
[
  [
    // Quantifiers
    function(dr) { return regexQuantified(dr, "+", 1, rnd(10)); },
    function(dr) { return regexQuantified(dr, "*", 0, rnd(10)); },
    function(dr) { return regexQuantified(dr, "?", 0, 1); },
    function(dr) { return regexQuantified(dr, "+?", 1, 1); },
    function(dr) { return regexQuantified(dr, "*?", 0, 1); },
    function(dr) { var x = regexNumberOfMatches(); return regexQuantified(dr, "{" + x + "}", x, x); },
    function(dr) { var x = regexNumberOfMatches(); return regexQuantified(dr, "{" + x + ",}", x, x + rnd(10)); },
    function(dr) { var min = regexNumberOfMatches(); var max = min + regexNumberOfMatches(); return regexQuantified(dr, "{" + min + "," + max + "}", min, max); }
  ],
  [
    // Combinations: concatenation, disjunction
    function(dr) { return regexConcatenation(dr); },
    function(dr) { return regexDisjunction(dr); }
  ],
  [
    // Grouping
    function(dr) { return ["\\" + (rnd(3) + 1), backrefHack.slice(0)]; }, // backref
    function(dr) { return regexGrouped("(", dr, ")");   }, // capturing: feeds \1 and exec() result
    function(dr) { return regexGrouped("(?:", dr, ")"); }, // non-capturing
    function(dr) { return regexGrouped("(?=", dr, ")"); }, // lookahead
    function(dr) { return regexGrouped("(?!", dr, ")"); }  // lookahead(not)
  ]
];

function quantifierHelper(pm, min, max, pms)
{
  var repeats = Math.min(min + rnd(max - min + 5) - 2, 10);
  var returnValue = "";
  for (var i = 0; i < repeats; i++)
  {
    if (rnd(100) < 80)
      returnValue = returnValue + pm;
    else
      returnValue = returnValue + Random.index(pms);
  }
  return returnValue;
}

function regexQuantified(dr, operator, min, max)
{
  var [re, pms] = regexPattern(dr, true);
  var newpms = [];
  for (var i = 0; i < POTENTIAL_MATCHES; i++)
    newpms[i] = quantifierHelper(pms[i], min, max, pms);
  return [re + operator, newpms];
}

function regexConcatenation(dr)
{
  var [re1, strings1] = regexPattern(dr, false);
  var [re2, strings2] = regexPattern(dr, false);
  var newStrings = [];

  for (var i = 0; i < POTENTIAL_MATCHES; i++)
  {
    var chance = rnd(100);
    if (chance < 10)
      newStrings[i] = "";
    else if (chance < 20)
      newStrings[i] = strings1[i];
    else if (chance < 30)
      newStrings[i] = strings2[i];
    else if (chance < 65)
      newStrings[i] = strings1[i] + strings2[i];
    else
      newStrings[i] = Random.index(strings1) + Random.index(strings2);
  }

  return [re1 + re2, newStrings];
}

function regexDisjunction(dr)
{
  var [re1, strings1] = regexPattern(dr, false);
  var [re2, strings2] = regexPattern(dr, false);
  var newStrings = [];

  for (var i = 0; i < POTENTIAL_MATCHES; i++)
  {
    var chance = rnd(100);
    if (chance < 10)
      newStrings[i] = "";
    else if (chance < 20)
      newStrings[i] = Random.index(strings1) + Random.index(strings2);
    else if (chance < 60)
      newStrings[i] = strings1[i];
    else
      newStrings[i] = strings2[i];
  }
  return [re1 + "|" + re2, newStrings];
}

function regexGrouped(prefix, dr, postfix)
{
  var [re, strings] = regexPattern(dr, false);
  var newStrings = [];
  for (var i = 0; i < POTENTIAL_MATCHES; ++i) {
    newStrings[i] = rnd(5) ? strings[i] : "";
    if (prefix == "(" && strings[i].length < 40 && rnd(3) === 0) {
      backrefHack[i] = strings[i];
    }
  }
  return [prefix + re + postfix, newStrings];
}

var letters =
["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
 "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];

var hexDigits = [
  "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
  "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
  "a", "b", "c", "d", "e", "f",
  "A", "B", "C", "D", "E", "F"
];

function regexTerm()
{
  var [re, oneString] = regexTermPair();
  var strings = [];
  for (var i = 0; i < POTENTIAL_MATCHES; ++i) {
    strings[i] = rnd(5) ? oneString : regexTermPair()[1];
  }
  return [re, strings];
}

function regexCharCode()
{
  return rnd(2) ? rnd(256) : rnd(65536);
}

// These return matching pairs: [regex fragment, charcode for a matching one-character string].
var regexCharacterMakers = Random.weighted([
  // Possibly incorrect
  { w:20, v: function() { var cc = regexCharCode(); return [       String.fromCharCode(cc), cc]; } }, // literal that doesn't need to be escaped (OR wrong)
  { w: 4, v: function() { var cc = regexCharCode(); return ["\\" + String.fromCharCode(cc), cc]; } }, // escaped special character OR unnecessary escape (OR wrong)
  { w: 1, v: function() { return ["\\0",  0]; } },  // null [ignoring the "do not follow this with another digit" rule which would turn it into an octal escape]
  { w: 1, v: function() { return ["\\B", 66]; } },  // literal B -- ONLY within a character class. (Elsewhere, it's a "zero-width non-word boundary".)
  { w: 1, v: function() { return ["\\b",  8]; } },  // backspace -- ONLY within a character class. (Elsewhere, it's a "zero-width word boundary".)

  // Correct, unless I screwed up
  { w: 1, v: function() { return ["\\t",  9]; } },  // tab
  { w: 1, v: function() { return ["\\n", 10]; } },  // line break
  { w: 1, v: function() { return ["\\v", 11]; } },  // vertical tab
  { w: 1, v: function() { return ["\\f", 12]; } },  // form feed
  { w: 1, v: function() { return ["\\r", 13]; } },  // carriage return
  { w: 5, v: function() { var controlCharacterCode = rnd(26) + 1; return ["\\c" + String.fromCharCode(64 + controlCharacterCode), controlCharacterCode]; } },
  //{ w: 5, v: function() { var cc = regexCharCode(); return ["\\0" + cc.toString(8), cc] } }, // octal escape
  { w: 5, v: function() { var twoHex = Random.index(hexDigits) + Random.index(hexDigits); return ["\\x" + twoHex, parseInt(twoHex, 16)]; } },
  { w: 5, v: function() { var twoHex = Random.index(hexDigits) + Random.index(hexDigits); return ["\\u00" + twoHex, parseInt(twoHex, 16)]; } },
  { w: 5, v: function() { var fourHex = Random.index(hexDigits) + Random.index(hexDigits) + Random.index(hexDigits) + Random.index(hexDigits); return ["\\u" + fourHex, parseInt(fourHex, 16)]; } },
]);

function regexCharacter()
{
  var [matcher, charcode] = Random.index(regexCharacterMakers)();
  switch(rnd(10)) {
    case 0:  return [matcher, charcode + 32]; // lowercase
    case 1:  return [matcher, charcode - 32]; // uppercase
    case 2:  return [matcher, regexCharCode()]; // some other character
    default: return [matcher, charcode];
  }
}

var regexBuiltInCharClasses = [
    "\\d", "\\D", // digit
    "\\s", "\\S", // space
    "\\w", "\\W", // "word" character (alphanumeric plus underscore)
];

// Returns POTENTIAL_MATCHES one-character strings, mostly consisting of the input characters
function regexOneCharStringsWith(frequentChars) {
  var matches = [];
  for (var i = 0; i < POTENTIAL_MATCHES; ++i) {
    matches.push(rnd(8) ? Random.index(frequentChars) : String.fromCharCode(regexCharCode()));
  }
  return matches;
}

// Returns POTENTIAL_MATCHES short strings, using the input characters a lot.
function regexShortStringsWith(frequentChars) {
  var matches = [];
  for (var i = 0; i < POTENTIAL_MATCHES; ++i) {
    var s = "";
    while (rnd(3)) {
      s += rnd(4) ? Random.index(frequentChars) : String.fromCharCode(regexCharCode());
    }
    matches.push(s);
  }
  return matches;
}

var regexTermMakers =
  [
    function() { return regexCharacterClass(); },
    function() { var [re, cc] = regexCharacter();   return [re, regexOneCharStringsWith([String.fromCharCode(cc)])]; },
    function() { return [Random.index(regexBuiltInCharClasses), regexOneCharStringsWith(["0", "a", "_"])]; },
    function() { return ["[^]",                                 regexOneCharStringsWith(["\n"])];     },
    function() { return [".",                                   regexOneCharStringsWith(["\n"])];     },
    function() { return [Random.index(["^", "$"]),              regexShortStringsWith(["\n"])];     },            // string boundaries or line boundaries (with /m)
    function() { return [Random.index(["\\b", "\\B"]),          regexShortStringsWith([" ", "\n", "a", "1"])]; }, // word boundaries
  ];

function regexTerm()
{
  return Random.index(regexTermMakers)();
}

// Returns a pair: [(regex char class), (POTENTIAL_MATCHES number of strings that might match)]
// e.g. ["[a-z0-9]", ["a", "8", ...]]
function regexCharacterClass()
{
  var ranges = rnd(5);
  var inRange = rnd(2);
  var charBucket = [String.fromCharCode(regexCharCode())]; // from which potenial matches will be drawn

  var re = "[";
  if (!inRange) {
    re += "^";
  }

  for (var i = 0; i < ranges; ++i) {
    if (rnd(100) == 0) {
      // Confuse things by tossing in an extra "-"
      re += "-";
      if (rnd(2)) {
        re += String.fromCharCode(regexCharCode());
      }
    }

    if (rnd(3) == 1) {
      // Add a built-in class, like "\d"
      re += Random.index(regexBuiltInCharClasses);
      charBucket.push("a");
      charBucket.push("0");
      charBucket.push("_");
    } else if (rnd(2)) {
      // Add a range, like "a-z"
      var a = regexCharacter();
      var b = regexCharacter();
      if ((a[1] <= b[1]) == !!rnd(10)) {
        [lo, hi] = [a, b];
      } else {
        [lo, hi] = [b, a];
      }

      re += lo[0] + "-" + hi[0];
      charBucket.push(String.fromCharCode(lo[1] + rnd(3) - 1));
      charBucket.push(String.fromCharCode(hi[1] + rnd(3) - 1));
      charBucket.push(String.fromCharCode(lo[1] + rnd(Math.max(hi[1] - lo[1], 1)))); // something in the middle
    } else {
      // Add a single character
      var a = regexCharacter();
      re += a[0];
      charBucket.push(String.fromCharCode(a[1]));
    }
  }

  re += "]";
  return [re, pickN(charBucket, POTENTIAL_MATCHES)];
}

function pickN(bucket, picks)
{
  var picked = [];
  for (var i = 0; i < picks; ++i) {
    picked.push(Random.index(bucket));
  }
  return picked;
}
<commit_msg>Declare variables<commit_after>
/*********************************
 * GENERATING REGEXPS AND INPUTS *
 *********************************/

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

// The basic data structure returned by most of the regex* functions is a tuple:
//   [ regex string, array of potential matches ]
// For example:
//   ["a|b*", ["a", "b", "bbbb", "", "c"]]
// These functions work together recursively to build up a regular expression
// along with input strings.

// This paradigm works well for the recursive nature of most regular expression components,
// but breaks down when we encounter lookahead assertions or backrefs (\1).

// How many potential matches to create per regexp
var POTENTIAL_MATCHES = 10;

// Stored captures
var backrefHack = [];
for (var i = 0; i < POTENTIAL_MATCHES; ++i) {
  backrefHack[i] = "";
}

function regexNumberOfMatches()
{
  if (rnd(10))
    return rnd(5);
  return Math.pow(2, rnd(40)) + rnd(3) - 1;
}

function regexPattern(depth, parentWasQuantifier)
{
  if (depth == 0 || (rnd(depth) == 0))
    return regexTerm();

  var dr = depth - 1;

  var index = rnd(regexMakers.length);
  if (parentWasQuantifier && rnd(30)) index = rnd(regexMakers.length - 1) + 1; // avoid double quantifiers
  return (Random.index(regexMakers[index]))(dr);
}

var regexMakers =
[
  [
    // Quantifiers
    function(dr) { return regexQuantified(dr, "+", 1, rnd(10)); },
    function(dr) { return regexQuantified(dr, "*", 0, rnd(10)); },
    function(dr) { return regexQuantified(dr, "?", 0, 1); },
    function(dr) { return regexQuantified(dr, "+?", 1, 1); },
    function(dr) { return regexQuantified(dr, "*?", 0, 1); },
    function(dr) { var x = regexNumberOfMatches(); return regexQuantified(dr, "{" + x + "}", x, x); },
    function(dr) { var x = regexNumberOfMatches(); return regexQuantified(dr, "{" + x + ",}", x, x + rnd(10)); },
    function(dr) { var min = regexNumberOfMatches(); var max = min + regexNumberOfMatches(); return regexQuantified(dr, "{" + min + "," + max + "}", min, max); }
  ],
  [
    // Combinations: concatenation, disjunction
    function(dr) { return regexConcatenation(dr); },
    function(dr) { return regexDisjunction(dr); }
  ],
  [
    // Grouping
    function(dr) { return ["\\" + (rnd(3) + 1), backrefHack.slice(0)]; }, // backref
    function(dr) { return regexGrouped("(", dr, ")");   }, // capturing: feeds \1 and exec() result
    function(dr) { return regexGrouped("(?:", dr, ")"); }, // non-capturing
    function(dr) { return regexGrouped("(?=", dr, ")"); }, // lookahead
    function(dr) { return regexGrouped("(?!", dr, ")"); }  // lookahead(not)
  ]
];

function quantifierHelper(pm, min, max, pms)
{
  var repeats = Math.min(min + rnd(max - min + 5) - 2, 10);
  var returnValue = "";
  for (var i = 0; i < repeats; i++)
  {
    if (rnd(100) < 80)
      returnValue = returnValue + pm;
    else
      returnValue = returnValue + Random.index(pms);
  }
  return returnValue;
}

function regexQuantified(dr, operator, min, max)
{
  var [re, pms] = regexPattern(dr, true);
  var newpms = [];
  for (var i = 0; i < POTENTIAL_MATCHES; i++)
    newpms[i] = quantifierHelper(pms[i], min, max, pms);
  return [re + operator, newpms];
}

function regexConcatenation(dr)
{
  var [re1, strings1] = regexPattern(dr, false);
  var [re2, strings2] = regexPattern(dr, false);
  var newStrings = [];

  for (var i = 0; i < POTENTIAL_MATCHES; i++)
  {
    var chance = rnd(100);
    if (chance < 10)
      newStrings[i] = "";
    else if (chance < 20)
      newStrings[i] = strings1[i];
    else if (chance < 30)
      newStrings[i] = strings2[i];
    else if (chance < 65)
      newStrings[i] = strings1[i] + strings2[i];
    else
      newStrings[i] = Random.index(strings1) + Random.index(strings2);
  }

  return [re1 + re2, newStrings];
}

function regexDisjunction(dr)
{
  var [re1, strings1] = regexPattern(dr, false);
  var [re2, strings2] = regexPattern(dr, false);
  var newStrings = [];

  for (var i = 0; i < POTENTIAL_MATCHES; i++)
  {
    var chance = rnd(100);
    if (chance < 10)
      newStrings[i] = "";
    else if (chance < 20)
      newStrings[i] = Random.index(strings1) + Random.index(strings2);
    else if (chance < 60)
      newStrings[i] = strings1[i];
    else
      newStrings[i] = strings2[i];
  }
  return [re1 + "|" + re2, newStrings];
}

function regexGrouped(prefix, dr, postfix)
{
  var [re, strings] = regexPattern(dr, false);
  var newStrings = [];
  for (var i = 0; i < POTENTIAL_MATCHES; ++i) {
    newStrings[i] = rnd(5) ? strings[i] : "";
    if (prefix == "(" && strings[i].length < 40 && rnd(3) === 0) {
      backrefHack[i] = strings[i];
    }
  }
  return [prefix + re + postfix, newStrings];
}

var letters =
["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
 "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];

var hexDigits = [
  "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
  "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
  "a", "b", "c", "d", "e", "f",
  "A", "B", "C", "D", "E", "F"
];

function regexTerm()
{
  var [re, oneString] = regexTermPair();
  var strings = [];
  for (var i = 0; i < POTENTIAL_MATCHES; ++i) {
    strings[i] = rnd(5) ? oneString : regexTermPair()[1];
  }
  return [re, strings];
}

function regexCharCode()
{
  return rnd(2) ? rnd(256) : rnd(65536);
}

// These return matching pairs: [regex fragment, charcode for a matching one-character string].
var regexCharacterMakers = Random.weighted([
  // Possibly incorrect
  { w:20, v: function() { var cc = regexCharCode(); return [       String.fromCharCode(cc), cc]; } }, // literal that doesn't need to be escaped (OR wrong)
  { w: 4, v: function() { var cc = regexCharCode(); return ["\\" + String.fromCharCode(cc), cc]; } }, // escaped special character OR unnecessary escape (OR wrong)
  { w: 1, v: function() { return ["\\0",  0]; } },  // null [ignoring the "do not follow this with another digit" rule which would turn it into an octal escape]
  { w: 1, v: function() { return ["\\B", 66]; } },  // literal B -- ONLY within a character class. (Elsewhere, it's a "zero-width non-word boundary".)
  { w: 1, v: function() { return ["\\b",  8]; } },  // backspace -- ONLY within a character class. (Elsewhere, it's a "zero-width word boundary".)

  // Correct, unless I screwed up
  { w: 1, v: function() { return ["\\t",  9]; } },  // tab
  { w: 1, v: function() { return ["\\n", 10]; } },  // line break
  { w: 1, v: function() { return ["\\v", 11]; } },  // vertical tab
  { w: 1, v: function() { return ["\\f", 12]; } },  // form feed
  { w: 1, v: function() { return ["\\r", 13]; } },  // carriage return
  { w: 5, v: function() { var controlCharacterCode = rnd(26) + 1; return ["\\c" + String.fromCharCode(64 + controlCharacterCode), controlCharacterCode]; } },
  //{ w: 5, v: function() { var cc = regexCharCode(); return ["\\0" + cc.toString(8), cc] } }, // octal escape
  { w: 5, v: function() { var twoHex = Random.index(hexDigits) + Random.index(hexDigits); return ["\\x" + twoHex, parseInt(twoHex, 16)]; } },
  { w: 5, v: function() { var twoHex = Random.index(hexDigits) + Random.index(hexDigits); return ["\\u00" + twoHex, parseInt(twoHex, 16)]; } },
  { w: 5, v: function() { var fourHex = Random.index(hexDigits) + Random.index(hexDigits) + Random.index(hexDigits) + Random.index(hexDigits); return ["\\u" + fourHex, parseInt(fourHex, 16)]; } },
]);

function regexCharacter()
{
  var [matcher, charcode] = Random.index(regexCharacterMakers)();
  switch(rnd(10)) {
    case 0:  return [matcher, charcode + 32]; // lowercase
    case 1:  return [matcher, charcode - 32]; // uppercase
    case 2:  return [matcher, regexCharCode()]; // some other character
    default: return [matcher, charcode];
  }
}

var regexBuiltInCharClasses = [
    "\\d", "\\D", // digit
    "\\s", "\\S", // space
    "\\w", "\\W", // "word" character (alphanumeric plus underscore)
];

// Returns POTENTIAL_MATCHES one-character strings, mostly consisting of the input characters
function regexOneCharStringsWith(frequentChars) {
  var matches = [];
  for (var i = 0; i < POTENTIAL_MATCHES; ++i) {
    matches.push(rnd(8) ? Random.index(frequentChars) : String.fromCharCode(regexCharCode()));
  }
  return matches;
}

// Returns POTENTIAL_MATCHES short strings, using the input characters a lot.
function regexShortStringsWith(frequentChars) {
  var matches = [];
  for (var i = 0; i < POTENTIAL_MATCHES; ++i) {
    var s = "";
    while (rnd(3)) {
      s += rnd(4) ? Random.index(frequentChars) : String.fromCharCode(regexCharCode());
    }
    matches.push(s);
  }
  return matches;
}

var regexTermMakers =
  [
    function() { return regexCharacterClass(); },
    function() { var [re, cc] = regexCharacter();   return [re, regexOneCharStringsWith([String.fromCharCode(cc)])]; },
    function() { return [Random.index(regexBuiltInCharClasses), regexOneCharStringsWith(["0", "a", "_"])]; },
    function() { return ["[^]",                                 regexOneCharStringsWith(["\n"])];     },
    function() { return [".",                                   regexOneCharStringsWith(["\n"])];     },
    function() { return [Random.index(["^", "$"]),              regexShortStringsWith(["\n"])];     },            // string boundaries or line boundaries (with /m)
    function() { return [Random.index(["\\b", "\\B"]),          regexShortStringsWith([" ", "\n", "a", "1"])]; }, // word boundaries
  ];

function regexTerm()
{
  return Random.index(regexTermMakers)();
}

// Returns a pair: [(regex char class), (POTENTIAL_MATCHES number of strings that might match)]
// e.g. ["[a-z0-9]", ["a", "8", ...]]
function regexCharacterClass()
{
  var ranges = rnd(5);
  var inRange = rnd(2);
  var charBucket = [String.fromCharCode(regexCharCode())]; // from which potenial matches will be drawn

  var re = "[";
  if (!inRange) {
    re += "^";
  }

  var lo, hi;

  for (var i = 0; i < ranges; ++i) {
    if (rnd(100) == 0) {
      // Confuse things by tossing in an extra "-"
      re += "-";
      if (rnd(2)) {
        re += String.fromCharCode(regexCharCode());
      }
    }

    if (rnd(3) == 1) {
      // Add a built-in class, like "\d"
      re += Random.index(regexBuiltInCharClasses);
      charBucket.push("a");
      charBucket.push("0");
      charBucket.push("_");
    } else if (rnd(2)) {
      // Add a range, like "a-z"
      var a = regexCharacter();
      var b = regexCharacter();
      if ((a[1] <= b[1]) == !!rnd(10)) {
        [lo, hi] = [a, b];
      } else {
        [lo, hi] = [b, a];
      }

      re += lo[0] + "-" + hi[0];
      charBucket.push(String.fromCharCode(lo[1] + rnd(3) - 1));
      charBucket.push(String.fromCharCode(hi[1] + rnd(3) - 1));
      charBucket.push(String.fromCharCode(lo[1] + rnd(Math.max(hi[1] - lo[1], 1)))); // something in the middle
    } else {
      // Add a single character
      var a = regexCharacter();
      re += a[0];
      charBucket.push(String.fromCharCode(a[1]));
    }
  }

  re += "]";
  return [re, pickN(charBucket, POTENTIAL_MATCHES)];
}

function pickN(bucket, picks)
{
  var picked = [];
  for (var i = 0; i < picks; ++i) {
    picked.push(Random.index(bucket));
  }
  return picked;
}
<|endoftext|>


<commit_before><commit_msg>commented out alert<commit_after><|endoftext|>


<commit_before>var child_process = require('child_process');
var should = require("should");
var fs = require("fs");
var serialport;
var shared = require("../../www/js/shared/JsonUtil");
var Logger = require("../../www/js/shared/Logger");
var MTO_FPD = require("../../www/js/shared/MTO_FPD");

try {
    serialport = require("serialport");
} catch (e) {
    serialport = null; // failover
}

(function(exports) {
    function reset_serialDriver(that) {
        console.log("TTY\t: FireStepDriver reset_serialDriver()");
        that.model.available = false;
        that.model.initialized = false;
        that.serialQueue = [];
    }

    function send_startup(that, onStartup) {
        that.model.available = true;
        if (that.serialQueue.length > 0) {
            console.log("TTY\t: FireStepDriver send_startup() clearing queue items:", that.serialQueue.length);
            that.serialQueue = [];
        }
        that.serialInProgress = false;
        that.model.initialized = false;
        onStartup();
        that.processQueue();
    }

    function open_serialport(that, onStartup, options) {
        console.log("TTY\t: FireStepDriver(" + that.model.rest.serialPath + ") opening serialport");
        that.serial = new serialport.SerialPort(that.model.rest.serialPath, {
            buffersize: options.buffersize,
            parser: serialport.parsers.readline('\n'),
            baudrate: options.baudrate
        }, false);
        that.serial.on("data", function(data) {
            var jdata = JSON.parse(data);
            that.onSerialData(data);
        });
        that.serialInProgress = true;
        that.model.driver = "serialport";
        that.serial.open(function(error) {
            that.error = error;
            if (error) {
                console.log("TTY\t: FireStepDriver.open(" + that.model.rest.serialPath + ") FAILED:" + error);
                that.model.available = false;
                reset_serialDriver(that);
            } else {
                that.model.available = true;
                console.log("TTY\t: FireStepDriver() SerialPort.open(" + that.model.rest.serialPath + ") ready...");
                reset_serialDriver(that);
                send_startup(that, onStartup);
            }
        });
    }

    function open_firestep(that, onStartup, options) {
        try {
            that.firestep_proc = {}; // mark intent (actual value is set async)
            that.model.driver = "firestep";

            function onOpenSuccess(that, stdout, attempts) {
                console.log("TTY\t: FireStepDriver(" + that.model.rest.serialPath + ") firestep reset successful. attempts:" + attempts + " stdout:" + stdout);
                that.firestep_proc = child_process.spawn('firestep', ['-d', that.model.rest.serialPath]);
                console.log("TTY\t: FireStepDriver(" + that.model.rest.serialPath + ") firestep cli pid:" + that.firestep_proc.pid);
                that.firestep_proc.on('close', function(code) {
                    if (code) {
                        console.log("TTY\t: firestep cli ERROR:" + code);
                    } else {
                        console.log("TTY\t: firestep cli ended normally");
                    }
                });
                that.firestep_proc.stdout.on('data', function(buffer) {
                    var data = buffer.toString();
                    data = data.substr(0, data.length - 1); // chop LF to match serialport
                    //console.log("TTY\t: firestep stdout:" + data);
                    that.onSerialData(data);
                });
                that.firestep_proc.stderr.on('data', function(data) {
                    console.warn("STDERR\t: firestep => " + data);
                    reset_serialDriver(that);
                });
                send_startup(that, onStartup);
            }
            var cmd = 'firestep -d ' + that.model.rest.serialPath + ' -r';
            console.log("TTY\t: FireStepDriver(" + that.model.rest.serialPath + ") " + cmd);
            var child1 = child_process.exec(cmd, function(error, stdout, stdin) {
                if (error instanceof Error) {
                    console.log("TTY\t: FireStepDriver(" + that.model.rest.serialPath + ") attempt #1:" + error);
                    var child2 = child_process.exec(cmd, function(error, stdout, stdin) {
                        if (error instanceof Error) {
                            reset_serialDriver(that);
                            console.log("TTY\t: FireStepDriver(" + that.model.rest.serialPath + ") RETRY #1:" + error);
                        } else {
                            onOpenSuccess(that, stdout, 2);
                        }
                    });
                } else {
                    onOpenSuccess(that, stdout, 1);
                }
            });
        } catch (e) {
            console.log("TTY\t: FireStepDriver(" + that.model.rest.serialPath + ") UNAVAILABLE:" + e);
            reset_serialDriver(that);
        }
    }

    function close_serialport(that) {
        console.log("ERROR\t: close_serialport() not implemented");
    }

    function close_firestep(that) {
        if (that.isAvailable() && that.firestep_proc != null) {
            console.log("INFO\t: shutting down FireStep");
            that.firestep_proc.kill('SIGTERM');
        }
    }

    ////////////////// constructor
    function FireStepDriver(model, options) {
        var that = this;
        should.exist(model);
        options = options || {};
        options.buffersize = options.buffersize || 255;
        options.baudrate = options.baudrate || 19200;
        options.maxHistory = options.maxHistory || 50;
        options.msLaunchTimeout = options.msLaunchTimeout || 3000; // allow EEPROM commands to complete
        that.mto = options.mto || new MTO_FPD(options);
        that.maxHistory = options.maxHistory;
        that.serialQueue = [];
        that.serialInProgress = false;
        that.serialHistory = [];
        that.msLaunchTimeout = options.msLaunchTimeout;
        that.model = model;
        that.name = "FireStepDriver";
        that.handlers = {
            idle: function() {},
            response: function(response) {},
        };

        return that;
    }
    FireStepDriver.prototype.on = function(event, callback) {
        var that = this;
        that.handlers[event] = callback;
        return that;
    }

    FireStepDriver.prototype.open = function(onStartup, options) {
        var that = this;
        try {
            fs.statSync(that.model.rest.serialPath);
        } catch (err) {
            var err = new Error("no serial device:" + that.model.rest.serialPath);
            console.log("INFO\t: " + err);
            onStartup(err);
            return;
        }
        if (serialport) {
            open_serialport(that, onStartup, options);
        } else {
            open_firestep(that, onStartup, options);
        }
    }

    FireStepDriver.prototype.close = function(options) {
        var that = this;
        if (serialport) {
            close_serialport(that);
        } else {
            close_firestep(that);
        }
    }

    FireStepDriver.prototype.write = function(cmd) {
        var that = this;
        that.model.writes++;
        console.log("TTY\t: WRITE(" + that.model.writes + ") " + cmd + "\\n");
        try {
            if (that.serial) {
                that.serial.write(cmd);
                that.serial.write("\n");
            } else if (that.firestep_proc) {
                if (that.firestep_proc.pid) {
                    that.firestep_proc.stdin.write(cmd);
                    that.firestep_proc.stdin.write("\n");
                } else {
                    setTimeout(function() {
                        if (that.firestep_proc.pid) {
                            that.firestep_proc.stdin.write(cmd);
                            that.firestep_proc.stdin.write("\n");
                        } else {
                            // FireStep spawn failed
                            console.log("TTY\t: firestep response TIMEOUT:" + that.msLaunchTimeout + "ms");
                            reset_serialDriver(that);
                        }
                    }, that.msLaunchTimeout);
                }
            } else {
                throw new Error("no serial driver");
            }
        } catch (e) {
            console.log("TTY\t: FireStepDriver(" + that.model.rest.serialPath + ") UNAVAILABLE:" + e);
            reset_serialDriver(that);
        }
    }
    FireStepDriver.prototype.processQueue = function() {
        var that = this;
        if (that.serialQueue.length <= 0) {
            //console.log("TTY\t: FireStepDriver.processQueue(empty) ");
        } else if (!that.model.available) {
            console.log("TTY\t: FireStepDriver.processQueue(unavailable) ", that.serialQueue.length,
                " items");
        } else if (that.serialInProgress) {
            //console.log("TTY\t: FireStepDriver.processQueue(busy) ", that.serialQueue.length, " items");
        } else {
            that.serialInProgress = true;
            var jcmd = that.serialQueue.shift();
            that.serialHistory.splice(0, 0, jcmd);
            that.serialHistory.splice(that.maxHistory);
            var cmd = JSON.stringify(jcmd.cmd);
            that.write(cmd);
        }
    };
    FireStepDriver.prototype.onSerialData = function(data) {
        var that = this;
        that.model.reads++;
        console.log("TTY\t: READ(" + that.model.reads + ") " + data + "\\n");
        if (typeof data !== 'string') {
            throw new Error("expected Javascript string for serial data return");
        }
        var request = that.serialHistory.length > 0 ? that.serialHistory[0] : {};
        if (data.indexOf('{') === 0) { // success
            var response = JSON.parse(data);
            if (!response) {
                throw new Error("could not parse firestep response:" + data);
            }
            that.handlers.response(response);
            request.resp = response;
            if (response.s < 0) {
                console.log("TTY\t: FireStep COMMAND FAILED:" + data);
                console.log("TTY\t: FireStepDriver() COMMAND QUEUE CLEARED " + that.serialQueue.length + " ITEMS");
                that.serialQueue = [];
            }
        }

        if (that.serialInProgress && data[data.length - 1] === ' ') { // FireStep idle is SPACE-LF
            that.serialInProgress = false;
            try {
                request.onDone && request.onDone(request.resp);
            } catch (e) {
                console.log("TTY\t: ERROR(response handler failed):" + data, e);
            }
            that.processQueue();
            if (that.serialQueue.length == 0) {
                that.handlers.idle();
            }
        }

        return that;
    };

    FireStepDriver.prototype.history = function() {
        var that = this;
        return that.serialHistory;
    }
    FireStepDriver.prototype.queueLength = function() {
        var that = this;
        return that.serialQueue.length;
    }
    FireStepDriver.prototype.pushQueue = function(cmd, onDone) {
        var that = this;
        that.serialQueue.push({
            "cmd": cmd,
            "onDone": onDone
        });
    }

    module.exports = exports.FireStepDriver = FireStepDriver;
})(typeof exports === "object" ? exports : (exports = {}));
<commit_msg>firestep-save<commit_after>var child_process = require('child_process');
var should = require("should");
var fs = require("fs");
var serialport;
var shared = require("../../www/js/shared/JsonUtil");
var Logger = require("../../www/js/shared/Logger");
var MTO_FPD = require("../../www/js/shared/MTO_FPD");

try {
    serialport = require("serialport");
} catch (e) {
    serialport = null; // failover
}

(function(exports) {
    function reset_serialDriver(that) {
        console.log("TTY\t: FireStepDriver reset_serialDriver()");
        that.model.available = false;
        that.model.initialized = false;
        that.serialQueue = [];
    }

    function send_startup(that, onStartup) {
        that.model.available = true;
        if (that.serialQueue.length > 0) {
            console.log("TTY\t: FireStepDriver send_startup() clearing queue items:", that.serialQueue.length);
            that.serialQueue = [];
        }
        that.serialInProgress = false;
        that.model.initialized = false;
        onStartup();
        that.processQueue();
    }

    function open_serialport(that, onStartup, options) {
        console.log("TTY\t: FireStepDriver(" + that.model.rest.serialPath + ") opening serialport");
        that.serial = new serialport.SerialPort(that.model.rest.serialPath, {
            buffersize: options.buffersize,
            parser: serialport.parsers.readline('\n'),
            baudrate: options.baudrate
        }, false);
        that.serial.on("data", function(data) {
            var jdata = JSON.parse(data);
            that.onSerialData(data);
        });
        that.serialInProgress = true;
        that.model.driver = "serialport";
        that.serial.open(function(error) {
            that.error = error;
            if (error) {
                console.log("TTY\t: FireStepDriver.open(" + that.model.rest.serialPath + ") FAILED:" + error);
                that.model.available = false;
                reset_serialDriver(that);
            } else {
                that.model.available = true;
                console.log("TTY\t: FireStepDriver() SerialPort.open(" + that.model.rest.serialPath + ") ready...");
                reset_serialDriver(that);
                send_startup(that, onStartup);
            }
        });
    }

    function open_firestep(that, onStartup, options) {
        try {
            that.firestep_proc = {}; // mark intent (actual value is set async)
            that.model.driver = "firestep";

            function onOpenSuccess(that, stdout, attempts) {
                console.log("TTY\t: FireStepDriver(" + that.model.rest.serialPath + ") firestep reset successful. attempts:" + attempts + " stdout:" + stdout);
                that.firestep_proc = child_process.spawn('firestep', ['-d', that.model.rest.serialPath]);
                console.log("TTY\t: FireStepDriver(" + that.model.rest.serialPath + ") firestep cli pid:" + that.firestep_proc.pid);
                that.firestep_proc.on('close', function(code) {
                    if (code) {
                        console.log("TTY\t: firestep cli ERROR:" + code);
                    } else {
                        console.log("TTY\t: firestep cli ended normally");
                    }
                });
                that.firestep_proc.stdout.on('data', function(buffer) {
                    var data = buffer.toString();
                    data = data.substr(0, data.length - 1); // chop LF to match serialport
                    //console.log("TTY\t: firestep stdout:" + data);
                    that.onSerialData(data);
                });
                that.firestep_proc.stderr.on('data', function(data) {
                    console.warn("STDERR\t: firestep => " + data);
                    reset_serialDriver(that);
                });
                send_startup(that, onStartup);
            }
            var cmd = 'firestep -d ' + that.model.rest.serialPath + ' -r';
            console.log("TTY\t: FireStepDriver(" + that.model.rest.serialPath + ") " + cmd);
            var child1 = child_process.exec(cmd, function(error, stdout, stdin) {
                if (error instanceof Error) {
                    console.log("TTY\t: FireStepDriver(" + that.model.rest.serialPath + ") attempt #1:" + error);
                    var child2 = child_process.exec(cmd, function(error, stdout, stdin) {
                        if (error instanceof Error) {
                            reset_serialDriver(that);
                            console.log("TTY\t: FireStepDriver(" + that.model.rest.serialPath + ") RETRY #1:" + error);
                        } else {
                            onOpenSuccess(that, stdout, 2);
                        }
                    });
                } else {
                    onOpenSuccess(that, stdout, 1);
                }
            });
        } catch (e) {
            console.log("TTY\t: FireStepDriver(" + that.model.rest.serialPath + ") UNAVAILABLE:" + e);
            reset_serialDriver(that);
        }
    }

    function close_serialport(that) {
        console.log("ERROR\t: close_serialport() not implemented");
    }

    function close_firestep(that) {
        if (that.model.available && that.firestep_proc != null) {
            console.log("INFO\t: shutting down FireStep");
            that.firestep_proc.kill('SIGTERM');
        }
    }

    ////////////////// constructor
    function FireStepDriver(model, options) {
        var that = this;
        should.exist(model);
        options = options || {};
        options.buffersize = options.buffersize || 255;
        options.baudrate = options.baudrate || 19200;
        options.maxHistory = options.maxHistory || 50;
        options.msLaunchTimeout = options.msLaunchTimeout || 3000; // allow EEPROM commands to complete
        that.mto = options.mto || new MTO_FPD(options);
        that.maxHistory = options.maxHistory;
        that.serialQueue = [];
        that.serialInProgress = false;
        that.serialHistory = [];
        that.msLaunchTimeout = options.msLaunchTimeout;
        that.model = model;
        that.name = "FireStepDriver";
        that.handlers = {
            idle: function() {},
            response: function(response) {},
        };

        return that;
    }
    FireStepDriver.prototype.on = function(event, callback) {
        var that = this;
        that.handlers[event] = callback;
        return that;
    }

    FireStepDriver.prototype.open = function(onStartup, options) {
        var that = this;
        try {
            fs.statSync(that.model.rest.serialPath);
        } catch (err) {
            var err = new Error("no serial device:" + that.model.rest.serialPath);
            console.log("INFO\t: " + err);
            onStartup(err);
            return;
        }
        if (serialport) {
            open_serialport(that, onStartup, options);
        } else {
            open_firestep(that, onStartup, options);
        }
    }

    FireStepDriver.prototype.close = function(options) {
        var that = this;
        if (serialport) {
            close_serialport(that);
        } else {
            close_firestep(that);
        }
    }

    FireStepDriver.prototype.write = function(cmd) {
        var that = this;
        that.model.writes++;
        console.log("TTY\t: WRITE(" + that.model.writes + ") " + cmd + "\\n");
        try {
            if (that.serial) {
                that.serial.write(cmd);
                that.serial.write("\n");
            } else if (that.firestep_proc) {
                if (that.firestep_proc.pid) {
                    that.firestep_proc.stdin.write(cmd);
                    that.firestep_proc.stdin.write("\n");
                } else {
                    setTimeout(function() {
                        if (that.firestep_proc.pid) {
                            that.firestep_proc.stdin.write(cmd);
                            that.firestep_proc.stdin.write("\n");
                        } else {
                            // FireStep spawn failed
                            console.log("TTY\t: firestep response TIMEOUT:" + that.msLaunchTimeout + "ms");
                            reset_serialDriver(that);
                        }
                    }, that.msLaunchTimeout);
                }
            } else {
                throw new Error("no serial driver");
            }
        } catch (e) {
            console.log("TTY\t: FireStepDriver(" + that.model.rest.serialPath + ") UNAVAILABLE:" + e);
            reset_serialDriver(that);
        }
    }
    FireStepDriver.prototype.processQueue = function() {
        var that = this;
        if (that.serialQueue.length <= 0) {
            //console.log("TTY\t: FireStepDriver.processQueue(empty) ");
        } else if (!that.model.available) {
            console.log("TTY\t: FireStepDriver.processQueue(unavailable) ", that.serialQueue.length,
                " items");
        } else if (that.serialInProgress) {
            //console.log("TTY\t: FireStepDriver.processQueue(busy) ", that.serialQueue.length, " items");
        } else {
            that.serialInProgress = true;
            var jcmd = that.serialQueue.shift();
            that.serialHistory.splice(0, 0, jcmd);
            that.serialHistory.splice(that.maxHistory);
            var cmd = JSON.stringify(jcmd.cmd);
            that.write(cmd);
        }
    };
    FireStepDriver.prototype.onSerialData = function(data) {
        var that = this;
        that.model.reads++;
        console.log("TTY\t: READ(" + that.model.reads + ") " + data + "\\n");
        if (typeof data !== 'string') {
            throw new Error("expected Javascript string for serial data return");
        }
        var request = that.serialHistory.length > 0 ? that.serialHistory[0] : {};
        if (data.indexOf('{') === 0) { // success
            var response = JSON.parse(data);
            if (!response) {
                throw new Error("could not parse firestep response:" + data);
            }
            that.handlers.response(response);
            request.resp = response;
            if (response.s < 0) {
                console.log("TTY\t: FireStep COMMAND FAILED:" + data);
                console.log("TTY\t: FireStepDriver() COMMAND QUEUE CLEARED " + that.serialQueue.length + " ITEMS");
                that.serialQueue = [];
            }
        }

        if (that.serialInProgress && data[data.length - 1] === ' ') { // FireStep idle is SPACE-LF
            that.serialInProgress = false;
            try {
                request.onDone && request.onDone(request.resp);
            } catch (e) {
                console.log("TTY\t: ERROR(response handler failed):" + data, e);
            }
            that.processQueue();
            if (that.serialQueue.length == 0) {
                that.handlers.idle();
            }
        }

        return that;
    };

    FireStepDriver.prototype.history = function() {
        var that = this;
        return that.serialHistory;
    }
    FireStepDriver.prototype.queueLength = function() {
        var that = this;
        return that.serialQueue.length;
    }
    FireStepDriver.prototype.pushQueue = function(cmd, onDone) {
        var that = this;
        that.serialQueue.push({
            "cmd": cmd,
            "onDone": onDone
        });
    }

    module.exports = exports.FireStepDriver = FireStepDriver;
})(typeof exports === "object" ? exports : (exports = {}));
<|endoftext|>


<commit_before>/**
 * Wrapper for {@link Ext.window.Window} providing common configuration for its
 * use within Slate UIs
 */
Ext.define('Slate.ui.Window', {
    extend: 'Ext.window.Window',
    xtype: 'slate-window',
    requires: [
        'Slate.ui.PanelFooter'
    ],

    /**
     * @cfg {Boolean}
     * @inheritdoc Ext.tab.Panel#removePanelHeader
     * @localdoc True to remove header for any added mainView panel,
     * modeled after how tabpanel does the same
     */
    removeMainViewHeader: true,

    /**
     * @cfg {Boolean}
     * True to adopt any footer within mainView to the window itself.
     */
    adoptMainViewFooter: true,

    config: {

        /**
         * @cfg {Ext.Component|Object|String|null}
         *
         * A component, config, or xtype for a main view to add to the window
         */
        mainView: null,

        /**
         * @cfg {Ext.Component|Object|String|null}
         *
         * A component, config, or xtype for a footer component
         */
        footer: null,

        minWidth: 400,
        width: 560,
        minHeight: 200,
        scrollable: true,
        bodyStyle: {
            backgroundColor: '#f5f5f5'
        }
    },

    // window configuration
    shadow: 'frame',
    bodyPadding: 16,
    constrain: true,

    // component configuration
    componentCls: 'slate-window',

    // config handlers
    applyMainView: function(mainView) {
        if (mainView === null) {
            return mainView;
        }

        if (mainView === true) {
            mainView = {};
        } else if (typeof mainView == 'string') {
            mainView = {
                xtype: mainView
            };
        }

        return this.lookupComponent(mainView);
    },

    updateMainView: function(mainView, oldMainView) {
        var me = this,
            items = me.items,
            footer = mainView && mainView.down('slate-panelfooter');

        if (oldMainView) {
            oldMainView.un('titlechange', 'onMainViewTitleChange', me);
        }

        if (mainView && mainView.isPanel) {
            if (me.removeMainViewHeader) {
                if (mainView.rendered) {
                    if (mainView.header) {
                        mainView.header.hide();
                    }
                } else {
                    mainView.header = false;
                }
            }

            mainView.on('titlechange', 'onMainViewTitleChange', me);
        }

        if (mainView.border) {
            mainView.setBorder(false);
        }

        if (mainView.title) {
            me.setTitle(mainView.title);
        }

        if (footer && me.adoptMainViewFooter) {
            mainView.remove(footer, false);
            me.setFooter(footer);
        }

        if (items && items.isMixedCollection) {
            if (oldMainView) {
                me.remove(oldMainView);
            }

            if (mainView) {
                me.insert(0, mainView);
            }
        }
    },

    applyFooter: function(footer, oldFooter) {
        if (typeof footer === 'boolean') {
            footer = {
                hidden: !footer
            };
        }

        return Ext.factory(footer, 'Slate.ui.PanelFooter', oldFooter);
    },

    updateFooter: function(footer, oldFooter) {
        var me = this,
            items = me.items;

        if (items && items.isMixedCollection) {
            if (oldFooter) {
                me.remove(oldFooter);
            }

            if (footer) {
                me.addDocked(footer);
            }
        }
    },

    // container lifecycle
    initItems: function() {
        var me = this,
            mainView = me.getMainView(),
            footer = me.getFooter();

        me.callParent(arguments);

        if (mainView) {
            me.insert(0, mainView);
        }

        if (footer) {
            me.addDocked(footer);
        }
    },

    // event handlers
    onMainViewTitleChange: function(mainView, title) {
        this.setTitle(title);
    }
});<commit_msg>Add PanelFooter to footer cfg docs<commit_after>/**
 * Wrapper for {@link Ext.window.Window} providing common configuration for its
 * use within Slate UIs
 */
Ext.define('Slate.ui.Window', {
    extend: 'Ext.window.Window',
    xtype: 'slate-window',
    requires: [
        'Slate.ui.PanelFooter'
    ],

    /**
     * @cfg {Boolean}
     * @inheritdoc Ext.tab.Panel#removePanelHeader
     * @localdoc True to remove header for any added mainView panel,
     * modeled after how tabpanel does the same
     */
    removeMainViewHeader: true,

    /**
     * @cfg {Boolean}
     * True to adopt any footer within mainView to the window itself.
     */
    adoptMainViewFooter: true,

    config: {

        /**
         * @cfg {Ext.Component|Object|String|null}
         *
         * A component, config, or xtype for a main view to add to the window
         */
        mainView: null,

        /**
         * @cfg {Slate.ui.PanelFooter|Ext.Component|Object|String|null}
         *
         * A component, config, or xtype for a footer component
         */
        footer: null,

        minWidth: 400,
        width: 560,
        minHeight: 200,
        scrollable: true,
        bodyStyle: {
            backgroundColor: '#f5f5f5'
        }
    },

    // window configuration
    shadow: 'frame',
    bodyPadding: 16,
    constrain: true,

    // component configuration
    componentCls: 'slate-window',

    // config handlers
    applyMainView: function(mainView) {
        if (mainView === null) {
            return mainView;
        }

        if (mainView === true) {
            mainView = {};
        } else if (typeof mainView == 'string') {
            mainView = {
                xtype: mainView
            };
        }

        return this.lookupComponent(mainView);
    },

    updateMainView: function(mainView, oldMainView) {
        var me = this,
            items = me.items,
            footer = mainView && mainView.down('slate-panelfooter');

        if (oldMainView) {
            oldMainView.un('titlechange', 'onMainViewTitleChange', me);
        }

        if (mainView && mainView.isPanel) {
            if (me.removeMainViewHeader) {
                if (mainView.rendered) {
                    if (mainView.header) {
                        mainView.header.hide();
                    }
                } else {
                    mainView.header = false;
                }
            }

            mainView.on('titlechange', 'onMainViewTitleChange', me);
        }

        if (mainView.border) {
            mainView.setBorder(false);
        }

        if (mainView.title) {
            me.setTitle(mainView.title);
        }

        if (footer && me.adoptMainViewFooter) {
            mainView.remove(footer, false);
            me.setFooter(footer);
        }

        if (items && items.isMixedCollection) {
            if (oldMainView) {
                me.remove(oldMainView);
            }

            if (mainView) {
                me.insert(0, mainView);
            }
        }
    },

    applyFooter: function(footer, oldFooter) {
        if (typeof footer === 'boolean') {
            footer = {
                hidden: !footer
            };
        }

        return Ext.factory(footer, 'Slate.ui.PanelFooter', oldFooter);
    },

    updateFooter: function(footer, oldFooter) {
        var me = this,
            items = me.items;

        if (items && items.isMixedCollection) {
            if (oldFooter) {
                me.remove(oldFooter);
            }

            if (footer) {
                me.addDocked(footer);
            }
        }
    },

    // container lifecycle
    initItems: function() {
        var me = this,
            mainView = me.getMainView(),
            footer = me.getFooter();

        me.callParent(arguments);

        if (mainView) {
            me.insert(0, mainView);
        }

        if (footer) {
            me.addDocked(footer);
        }
    },

    // event handlers
    onMainViewTitleChange: function(mainView, title) {
        this.setTitle(title);
    }
});<|endoftext|>


<commit_before>/*!
Cloud4all Preferences Management Tools

Copyright 2013 CERTH/HIT

Licensed under the New BSD license. You may not use this file except in
compliance with this License.

You may obtain a copy of the License at
https://github.com/GPII/prefsEditors/LICENSE.txt
*/

/*global fluid, jQuery, gpii*/
/*jslint white: true, onevar: true, funcinvoke: true, forvar: true, undef: true, newcap: true, nomen: true, regexp: true, plusplus: true, bitwise: true, maxerr: 50, indent: 4 */

(function ($, fluid) {
    fluid.registerNamespace("gpii.prefs.adjusters_pilot_2");

    gpii.prefs.adjusters_pilot_2.primarySchema = {
        "magnifier.invertColours": {
            "type": "boolean",
            "default": false
        },
        "showCrosshairs": {
            "type": "boolean",
            "default": false
        },
        "magnifier.tracking": {
            "type": "string",
            "default": "",
            "enum": ["mousecursor", "textcursor", "keyboardfocus"]
        },
        "screenReader.tracking": {
            "type": "string",
            "default": "",
            "enum": ["mousecursor", "textcursor", "keyboardfocus"]
        }
    };

    gpii.prefs.adjusters_pilot_2.auxiliarySchema = {
        "namespace": "gpii.prefs.adjusters_pilot_2.auxiliarySchema",
        "templatePrefix": "../../src/shared/adjusters/html/",
        "template": "%prefix/adjustersPilots2.html",
        "messagePrefix": "../../src/shared/adjusters/messages/en/", // default
        "message": "%prefix/pmt.json",

        "magnifier.invertColours": {
            "type": "magnifier.invertColours",
            /*"enactor": {
                "type": "gpii.uiOptions.enactors.contrast"
            },*/
            "panel": {
                "type": "gpii.prefs.panel.magnifier.invertColours",
                "container": ".gpiic-increaseSize-magnifierInvertColours",
                "template": "%prefix/UIOptionsTemplate-iconCheckAdjuster.html",
                "message": "%prefix/magnifierInvertColours.json"
            }
        },
        "showCrosshairs": {
            "type": "showCrosshairs",
            /*"enactor": {
                "type": "gpii.uiOptions.enactors.contrast"
            },*/
            "panel": {
                "type": "gpii.prefs.panel.showCrosshairs",
                "container": ".gpiic-increaseSize-showCrosshairs",
                "template": "%prefix/UIOptionsTemplate-iconCheckAdjuster.html",
                "message": "%prefix/showCrosshairs.json"
            }
        },
        "magnifierTracking": {
            "type": "magnifier.tracking",
            "classes": {
                "mousecursor": "gpii-followingElement-mouseCursorIcon",
                "textcursor": "gpii-followingElement-textCursorIcon",
                "keyboardfocus": "gpii-followingElement-keyboardFocusIcon"
            },
            "panel": {
                "type": "gpii.prefs.panel.followingElement.magnifier",
                "container": ".gpiic-increaseSize-magnifierFollows",
                "template": "%prefix/UIOptionsTemplate-followingElement.html",
                "message": "%prefix/followingElement.json",
                "classnameMap": {"followingElement": "@magnifierTracking.classes"}
            }
        },
        "screenReaderTracking": {
            "type": "screenReader.tracking",
            "classes": {
                "mousecursor": "gpii-followingElement-mouseCursorIcon",
                "textcursor": "gpii-followingElement-textCursorIcon",
                "keyboardfocus": "gpii-followingElement-keyboardFocusIcon"
            },
            "panel": {
                "type": "gpii.prefs.panel.followingElement.screenReader",
                "container": ".gpiic-increaseSize-screenReaderFollows",
                "template": "%prefix/UIOptionsTemplate-followingElement.html",
                "message": "%prefix/followingElement.json",
                "classnameMap": {"followingElement": "@screenReaderTracking.classes"}
            }
        }
    };
})(jQuery, fluid);
<commit_msg>Reusing classes for followingElement adjusters.<commit_after>/*!
Cloud4all Preferences Management Tools

Copyright 2013 CERTH/HIT

Licensed under the New BSD license. You may not use this file except in
compliance with this License.

You may obtain a copy of the License at
https://github.com/GPII/prefsEditors/LICENSE.txt
*/

/*global fluid, jQuery, gpii*/
/*jslint white: true, onevar: true, funcinvoke: true, forvar: true, undef: true, newcap: true, nomen: true, regexp: true, plusplus: true, bitwise: true, maxerr: 50, indent: 4 */

(function ($, fluid) {
    fluid.registerNamespace("gpii.prefs.adjusters_pilot_2");

    gpii.prefs.adjusters_pilot_2.primarySchema = {
        "magnifier.invertColours": {
            "type": "boolean",
            "default": false
        },
        "showCrosshairs": {
            "type": "boolean",
            "default": false
        },
        "magnifier.tracking": {
            "type": "string",
            "default": "",
            "enum": ["mousecursor", "textcursor", "keyboardfocus"]
        },
        "screenReader.tracking": {
            "type": "string",
            "default": "",
            "enum": ["mousecursor", "textcursor", "keyboardfocus"]
        }
    };

    gpii.prefs.adjusters_pilot_2.auxiliarySchema = {
        "namespace": "gpii.prefs.adjusters_pilot_2.auxiliarySchema",
        "templatePrefix": "../../src/shared/adjusters/html/",
        "template": "%prefix/adjustersPilots2.html",
        "messagePrefix": "../../src/shared/adjusters/messages/en/", // default
        "message": "%prefix/pmt.json",

        "magnifier.invertColours": {
            "type": "magnifier.invertColours",
            /*"enactor": {
                "type": "gpii.uiOptions.enactors.contrast"
            },*/
            "panel": {
                "type": "gpii.prefs.panel.magnifier.invertColours",
                "container": ".gpiic-increaseSize-magnifierInvertColours",
                "template": "%prefix/UIOptionsTemplate-iconCheckAdjuster.html",
                "message": "%prefix/magnifierInvertColours.json"
            }
        },
        "showCrosshairs": {
            "type": "showCrosshairs",
            /*"enactor": {
                "type": "gpii.uiOptions.enactors.contrast"
            },*/
            "panel": {
                "type": "gpii.prefs.panel.showCrosshairs",
                "container": ".gpiic-increaseSize-showCrosshairs",
                "template": "%prefix/UIOptionsTemplate-iconCheckAdjuster.html",
                "message": "%prefix/showCrosshairs.json"
            }
        },
        "followingElement": {
            "classes": {
                "mousecursor": "gpii-followingElement-mouseCursorIcon",
                "textcursor": "gpii-followingElement-textCursorIcon",
                "keyboardfocus": "gpii-followingElement-keyboardFocusIcon"
            }
        },
        "magnifierTracking": {
            "type": "magnifier.tracking",
            "panel": {
                "type": "gpii.prefs.panel.followingElement.magnifier",
                "container": ".gpiic-increaseSize-magnifierFollows",
                "template": "%prefix/UIOptionsTemplate-followingElement.html",
                "message": "%prefix/followingElement.json",
                "classnameMap": {"followingElement": "@followingElement.classes"}
            }
        },
        "screenReaderTracking": {
            "type": "screenReader.tracking",
            "panel": {
                "type": "gpii.prefs.panel.followingElement.screenReader",
                "container": ".gpiic-increaseSize-screenReaderFollows",
                "template": "%prefix/UIOptionsTemplate-followingElement.html",
                "message": "%prefix/followingElement.json",
                "classnameMap": {"followingElement": "@followingElement.classes"}
            }
        }
    };
})(jQuery, fluid);
<|endoftext|>


<commit_before>

var project = require('pillars');
var config = require('./config.js');

var Generate = require('./generate.js');

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

project.services.get('http').configure({
	port: config.port
}).start();

var DB = require('./store/db.js');

DB.getTypes(function(types) {

	for (var i = 0; i < types.length; i++) {
		Generate.new(types[i], types[i].name.toLowerCase(), project);
	}
});

// Crate main routes, the same to all projects
project.routes.add(
	new Route({
		id: 'Endpoint',
		path: '/endpoint',
		method: ['POST']
	},
	function(gw) {

		// console.log(gw.params);

		// console.log(typeof gw.params.type);
		// console.log(JSON.parse(gw.params.type));

		Generate.new(JSON.parse(gw.params.type), gw.params.endpoint, project);

		gw.html('done');

		// gw.html("
Hello World!!
");
	})
);
<commit_msg>add default type<commit_after>

var project = require('pillars');
var config = require('./config.js');

var Generate = require('./generate.js');

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

project.services.get('http').configure({
	port: config.port
}).start();

var DB = require('./store/db.js');

DB.getTypes(function(types) {

	for (var i = 0; i < types.length; i++) {
		Generate.new(types[i], types[i].name.toLowerCase(), project);
	}
});

// Crate main routes, the same to all projects
project.routes.add(
	new Route({
		id: 'Endpoint',
		path: '/endpoint',
		method: ['POST']
	},
	function(gw) {

		// console.log(gw.params);

		// console.log(typeof gw.params.type);
		// console.log(JSON.parse(gw.params.type));

		Generate.new(JSON.parse(gw.params.type), gw.params.endpoint || JSON.parse(gw.params.type).name, project);

		gw.html('done');

		// gw.html("
Hello World!!
");
	})
);
<|endoftext|>


<commit_before>polyteeth.prototype = extend(Instrument);

function polyteeth(ctx) {
  Instrument.call(this, ctx);

  this.register_param("decay", 0.2, 0.01, 0.5, 0.01);
  this.register_param("freq0", 440, 220, 880, 1);
  this.register_param("ATK", 0.2, 0.05, 5, 0.1);
  this.register_param("subteeth", 0.2, 0, 0.01);

  this.polyteeth2 = ctx.createOscillator();
  this.polyteeth2.type = "sawtooth";
  this.polyteeth2.frequency.value = this.p("freq0");
  this.polyteeth2.start(0);

  this.polyteeth1 = ctx.createOscillator();
  this.polyteeth1.type = "sawtooth";
  this.polyteeth1.frequency.value = this.p("freq0");
  this.polyteeth1.frequency.value = this.p("freq0")/Math.pow(2,0.25);
  this.polyteeth1.start(0);

  this.polyteeth3 = ctx.createOscillator();
  this.polyteeth3.type = "sawtooth";
  this.polyteeth3.frequency.value = this.p("freq0")*Math.pow(2,0.25);
  this.polyteeth3.start(0);

  this.subteeth = ctx.createGain();
  this.subteeth.gain.value = 0.5;

  this.polyteethGain = ctx.createGain();
  this.polyteethGain.gain.setValueAtTime(0,0);

  this.polyteeth1.connect(this.subteeth);
  this.polyteeth3.connect(this.subteeth);
  this.subteeth.connect(this.polyteethGain);
  this.polyteeth2.connect(this.polyteethGain);
}

polyteeth.prototype.connect = function(node) {
  this.polyteethGain.connect(node);
}

polyteeth.prototype.trigger = function(velocity, time) {
  var t = time || this.ctx.currentTime;
  var v = velocity2gain(velocity);

  this.polyteeth2.frequency.value = this.p("freq0");
  this.polyteeth3.frequency.value = this.p("freq0")*Math.pow(2,0.25);
  this.polyteeth1.frequency.value = this.p("freq0")/Math.pow(2,0.25);

  this.subteeth.gain.setValueAtTime = this.p("subteeth");

  this.polyteethGain.gain.cancelScheduledValues(t);
  this.polyteethGain.gain.setValueAtTime(0, t);
  this.polyteethGain.gain.linearRampToValueAtTime(v * this.p("ATK"), t + 0.01);
  this.polyteethGain.gain.setTargetAtTime(0, t + 0.01, this.p("decay"));
}

polyteeth.prototype.name = function() {
  return "polyteeth";
}
<commit_msg>correc sawteeth<commit_after>polyteeth.prototype = extend(Instrument);

function polyteeth(ctx) {
  Instrument.call(this, ctx);

  this.register_param("decay", 0.2, 0.01, 0.5, 0.01);
  this.register_param("freq0", 440, 220, 880, 1);
  this.register_param("ATK", 0.2, 0.05, 5, 0.1);
  this.register_param("subteeth", 0.2, 0, 1, 0.01);

  this.polyteeth2 = ctx.createOscillator();
  this.polyteeth2.type = "sawtooth";
  this.polyteeth2.frequency.value = this.p("freq0");
  this.polyteeth2.start(0);

  this.polyteeth1 = ctx.createOscillator();
  this.polyteeth1.type = "sawtooth";
  this.polyteeth1.frequency.value = this.p("freq0");
  this.polyteeth1.frequency.value = this.p("freq0")/Math.pow(2,0.25);
  this.polyteeth1.start(0);

  this.polyteeth3 = ctx.createOscillator();
  this.polyteeth3.type = "sawtooth";
  this.polyteeth3.frequency.value = this.p("freq0")*Math.pow(2,0.25);
  this.polyteeth3.start(0);

  this.subteeth = ctx.createGain();
  this.subteeth.gain.value = 0.5;

  this.polyteethGain = ctx.createGain();
  this.polyteethGain.gain.setValueAtTime(0,0);

  this.polyteeth1.connect(this.subteeth);
  this.polyteeth3.connect(this.subteeth);
  this.subteeth.connect(this.polyteethGain);
  this.polyteeth2.connect(this.polyteethGain);
}

polyteeth.prototype.connect = function(node) {
  this.polyteethGain.connect(node);
}

polyteeth.prototype.trigger = function(velocity, time) {
  var t = time || this.ctx.currentTime;
  var v = velocity2gain(velocity);

  this.polyteeth2.frequency.value = this.p("freq0");
  this.polyteeth3.frequency.value = this.p("freq0")*Math.pow(2,0.25);
  this.polyteeth1.frequency.value = this.p("freq0")/Math.pow(2,0.25);

  this.subteeth.gain.setValueAtTime = (t,this.p("subteeth"));

  this.polyteethGain.gain.cancelScheduledValues(t);
  this.polyteethGain.gain.setValueAtTime(0, t);
  this.polyteethGain.gain.linearRampToValueAtTime(v * this.p("ATK"), t + 0.01);
  this.polyteethGain.gain.setTargetAtTime(0, t + 0.01, this.p("decay"));
}

polyteeth.prototype.name = function() {
  return "polyteeth";
}
<|endoftext|>


<commit_before>angular.module('score-stage')
.directive('ssVexFlow', [ function() {

    var WIDTH = 1000;
    var MAX_WIDTH = WIDTH - 1;

    function link(scope, element, attrs) {

        var bars = [0,0,0,0,0,0].fill(new SS.Bar(new SS.TimeSignature(3, 4), [ new SS.Tick('q', [ new SS.Note('a', 4) ]), new SS.Tick('q', [ new SS.Note('b', 4) ]),
            new SS.Tick('q', []), new SS.Tick('q', []), new SS.Tick('q', [ new SS.Note('c', 5), new SS.Note('d', 5), new SS.Note('e', 5) ]) ]));

        var renderer = new Vex.Flow.Renderer(element[0], Vex.Flow.Renderer.Backends.SVG);
        var context = renderer.getContext();

        var prev = undefined;
        // Most recent top, bottom, and left, and total width
        var row = { top : 0, left : 0, width : 0 };
        bars.forEach(function(bar) {

            var clef = 'treble';
            // Create the notes
            var notes = bar.ticks.map(function(tick) {
                var keys = tick.notes.map(function(note) {
                    return note.letter + '/' + note.octave;
                });
                var duration = tick.duration;
                if (tick.isRest()) {
                    keys = [ 'b/4' ];
                    duration += 'r';
                }
                return new Vex.Flow.StaveNote({ clef : clef, keys : keys, duration : duration });
            });

            var voice = new Vex.Flow.Voice({ beat_value : bar.time.upper, num_beats : bar.time.lower }).setStrict(false).addTickables(notes);
            var formatter = new Vex.Flow.Formatter().joinVoices([ voice ]);
            var stave = new Vex.Flow.Stave(0, 0, MAX_WIDTH);

            var width = formatter.preCalculateMinTotalWidth([ voice ]) * 2;
            formatter.format([ voice ], width);
            width += stave.getNoteStartX() + MAX_WIDTH - stave.getNoteEndX();
            var modWidths = stave.getModifiers().reduce(function(prev, curr) {
                return prev + curr.getWidth() + curr.getPadding();
            }, 0);
            width += modWidths;

            var newRow = (row.width + width) > MAX_WIDTH;
            if (newRow) {
                row.top = (prev && prev.getBottomY()) || 0;
                row.left = 0;
                row.width = width;
            }
            else {
                row.left = row.width;
                row.width += width;
            }
            stave.setX(row.left).setY(row.top);

//            var stave = new Vex.Flow.Stave(row.left, row.top, width);
//            if (newRow) {
//                stave.addClef(clef);
//            }
//            else if (!prev) {
//                stave.addClef(clef);
//                stave.addTimeSignature(bar.time.vexFormat());
//            }
//            console.log(row.left, stave.getNoteStartX())
//            console.log(stave.getNoteStartX() - (row.left - width))
//            console.log(row.left - stave.getNoteEndX())
//            var extraWidth = (stave.getNoteStartX() - (row.left - width)) + (row.left - stave.getNoteEndX());
//            width += extraWidth;
//            row.width += extraWidth;
//            row.left += extraWidth;
//            stave.setWidth(width);

            stave.setWidth(width).setContext(context).draw();
            voice.draw(context, stave);
            prev = stave;
        });

        renderer.resize(WIDTH, prev.getBottomY());
    }

    return {
        restrict : 'E',
        link : link
    };
} ])
.directive('ssMusicScore', [ function() {

    function link(scope, element, attrs) {

    }

    return {
        restrict : 'E',
        link : link,
        template :
            `<md-card flex="none" layout="column" layout-align="start center">
                <md-card-content flex layout="column" layout-align="start center">
                    <ss-vex-flow flex layout="column" layout-align="start center"></ss-vex-flow>
                </md-card-content>
            </md-card>`
    };
} ]);<commit_msg>Improved extra spacing with modifiers<commit_after>angular.module('score-stage')
.directive('ssVexFlow', [ function() {

    var WIDTH = 1000;
    var MAX_WIDTH = WIDTH - 1;

    function getExtraWidth(stave) {
        return (stave.getNoteStartX() + MAX_WIDTH - stave.getNoteEndX())
            + stave.getModifiers().reduce(function(prev, curr) {
                if (curr.getPosition() === Vex.Flow.StaveModifier.Position.END) {
                    return prev + curr.getWidth() + curr.getPadding();
                }
                return prev;
            }, 0);
    }

    function link(scope, element, attrs) {

        var bars = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
            .fill(new SS.Bar(new SS.TimeSignature(3, 4), [ new SS.Tick('q', [ new SS.Note('a', 4) ]), new SS.Tick('q', [ new SS.Note('b', 4) ]),
                new SS.Tick('q', []), new SS.Tick('q', []), new SS.Tick('q', [ new SS.Note('c', 5), new SS.Note('d', 5), new SS.Note('e', 5) ]) ]));

        var renderer = new Vex.Flow.Renderer(element[0], Vex.Flow.Renderer.Backends.SVG);
        var context = renderer.getContext();

        var prev = undefined;
        // Most recent top, bottom, and left, and total width
        var row = { top : 0, left : 0, width : 0 };
        bars.forEach(function(bar) {

            var clef = 'treble';
            // Create the notes
            var notes = bar.ticks.map(function(tick) {
                var keys = tick.notes.map(function(note) {
                    return note.letter + '/' + note.octave;
                });
                var duration = tick.duration;
                if (tick.isRest()) {
                    keys = [ 'b/4' ];
                    duration += 'r';
                }
                return new Vex.Flow.StaveNote({ clef : clef, keys : keys, duration : duration });
            });

            var voice = new Vex.Flow.Voice({ beat_value : bar.time.upper, num_beats : bar.time.lower }).setStrict(false).addTickables(notes);
            var formatter = new Vex.Flow.Formatter().joinVoices([ voice ]);
            var stave = new Vex.Flow.Stave(0, 0, MAX_WIDTH);

            var width = formatter.preCalculateMinTotalWidth([ voice ]) * 2;
            formatter.format([ voice ], width);
            var extraWidth = getExtraWidth(stave);
            width += extraWidth;

            var newRow = (row.width + width) > MAX_WIDTH;
            if (newRow) {
                row.top = (prev && prev.getBottomY()) || 0;
                row.left = 0;
                row.width = width;
            }
            else {
                row.left = row.width;
                row.width += width;
            }
            stave.setX(row.left).setY(row.top);

            if (newRow) {
                stave.addClef(clef);
            }
            else if (!prev) {
                stave.addClef(clef);
                stave.addTimeSignature(bar.time.vexFormat());
            }

            extraWidth = getExtraWidth(stave);
            width += extraWidth;
            row.width += extraWidth;
            row.left += extraWidth;

            stave.setWidth(width).setContext(context).draw();
            voice.draw(context, stave);
            prev = stave;
        });

        renderer.resize(WIDTH, prev.getBottomY());
    }

    return {
        restrict : 'E',
        link : link
    };
} ])
.directive('ssMusicScore', [ function() {

    function link(scope, element, attrs) {

    }

    return {
        restrict : 'E',
        link : link,
        template :
            `<md-card flex="none" layout="column" layout-align="start center">
                <md-card-content flex layout="column" layout-align="start center">
                    <ss-vex-flow flex layout="column" layout-align="start center"></ss-vex-flow>
                </md-card-content>
            </md-card>`
    };
} ]);<|endoftext|>


<commit_before>if (typeof (require) != 'undefined') {
	var loader = require('../../node_modules/Butterfly-js/dist/butterfly.min.js').loader;
}

/**
 * Engine module, deal with the whole game linking, the screens, display
 * of a loading bar...
 */
loader.addModule('Engine',
'B', 'Canvas', 'Controls', 'Level', 'data', 'GUI',
function (B, canvas, Controls, Level, data, GUI) {
	var _callbacks = {},
		engine = {},
		fps = 30,
		currentLevelIndex = 0,
		// some states
		gameFinished = false,
		levelFinished = false,
		_drawables = [],
		level;

	function _loadResources (loadedCallback) {
		var r, loaded = 0,
			loadingPadding = canvas.width() / 5,
			loadingWidth = 3 * loadingPadding,
			resources = data.resources;

		if (!resources) {
			loadedCallback();
			return;
		}

		canvas.clearScreen();
		GUI.progressBar(
			loadingPadding, canvas.height() / 2,
			loadingWidth, 30,
			0,
			'black', 'white', 'black'
		);
		for (r = 0; r < resources.length; r++) {
			resources[r].resource = new Image();
			resources[r].resource.onload = function () {
				if (++loaded == resources.length) {
					loadedCallback();
				}
				else {
					GUI.progressBar(
						loadingPadding, canvas.height() / 2,
						loadingWidth, 30,
						loaded / resources.length,
						'black', 'white', 'black'
					);
				}
			};
			resources[r].resource.src = resources[r].url;
		}
	}

	/**
	 * Method to execute on each frame to update the game state and the
	 * objects's position and then redraw the canvas
	 */
	function _updateAll () {
		canvas.clearScreen('black');
		if (gameFinished) {
			_runCallback('gameFinishedScreen');
		}
		else if (levelFinished) {
			_runCallback('levelFinishedScreen');
		}
		else {
			_runCallback('moveAll');
			canvas.drawAll([_drawables, level.cells]);
		}
	}

	function _runCallback (name, args) {
		if (typeof _callbacks[name] == 'function') {
			_callbacks[name].apply(this, args);
		}
	}

	function _resetLevel (newLevel) {
		if (newLevel) {
			level = Level.createLevel(data, currentLevelIndex);
		}
		else {
			level.reset();
		}

		_runCallback('resetLevel');
	}

	function _initEvents () {
		// Event to execute when the player wins
		B.Events.on('win', null, function () {
			if (currentLevelIndex == data.maps.length - 1) {
				_resetLevel(true);
				gameFinished = true;
			}
			else {
				_resetLevel(false);
				levelFinished = true;
			}

			_runCallback('win');
		});

		// Event to execute when the player loses
		B.Events.on('lost', null, function () {
			_resetLevel(false);

			_runCallback('lose');
		});

		// Event to execute when the mouse is clicked
		B.Events.on('mouse-clicked', null, function (mX, mY) {
			if (levelFinished) {
				currentLevelIndex++;
				_resetLevel(true);
				levelFinished = false;
			}
			else if (gameFinished) {
				currentLevelIndex = 0;
				_resetLevel(true);
				gameFinished = false;
			}

			_runCallback('mouseClicked');
		});

		// Event to execute when the mouse move
		B.Events.on('mouse-moved', null, function (mX, mY) {
			mouseX = mX;
			mouseY = mY;

			_runCallback('mouseMoved', [mouseX, mouseY]);
		});
	}

	engine.addCallback = function (name, callback) {
		_callbacks[name] = callback;
	};

	engine.init = function (canvasElement, callback) {
		B.on(window, 'load', function () {
			// Init the view
			canvas.init(canvasElement);
			Controls.init(false, canvasElement);

			_loadResources(function () {
				_resetLevel(true);

				if (typeof callback == 'function') {
					callback();
				}
				setInterval(_updateAll, 1000 / fps);
			});
		});

		_initEvents();
	};

	engine.addDrawable = function (drawable) {
		_drawables.push(drawable);
	};

	engine.getLevel = function () {
		return level;
	};

	engine.resetLevel = _resetLevel;
	engine._loadResources = _loadResources;
	engine.updateAll = _updateAll;
	engine.levelFinished = levelFinished;
	engine.gameFinished = gameFinished;

	return engine;
});

<commit_msg>options added to enable the controls<commit_after>if (typeof (require) != 'undefined') {
	var loader = require('../../node_modules/Butterfly-js/dist/butterfly.min.js').loader;
}

/**
 * Engine module, deal with the whole game linking, the screens, display
 * of a loading bar...
 */
loader.addModule('Engine',
'B', 'Canvas', 'Controls', 'Level', 'data', 'GUI',
function (B, canvas, Controls, Level, data, GUI) {
	var _callbacks = {},
		engine = {},
		fps = 30,
		currentLevelIndex = 0,
		// some states
		gameFinished = false,
		levelFinished = false,
		_drawables = [],
		level;

	engine.OPTION_USE_KEYBOARD = 0x1;
	engine.OPTION_USE_MOUSE = 0x2;

	function _loadResources (loadedCallback) {
		var r, loaded = 0,
			loadingPadding = canvas.width() / 5,
			loadingWidth = 3 * loadingPadding,
			resources = data.resources;

		if (!resources) {
			loadedCallback();
			return;
		}

		canvas.clearScreen();
		GUI.progressBar(
			loadingPadding, canvas.height() / 2,
			loadingWidth, 30,
			0,
			'black', 'white', 'black'
		);
		for (r = 0; r < resources.length; r++) {
			resources[r].resource = new Image();
			resources[r].resource.onload = function () {
				if (++loaded == resources.length) {
					loadedCallback();
				}
				else {
					GUI.progressBar(
						loadingPadding, canvas.height() / 2,
						loadingWidth, 30,
						loaded / resources.length,
						'black', 'white', 'black'
					);
				}
			};
			resources[r].resource.src = resources[r].url;
		}
	}

	/**
	 * Method to execute on each frame to update the game state and the
	 * objects's position and then redraw the canvas
	 */
	function _updateAll () {
		canvas.clearScreen('black');
		if (gameFinished) {
			_runCallback('gameFinishedScreen');
		}
		else if (levelFinished) {
			_runCallback('levelFinishedScreen');
		}
		else {
			_runCallback('moveAll');
			canvas.drawAll([_drawables, level.cells]);
		}
	}

	function _runCallback (name, args) {
		if (typeof _callbacks[name] == 'function') {
			_callbacks[name].apply(this, args);
		}
	}

	function _resetLevel (newLevel) {
		if (newLevel) {
			level = Level.createLevel(data, currentLevelIndex);
		}
		else {
			level.reset();
		}

		_runCallback('resetLevel');
	}

	function _initEvents () {
		// Event to execute when the player wins
		B.Events.on('win', null, function () {
			if (currentLevelIndex == data.maps.length - 1) {
				_resetLevel(true);
				gameFinished = true;
			}
			else {
				_resetLevel(false);
				levelFinished = true;
			}

			_runCallback('win');
		});

		// Event to execute when the player loses
		B.Events.on('lost', null, function () {
			_resetLevel(false);

			_runCallback('lose');
		});

		// Event to execute when the mouse is clicked
		B.Events.on('mouse-clicked', null, function (mX, mY) {
			if (levelFinished) {
				currentLevelIndex++;
				_resetLevel(true);
				levelFinished = false;
			}
			else if (gameFinished) {
				currentLevelIndex = 0;
				_resetLevel(true);
				gameFinished = false;
			}

			_runCallback('mouseClicked');
		});

		// Event to execute when the mouse move
		B.Events.on('mouse-moved', null, function (mX, mY) {
			mouseX = mX;
			mouseY = mY;

			_runCallback('mouseMoved', [mouseX, mouseY]);
		});
	}

	engine.addCallback = function (name, callback) {
		_callbacks[name] = callback;
	};

	engine.init = function (canvasElement, options, callback) {
		B.on(window, 'load', function () {
			// Init the view
			canvas.init(canvasElement);
			Controls.init(
				(options & engine.OPTION_USE_KEYBOARD) == engine.OPTION_USE_KEYBOARD,
				(options & engine.OPTION_USE_MOUSE) == engine.OPTION_USE_MOUSE ? canvasElement : null
			);

			_loadResources(function () {
				_resetLevel(true);

				if (typeof callback == 'function') {
					callback();
				}
				setInterval(_updateAll, 1000 / fps);
			});
		});

		_initEvents();
	};

	engine.addDrawable = function (drawable) {
		_drawables.push(drawable);
	};

	engine.getLevel = function () {
		return level;
	};

	engine.resetLevel = _resetLevel;
	engine._loadResources = _loadResources;
	engine.updateAll = _updateAll;
	engine.levelFinished = levelFinished;
	engine.gameFinished = gameFinished;

	return engine;
});

<|endoftext|>


<commit_before>var request = require('request-promise');

/**
 * Creats a new foursquare client
 */
function Foursquare(clientID, clientSecret) {
  this.clientID = clientID;
  this.clientSecret = clientSecret;
}

/**
 * Authenticates this instance of Foursquare
 */
Foursquare.prototype.explore = function (lat, lng, price, section) {
  return request({
    method: 'GET',
    json: true,
    uri: 'https://api.foursquare.com/v2/venues/explore',
    qs: {
      ll: lat + ',' + lng,
      client_id: this.clientID,
      client_secret: this.clientSecret,
      v: 20151216,
      price: price,
      section: section
    }
  });
};

module.exports = Foursquare;
<commit_msg>Updated latitute/longitude accuracy to 100 meters.<commit_after>var request = require('request-promise');

/**
 * Creats a new foursquare client
 */
function Foursquare(clientID, clientSecret) {
  this.clientID = clientID;
  this.clientSecret = clientSecret;
}

/**
 * Authenticates this instance of Foursquare
 */
Foursquare.prototype.explore = function (lat, lng, price, section) {
  return request({
    method: 'GET',
    json: true,
    uri: 'https://api.foursquare.com/v2/venues/explore',
    qs: {
      ll: lat + ',' + lng,
      llAcc: 100,
      client_id: this.clientID,
      client_secret: this.clientSecret,
      v: 20151216,
      price: price,
      section: section
    }
  });
};

module.exports = Foursquare;
<|endoftext|>