<commit_before>'use strict';

var rewire  = require('rewire'),
    factory = require('./support/factory'),
    F       = require('fkit'),
    World   = rewire('../src/world');

var core = World.__get__('core');

// Stub each call to the `rollDice` function with the return values in the
// list of `xss`.
var stubRollDice = F.variadic(function(sandbox, xss) {
  var stub = sandbox.stub(core, 'rollDice');
  xss.map(function(xs, i) { stub.onCall(i).returns(xs); });
});

function find(as, bs) {
  return bs.map(function(q) {
    return F.find(comparator(q), as);
  });

  function comparator(p) {
    return F.compose(F.eq(p.id), F.get('id'));
  }
}

function move(world, a, b) {
  var result = world.move(a, b);
  return find(result.countries, [a, b]);
}

function attack(world, a, b) {
  var result = world.attack(a, b);
  return find(result.countries, [a, b]);
}

function reinforce(world, a, b, c) {
  var result = world.reinforce([a, b, c]);
  return find(result.countries, [a, b, c]);
}

describe('World', function() {
  var sandbox, x, y, z;

  // Player stubs.
  var p = {}, q = {};

  // Country stubs.
  var p1 = factory.buildCountry(1, p, [], 4, 4),
      p2 = factory.buildCountry(2, p, [], 2, 3),
      p3 = factory.buildCountry(3, p, [], 1, 2),
      q1 = factory.buildCountry(4, q, [], 2, 2);

  var world = factory.buildWorld([p1, p2, p3, q1]);

  beforeEach(function() {
    sandbox = sinon.sandbox.create();
  });

  afterEach(function() {
    sandbox.restore();
  });

  describe('#move', function() {
    beforeEach(function() {
      var result = move(world, p1, q1);

      x = result[0];
      y = result[1];
    });

    it('should move to the target country', function() {
      expect(x.player).to.equal(p);
      expect(y.player).to.equal(p);
    });

    it('should distribute the armies', function() {
      expect(x.armies).to.equal(2);
      expect(y.armies).to.equal(2);
    });
  });

  describe('#attack', function() {
    context('when the attacker rolls higher than the defender', function() {
      beforeEach(function() {
        stubRollDice(sandbox, [4, 3, 2, 1], [4, 3]);

        var result = attack(world, p1, q1);

        x = result[0];
        y = result[1];
      });

      it('should move the attacker to target country', function() {
        expect(x.player).to.equal(p);
        expect(y.player).to.equal(p);
      });

      it('should update the armies', function() {
        expect(x.armies).to.equal(2);
        expect(y.armies).to.equal(1);
      });
    });

    context('when the defender rolls equal to the attacker', function() {
      beforeEach(function() {
        stubRollDice(sandbox, [5, 1, 1, 1], [4, 4]);

        var result = attack(world, p1, q1);

        x = result[0];
        y = result[1];
      });

      it('should not move the attacker', function() {
        expect(x.player).to.equal(p);
        expect(y.player).to.equal(q);
      });

      it('should update the armies', function() {
        expect(x.armies).to.equal(3);
        expect(y.armies).to.equal(1);
      });
    });
  });

  describe('#reinforce', function() {
    it('should reinforce the countries', function() {
      sandbox.stub(core, 'distribute').returns([0, 1, 2]);

      var result = reinforce(world, p1, p2, p3);

      x = result[0];
      y = result[1];
      z = result[2];

      expect(x.armies).to.equal(4);
      expect(y.armies).to.equal(3);
      expect(z.armies).to.equal(2);
    });
  });
});
<commit_msg>Update World#attack tests.<commit_after>'use strict';

var rewire  = require('rewire'),
    factory = require('./support/factory'),
    F       = require('fkit'),
    World   = rewire('../src/world');

var core = World.__get__('core');

// Stub each call to the `rollDice` function with the return values in the
// list of `xss`.
var stubRollDice = F.variadic(function(sandbox, xss) {
  var stub = sandbox.stub(core, 'rollDice');
  xss.map(function(xs, i) { stub.onCall(i).returns(xs); });
});

function find(as, bs) {
  return bs.map(function(q) {
    return F.find(comparator(q), as);
  });

  function comparator(p) {
    return F.compose(F.eq(p.id), F.get('id'));
  }
}

function move(world, a, b) {
  var result = world.move(a, b);
  return find(result.countries, [a, b]);
}

function attack(world, a, b) {
  var result = world.attack(a, b);
  return find(result.countries, [a, b]);
}

function reinforce(world, a, b, c) {
  var result = world.reinforce([a, b, c]);
  return find(result.countries, [a, b, c]);
}

describe('World', function() {
  var sandbox, x, y, z;

  // Player stubs.
  var p = {}, q = {};

  // Country stubs.
  var p1 = factory.buildCountry(1, p, [], 4, 4),
      p2 = factory.buildCountry(2, p, [], 2, 3),
      p3 = factory.buildCountry(3, p, [], 1, 2),
      q1 = factory.buildCountry(4, q, [], 2, 2);

  var world = factory.buildWorld([p1, p2, p3, q1]);

  beforeEach(function() {
    sandbox = sinon.sandbox.create();
  });

  afterEach(function() {
    sandbox.restore();
  });

  describe('#move', function() {
    beforeEach(function() {
      var result = move(world, p1, q1);

      x = result[0];
      y = result[1];
    });

    it('should move to the target country', function() {
      expect(x.player).to.equal(p);
      expect(y.player).to.equal(p);
    });

    it('should distribute the armies', function() {
      expect(x.armies).to.equal(2);
      expect(y.armies).to.equal(2);
    });
  });

  describe('#attack', function() {
    context('when the attacker rolls higher than the defender', function() {
      beforeEach(function() {
        stubRollDice(sandbox, [6, 4, 2, 1], [6, 5]);

        var result = attack(world, p1, q1);

        x = result[0];
        y = result[1];
      });

      it('should move the attacker to target country', function() {
        expect(x.player).to.equal(p);
        expect(y.player).to.equal(p);
      });

      it('should update the armies', function() {
        expect(x.armies).to.equal(2);
        expect(y.armies).to.equal(1);
      });
    });

    context('when the attacker rolls equal to the defender', function() {
      beforeEach(function() {
        stubRollDice(sandbox, [5, 1, 1, 1], [6, 4]);

        var result = attack(world, p1, q1);

        x = result[0];
        y = result[1];
      });

      it('should not move the attacker', function() {
        expect(x.player).to.equal(p);
        expect(y.player).to.equal(q);
      });

      it('should update the armies', function() {
        expect(x.armies).to.equal(2);
        expect(y.armies).to.equal(2);
      });
    });

    context('when the attacker rolls lower than the defender', function() {
      beforeEach(function() {
        stubRollDice(sandbox, [5, 2, 1, 1], [6, 4]);

        var result = attack(world, p1, q1);

        x = result[0];
        y = result[1];
      });

      it('should not move the attacker', function() {
        expect(x.player).to.equal(p);
        expect(y.player).to.equal(q);
      });

      it('should update the armies', function() {
        expect(x.armies).to.equal(2);
        expect(y.armies).to.equal(2);
      });
    });
  });

  describe('#reinforce', function() {
    it('should reinforce the countries', function() {
      sandbox.stub(core, 'distribute').returns([0, 1, 2]);

      var result = reinforce(world, p1, p2, p3);

      x = result[0];
      y = result[1];
      z = result[2];

      expect(x.armies).to.equal(4);
      expect(y.armies).to.equal(3);
      expect(z.armies).to.equal(2);
    });
  });
});
<|endoftext|>


<commit_before>define(['lodash', 'jquery', 'jquery.form', 'models/Card'], function(_, $, $form, Card) {

    // This module sets up the card form used for adding new cards to a deck.
    // Uses the jquery.form plugin to AJAXify the html form.
    var CardForm = function(config) {
        if(!config || !config['formEl'] || !config['formMessageEl']) {
            throw new Error("invalid or missing CardForm config");
        }
        this.formEl = $(config.formEl);
        this.formMessageEl = $(config.formMessageEl);
		this.error = $.proxy(this.error, this);
		this.success = $.proxy(this.success, this);
    };

    CardForm.prototype.init = function() {
        // bind these methods to the "this" context since they
        // will be passed to the jQuery form plugin
        _.bindAll(this, ['beforeSubmit', 'success', 'error']);

        // use the jQuery.form plugin to AJAXify the form
        this.formEl.ajaxForm({
            resetForm: true,
            beforeSubmit: this.beforeSubmit,
            error: this.error,
            success: this.success
        });
	};

    // Status types for showing messages (constants)
    var MSG_INFO = CardForm.MSG_INFO = "info";
    var MSG_SUCCESS = CardForm.MSG_SUCCESS = "success";
    var MSG_ERROR = CardForm.MSG_ERROR = "error";

    CardForm.prototype.beforeSubmit = function() {
        this.msg("Saving card...", MSG_INFO);
    };

    CardForm.prototype.success = function(data, statusText, xhr, formEl) {
        //console.log("success", arguments);
        this.msg("Card saved. Refresh.", MSG_SUCCESS);
    };

    CardForm.prototype.error = function(xhr, textStatus, errorThrown) {
        this.msg("Card error: " + textStatus, MSG_ERROR);
    };

    // Displays a message about the status of the form.
    CardForm.prototype.msg = function(html, statusType) {
        var css, css_for = {};
        css_for[MSG_SUCCESS] = {color:"green"};
        css_for[MSG_ERROR] = {color:"red"};
        css_for[MSG_INFO] = {color:"black"};

        css = css_for[statusType];
        if(!css) {
            css = css_for[MSG_INFO];
        }

        this.formMessageEl.css(css).html(html);
    };

    return CardForm;
});
<commit_msg>no card model yet<commit_after>define(['lodash', 'jquery', 'jquery.form'], function(_, $, $form) {

    // This module sets up the card form used for adding new cards to a deck.
    // Uses the jquery.form plugin to AJAXify the html form.
    var CardForm = function(config) {
        if(!config || !config['formEl'] || !config['formMessageEl']) {
            throw new Error("invalid or missing CardForm config");
        }
        this.formEl = $(config.formEl);
        this.formMessageEl = $(config.formMessageEl);
		this.error = $.proxy(this.error, this);
		this.success = $.proxy(this.success, this);
    };

    CardForm.prototype.init = function() {
        // bind these methods to the "this" context since they
        // will be passed to the jQuery form plugin
        _.bindAll(this, ['beforeSubmit', 'success', 'error']);

        // use the jQuery.form plugin to AJAXify the form
        this.formEl.ajaxForm({
            resetForm: true,
            beforeSubmit: this.beforeSubmit,
            error: this.error,
            success: this.success
        });
	};

    // Status types for showing messages (constants)
    var MSG_INFO = CardForm.MSG_INFO = "info";
    var MSG_SUCCESS = CardForm.MSG_SUCCESS = "success";
    var MSG_ERROR = CardForm.MSG_ERROR = "error";

    CardForm.prototype.beforeSubmit = function() {
        this.msg("Saving card...", MSG_INFO);
    };

    CardForm.prototype.success = function(data, statusText, xhr, formEl) {
        //console.log("success", arguments);
        this.msg("Card saved. Refresh.", MSG_SUCCESS);
    };

    CardForm.prototype.error = function(xhr, textStatus, errorThrown) {
        this.msg("Card error: " + textStatus, MSG_ERROR);
    };

    // Displays a message about the status of the form.
    CardForm.prototype.msg = function(html, statusType) {
        var css, css_for = {};
        css_for[MSG_SUCCESS] = {color:"green"};
        css_for[MSG_ERROR] = {color:"red"};
        css_for[MSG_INFO] = {color:"black"};

        css = css_for[statusType];
        if(!css) {
            css = css_for[MSG_INFO];
        }

        this.formMessageEl.css(css).html(html);
    };

    return CardForm;
});
<|endoftext|>


<commit_before>'use strict';

/**
* Subject controller definition
* @scope Controllers
*/
define(['./module'], function (models) {
  models.factory('Schedule', function ($http, SubjectService) {
    var HEADING_ONE = Math.pow(2,25);

    /*
     * transpose an schedule matrix
     */
    var transpose = function(arr, schedItem) {
      var trans = [];
      _.each(arr, function(row, x){
        _.each(row, function(col, y){
          if (!trans[y]) { trans[y] = [] };
          if (col === '1'){
            trans[y][x] = schedItem;
          } else {
            trans[y][x] = {};
          }
        });
      });
      return trans;
    };
    /*
     * concatenates 2 schedules
     * this does not validate the schedules
     */
    var sumMatrix = function(arr1, arr2) {
      _.each(arr1, function(col, x){
        _.each(col, function(row, y){
          if (!_.isEmpty(arr2[x][y])) {
            arr1[x][y] = arr2[x][y];
          }
        });
      });
      return arr1;
    };

    function ScheduleThumbnail(w,h){
        this.w = w;
        this.h = h;
        this.color = {
                    "turquoise": "#1abc9c",
                    "emerland": "#2ecc71",
                    "peter-river": "#3498db",
                    "amethyst": "#9b59b6",
                    "wet-asphalt": "#34495e",
                    "green-sea": "#16a085",
                    "nephritis": "#27ae60",
                    "belize-hole": "#2980b9",
                    "wisteria": "#8e44ad",
                    "midnight-blue": "#2c3e50",
                    "sun-flower": "#f1c40f",
                    "carrot": "#e67e22",
                    "alizarin": "#e74c3c",
                    "clouds": "#ecf0f1",
                    "concrete": "#95a5a6",
                    "orange": "#f39c12",
                    "pumpkin": "#d35400",
                    "pomegranate": "#c0392b",
                    "silver": "#bdc3c7",
                    "asbestos": "#7f8c8d"};
    }

    ScheduleThumbnail.prototype.draw = function (context,schedules,x,y,lineWidth){
        context.beginPath();
        context.rect(x, y, this.w, this.h);
        context.fillStyle = 'white';
        context.fill();
        context.lineWidth = lineWidth;
        context.strokeStyle = 'black';
        context.stroke();
        var dayWidth = this.w / 7.0;
        var hourHeight = this.h / 24.0;
        context.beginPath();
        context.lineWidth = lineWidth/2;
        for(var i=0;i<7;i++){
            context.moveTo(x+(i*dayWidth),y);
            context.lineTo(x+(i*dayWidth),y+this.h);
            context.stroke();
        }
        context.moveTo(x,y+this.h/2);
        context.lineTo(x+this.w,y+this.h/2);
        context.stroke();

        context.lineWidth = 0;
        for(var s in schedules){

            var lx = x;
            var ly = y;
            context.beginPath();
            context.fillStyle= this.color[schedules[s]["color"]];
            for (var t in schedules[s]["schedule"]){
                var hours = schedules[s]["schedule"][t];
                ly = y;
                for (var h in hours){
                    if(hours[h] == '1'){
                        context.rect(lx,ly,dayWidth,hourHeight);
                        context.fill();
                    }
                    ly += hourHeight;
                }
                lx += dayWidth;
                context.fill();
            }
        }
    }

    var canvas = document.createElement("canvas");
    canvas.width = 100;
    canvas.height= 50;
    var context = canvas.getContext('2d');
    var generator = new ScheduleThumbnail(100,50);

    var Schedule = function(schedItems){

      var that = this;
      /*
       * adds the heading zeros and transforms the values to binary for the
       * busy array returns a string
       */
      var decimalToSchedString = function(value){

        that.earlyHours = (value & 127) > 0 || false || that.earlyHours;
        that.lateHours  = (value & 15728640) > 0 || false || that.lateHours;
        return ( value + HEADING_ONE ).toString(2).substring(2).split('').reverse().join('');
      };

      var parseRows = function(){
        var scheduleMatrix = transpose(that.busy, { name : 'busy', class : 'busy'});
        _.each(that.groups, function(group){
          var gName = (_.isUndefined(group.subject)) ? 'no hay horario' : group.subject + '-' + group.code;
          var gClass = (_.isUndefined(group.color)) ? 'warning' : group.color;
          var schedT = transpose(group.schedule, {name: gName , color : gClass});
          scheduleMatrix = sumMatrix(scheduleMatrix, schedT);
        });
        that.rows = scheduleMatrix;

        //var groupsT = transpose(that.groups);
      };

      var draw = function(){
        console.log(that.groups);
        generator.draw(context,that.groups,0,0,1);
        return canvas.toDataURL();
      }

      angular.extend(this,{
        rows: schedule,
        earlyHours: false,
        lateHours: false,
        toString: '',
        subjects: [],
        groups: [],
        busy: [],
        thumbnail : draw,
        parseRows : parseRows
      });
      canvas.width = canvas.width;
      /*
       * lazy loading rows for better performance
       */
      var rows =  new Array(24);
      _.each(rows, function(row){
        row = [];
        var cols = new Array(7);
        row.push(cols);
      });
      var schedule = rows;
      /*
       * TODO: get the appropiate busy code here
       */
      var dummyBusy = [0,0,0,0,0,0,0];

      dummyBusy.forEach(function(item){
        that.busy.push(decimalToSchedString(item));
      });

      schedItems.groups.forEach(function(group){
        var  s = [];
        group.schedule.forEach(function(item){
          s.push(decimalToSchedString(item));
        });
        var g = SubjectService.getByCode(group.subject);
        that.groups.push({
          subject: g.code,
          code: group.code,
          schedule: s ,
          color: g.color,
          dept : g.departament
        });
        that.subjects.push(g);

      });
    };
    return Schedule;
  });
});
<commit_msg>Rounding edges of schedule<commit_after>'use strict';

/**
* Subject controller definition
* @scope Controllers
*/
define(['./module'], function (models) {
  models.factory('Schedule', function ($http, SubjectService) {
    var HEADING_ONE = Math.pow(2,25);

    /*
     * transpose an schedule matrix
     */
    var transpose = function(arr, schedItem) {
      var trans = [];
      _.each(arr, function(row, x){
        _.each(row, function(col, y){
          if (!trans[y]) { trans[y] = [] };
          if (col === '1'){
            trans[y][x] = schedItem;
          } else {
            trans[y][x] = {};
          }
        });
      });
      return trans;
    };
    /*
     * concatenates 2 schedules
     * this does not validate the schedules
     */
    var sumMatrix = function(arr1, arr2) {
      _.each(arr1, function(col, x){
        _.each(col, function(row, y){
          if (!_.isEmpty(arr2[x][y])) {
            arr1[x][y] = arr2[x][y];
          }
        });
      });
      return arr1;
    };

    function ScheduleThumbnail(w,h){
        this.w = w;
        this.h = h;
        this.color = {
                    "turquoise": "#1abc9c",
                    "emerland": "#2ecc71",
                    "peter-river": "#3498db",
                    "amethyst": "#9b59b6",
                    "wet-asphalt": "#34495e",
                    "green-sea": "#16a085",
                    "nephritis": "#27ae60",
                    "belize-hole": "#2980b9",
                    "wisteria": "#8e44ad",
                    "midnight-blue": "#2c3e50",
                    "sun-flower": "#f1c40f",
                    "carrot": "#e67e22",
                    "alizarin": "#e74c3c",
                    "clouds": "#ecf0f1",
                    "concrete": "#95a5a6",
                    "orange": "#f39c12",
                    "pumpkin": "#d35400",
                    "pomegranate": "#c0392b",
                    "silver": "#bdc3c7",
                    "asbestos": "#7f8c8d"};
    }

    ScheduleThumbnail.prototype.draw = function (context,schedules,x,y,lineWidth){

        function roundedRect(x, y, w, h, r,context){
            context.beginPath();
            context.moveTo(x+r, y);
            context.lineTo(x+w-r, y);
            context.quadraticCurveTo(x+w, y, x+w, y+r);
            context.lineTo(x+w, y+h-r);
            context.quadraticCurveTo(x+w, y+h, x+w-r, y+h);
            context.lineTo(x+r, y+h);
            context.quadraticCurveTo(x, y+h, x, y+h-r);
            context.lineTo(x, y+r);
            context.quadraticCurveTo(x, y, x+r, y);
        }

        context.fillStyle = 'white';
        context.lineWidth = lineWidth;
        context.strokeStyle = 'gray';
        roundedRect(x, y, this.w, this.h,10,context);
        context.fill();
        context.stroke();
        var dayWidth = this.w / 7.0;
        var hourHeight = this.h / 24.0;

        context.lineWidth = 0;
        for(var s in schedules){

            var lx = x;
            var ly = y;
            context.beginPath();
            context.fillStyle= this.color[schedules[s]["color"]];
            for (var t in schedules[s]["schedule"]){
                var hours = schedules[s]["schedule"][t];
                ly = y;
                for (var h in hours){
                    if(hours[h] == '1'){
                        context.rect(lx,ly,dayWidth,hourHeight);
                        context.fill();
                    }
                    ly += hourHeight;
                }
                lx += dayWidth;
                context.fill();
            }
        }
        context.linWidth = lineWidth;
        context.beginPath();
        context.lineWidth = lineWidth/2;
        for(var i=1;i<7;i++){
            context.moveTo(x+(i*dayWidth),y);
            context.lineTo(x+(i*dayWidth),y+this.h);
            context.stroke();
        }
        context.moveTo(x,y+this.h/2);
        context.lineTo(x+this.w,y+this.h/2);
        context.stroke();
    }

    var canvas = document.createElement("canvas");
    canvas.width = 110;
    canvas.height= 55;
    var context = canvas.getContext('2d');
    var generator = new ScheduleThumbnail(100,50);

    var Schedule = function(schedItems){

      var that = this;
      /*
       * adds the heading zeros and transforms the values to binary for the
       * busy array returns a string
       */
      var decimalToSchedString = function(value){

        that.earlyHours = (value & 127) > 0 || false || that.earlyHours;
        that.lateHours  = (value & 15728640) > 0 || false || that.lateHours;
        return ( value + HEADING_ONE ).toString(2).substring(2).split('').reverse().join('');
      };

      var parseRows = function(){
        var scheduleMatrix = transpose(that.busy, { name : 'busy', class : 'busy'});
        _.each(that.groups, function(group){
          var gName = (_.isUndefined(group.subject)) ? 'no hay horario' : group.subject + '-' + group.code;
          var gClass = (_.isUndefined(group.color)) ? 'warning' : group.color;
          var schedT = transpose(group.schedule, {name: gName , color : gClass});
          scheduleMatrix = sumMatrix(scheduleMatrix, schedT);
        });
        that.rows = scheduleMatrix;

        //var groupsT = transpose(that.groups);
      };

      var draw = function(){
        console.log(that.groups);
        generator.draw(context,that.groups,1,1,0.5);
        return canvas.toDataURL();
      }

      angular.extend(this,{
        rows: schedule,
        earlyHours: false,
        lateHours: false,
        toString: '',
        subjects: [],
        groups: [],
        busy: [],
        thumbnail : draw,
        parseRows : parseRows
      });
      canvas.width = canvas.width;
      /*
       * lazy loading rows for better performance
       */
      var rows =  new Array(24);
      _.each(rows, function(row){
        row = [];
        var cols = new Array(7);
        row.push(cols);
      });
      var schedule = rows;
      /*
       * TODO: get the appropiate busy code here
       */
      var dummyBusy = [0,0,0,0,0,0,0];

      dummyBusy.forEach(function(item){
        that.busy.push(decimalToSchedString(item));
      });

      schedItems.groups.forEach(function(group){
        var  s = [];
        group.schedule.forEach(function(item){
          s.push(decimalToSchedString(item));
        });
        var g = SubjectService.getByCode(group.subject);
        that.groups.push({
          subject: g.code,
          code: group.code,
          schedule: s ,
          color: g.color,
          dept : g.departament
        });
        that.subjects.push(g);

      });
    };
    return Schedule;
  });
});
<|endoftext|>


<commit_before>/*global $,_,document,window,console,escape,Backbone,exports,WebSocket */
/*jslint vars:true todo:true sloppy:true */

(function() {
	console.log('loading select-tag');
	angular
		.module('webbox-widgets')
		.directive('indxSelectVal', function() {
			return {
				restrict: 'E',
				templateUrl:'/components/select-tag/select-tag.html',
				controller:function($scope, $attrs, webbox) {
					console.log('controller');
					var store, u, $sa, model; // private, keep it out of the scope.

					$scope.model_id = $attrs.modelId;
					$scope.box_id = $attrs.boxId;
					$scope.property = $attrs.property;
					$scope.values = [];

					var ctx = { scope: $scope.model_id };

					$scope._reload = function() {
						console.log('reload >> '); // , $scope.model_id, $scope.box_id, $scope.property, $attrs );
						var reload = arguments.callee;
						if (store === undefined ||
							$scope.box_id === undefined ||
							$scope.model_id === undefined ||
							$scope.property === undefined) { return ; }

						var box = $scope.box = store.get_box($scope.box_id);
						box.fetch().then(function(box) {
							box.get_obj($scope.model_id)
								.then(function(_m) {
									if (model) { model.off(null, null, ctx); }
									model = _m;
									window.model = model; // TODO: DEBUG!
									model.on('change', function() { $sa(reload); }, ctx);
									$sa(function() {
										$scope.values = (model.get($scope.property) || []).concat();
										console.log('values are ', $scope.values, $scope.property, model.get($scope.property));
									});
								}).fail(function(err) {	u.error('box fetch error ', err);	});
						}).fail(function(err) {	u.error('select error ', err);	});
					};
					$scope.option_string = function(v) {
						// turns value
						if (_.isObject(v) && v instanceof webbox.Obj) { return v.id; }
						if (_.isString(v)) { return v; }
						return v.toString();
					};
					$scope.option_value = function(v) {
						// turns value
						if (_.isObject(v) && v instanceof webbox.Obj) { return v.id; }
						if (_.isString(v)) { return v; }
						return v.toString();
					};
					$scope.option_type = function(v) {
						// turns value
						if (_.isObject(v) && v instanceof webbox.Obj) { return 'resource'; }
						if (_.isObject(v) && v instanceof webbox.File) { return 'file'; }
						if (_.isNumber(v)) { return 'number'; }
						if (_.isString(v)) { return 'string'; }
						return 'unknown';
					};
					webbox.loaded.then(function(_s) {
						u = _s.u;
						store = _s.store;
						$sa = $scope.$sa = function(f) { _s.safe_apply($scope, f); };
						$sa($scope._reload);
					});
				},
				link:function($scope, $element) {
					// add listeners here
					var $el = $element; // .select2({allowClear:true});
					$scope.$watch('box_id', $scope._reload);
					$scope.$watch('model_id', $scope._reload);
					$scope.$watch('property', $scope._reload);
					$el.on('change', function(evt) {
						var selected = $(evt.currentTarget).find(':selected');
						u.when(selected.map(function(x) {
							var v = $(this).attr('value'),
							t = $(this).attr('option-type'),
							d = u.deferred();
							if (t == 'resource') { return $scope.box.get_obj(v);}
							if (t == 'string') {	d.resolve(v.toString()); }
							if (t == 'number') {	d.resolve(parseFloat(v)); }
							else { d.resolve(v); }
							return d.promise();
						}).get()).then(function(vals) {
							$scope.$sa(function() {
								console.log('seleeeeeeeect!', vals);
								$scope.selected = vals;
							});
						});
					});
					$el.find('select').select2();
					console.log('link done');
				}
			}
		});
}());
<commit_msg>more progress on select<commit_after>/*global $,_,document,window,console,escape,Backbone,exports,WebSocket */
/*jslint vars:true todo:true sloppy:true */

(function() {
	console.log('loading select-tag');
	angular
		.module('webbox-widgets')
		.directive('indxSelectVal', function() {
			return {
				restrict: 'E',
				templateUrl:'/components/select-tag/select-tag.html',
				controller:function($scope, $attrs, webbox) {
					console.log('controller');

					var store, u, $sa, model; // private, keep it out of the scope.

					$scope.model_id = $attrs.srcModelId;
					$scope.box_id = $attrs.srcBoxId;
					$scope.property = $attrs.srcProperty;
					$scope.model = $attrs.model;
					$scope.values = [];

					var ctx = { scope: $scope.model_id };

					$scope._reload = function() {
						console.log('reload >> '); // , $scope.model_id, $scope.box_id, $scope.property, $attrs );
						var reload = arguments.callee;
						if (store === undefined ||
							$scope.box_id === undefined ||
							$scope.model_id === undefined ||
							$scope.property === undefined) { return ; }

						var box = $scope.box = store.get_box($scope.box_id);
						box.fetch().then(function(box) {
							box.get_obj($scope.model_id)
								.then(function(_m) {
									if (model) { model.off(null, null, ctx); }
									model = _m;
									window.model = model; // TODO: DEBUG!
									model.on('change', function() { $sa(reload); }, ctx);
									$sa(function() {
										$scope.values = (model.get($scope.property) || []).concat();
										console.log('values are ', $scope.values, $scope.property, model.get($scope.property));
									});
								}).fail(function(err) {	u.error('box fetch error ', err);	});
						}).fail(function(err) {	u.error('select error ', err);	});
					};
					$scope.option_string = function(v) {
						// turns value
						if (_.isObject(v) && v instanceof webbox.Obj) { return v.id; }
						if (_.isString(v)) { return v; }
						return v.toString();
					};
					$scope.option_value = function(v) {
						// turns value
						if (_.isObject(v) && v instanceof webbox.Obj) { return v.id; }
						if (_.isString(v)) { return v; }
						return v.toString();
					};
					$scope.option_type = function(v) {
						// turns value
						if (_.isObject(v) && v instanceof webbox.Obj) { return 'resource'; }
						if (_.isObject(v) && v instanceof webbox.File) { return 'file'; }
						if (_.isNumber(v)) { return 'number'; }
						if (_.isString(v)) { return 'string'; }
						return 'unknown';
					};
					$scope.option_value_to_raw = function(v, option_type) {
						var d = u.deferred(), t = option_type;
						if (t == 'resource') { return $scope.box.get_obj(v);}
						if (t == 'string') { d.resolve(v.toString()); }
						if (t == 'number') { d.resolve(parseFloat(v)); }
						else { d.resolve(v); }
						return d.promise();
					};

					// initialise
					webbox.loaded.then(function(_s) {
						u = _s.u;
						store = _s.store;
						$sa = $scope.$sa = function(f) { _s.safe_apply($scope, f); };
						$sa($scope._reload);
					});

				},
				link:function($scope, $element) {
					// add listeners here
					var $el = $element; // .select2({allowClear:true});
					$scope.$watch('box_id', $scope._reload);
					$scope.$watch('model_id', $scope._reload);
					$scope.$watch('property', $scope._reload);
					$el.on('change', function(evt) {
						var selected = $(evt.currentTarget).find(':selected');
						u.when(selected.map(function(x) {
							return $scope.option_value_to_raw($(this).attr('value'),$(this).attr('option-type'));
						}).get()).then(function(vals) {
							$scope.$sa(function() {
								console.log('seleeeeeeeect! - setting ', $scope.model, vals);
								$scope.$parent[$scope.model] = vals;

							});
						});
					});
					$el.find('select').select2();
					console.log('link done');
				}
			}
		});
}());
<|endoftext|>


<commit_before>(function() {
    /**
     * Represents a TextLayer.
     * @param id
     * @extends IB.Layer
     * @constructor
     */
    IB.TextLayer = function(id) {
        IB.Layer.call(this, id);
        this._node.addClass('ib-textlayer');

        _.extend(this._properties, {
            text: new IB.Properties.Text("Text", "Text layer"),
            font: new IB.Properties.Font("Font", "GOTHIC_14"),
            fg: new IB.Properties.Colour("Text colour", IB.ColourBlack),
            bg: new IB.Properties.Colour("Background", IB.ColourWhite),
            align: new IB.Properties.MultipleChoice("Alignment", {
                "GTextAlignmentLeft": "Left",
                "GTextAlignmentCenter": "Centre",
                "GTextAlignmentRight": "Right"
            }, "GTextAlignmentLeft"),
        });
        this._text = this._properties.text;
        this._textColour = this._properties.fg;
        this._backgroundColour = this._properties.bg;
        this._align = this._properties.align;
        this._font = this._properties.font;
        this._propListener(this._text, 'textChange');
        this._propListener(this._textColour, 'textColourChange');
        this._propListener(this._backgroundColour, 'backgroundColourChange');
        this._propListener(this._align, 'alignmentChange');
        this._propListener(this._font, 'fontChange');

        this.setSize(100, 20);
    };
    IB.TextLayer.prototype = Object.create(IB.Layer.prototype);
    IB.TextLayer.prototype.constructor = IB.TextLayer;
    IB.TextLayer.layerClass = 'TextLayer';
    _.extend(IB.TextLayer.prototype, {
        render: function(parent) {
            IB.Layer.prototype.render.call(this, parent);
            this._node.css({
                'background-color': this._backgroundColour.getValue().css,
                color: this._textColour.getValue().css,
                'text-align': {
                    "GTextAlignmentLeft": "left",
                    "GTextAlignmentCenter": "center",
                    "GTextAlignmentRight": "right"
                }[this._align.getValue()]
            });
            this._node.css(this._font.getCSS());
            this._node.text(this._font.filterText(this._text.getValue()).replace(/ /g, '\u00a0\u200B'));
        },
        setText: function(text) {
            this._text.setValue(text);
        },
        getText: function() {
            return this._text.getValue();
        },
        setTextColour: function(colour) {
            this._textColour.setValue(colour);
        },
        setBackgroundColour: function(colour) {
            this._backgroundColour.setValue(colour);
        },
        generateDeclaration: function() {
            return ["static TextLayer *" + this._ID + ";"];
        },
        generateInitialiser: function() {
            var init = [this._ID + " = text_layer_create(" + this.generateRect() + ");"];
            if(this._backgroundColour.getValue() != IB.ColourWhite) {
                init.push("text_layer_set_background_color(" + this._ID + ", " + this._backgroundColour.getValue().name + ");");
            }
            if(this._textColour.getValue() != IB.ColourBlack) {
                init.push("text_layer_set_text_color(" + this._ID + ", " + this._textColour.getValue().name + ");");
            }
            if(this._text.getValue() != "") {
                init.push("text_layer_set_text(" + this._ID + ", \"" + IB.escapeCString(this.getText()) + "\");");
            }
            if(this._align.getValue() != "GTextAlignLeft") {
                init.push("text_layer_set_text_alignment(" + this._ID + ", " + this._align.getValue() + ");");
            }
            if(this._font.getValue() != "GOTHIC_14") {
                init.push("text_layer_set_font(" + this._ID + ", fonts_get_system_font(" + this._font.getValue() + "));");
            }
            return init;
        },
        generateDestructor: function() {
            return ["text_layer_destroy(" + this._ID + ");"];
        },
        readProperties: function(properties) {
            IB.Layer.prototype.readProperties.call(this, properties);
            _.each(properties, function(values, property) {
                switch(property) {
                    case "text_layer_set_background_color":
                        this.setBackgroundColour(IB.ColourMap[values[0][1]]);
                        break;
                    case "text_layer_set_text_color":
                        this.setTextColour(IB.ColourMap[values[0][1]]);
                        break;
                    case "text_layer_set_text":
                        this.setText(JSON.parse(values[0][0]));
                        break;
                    case "text_layer_set_text_alignment":
                        this._align.setValue(values[0][1]);
                        break;
                    case "text_layer_set_font":
                        if(/^fonts_get_system_font\(/.test(values[0])) {
                            this._font.setValue(values[0][0].substring(22, values[0][0].length - 1));
                        }
                        break;
                }
            }, this);
        }
    });

    IB.registry.register(IB.TextLayer);
})();
<commit_msg>Fix font naming.<commit_after>(function() {
    /**
     * Represents a TextLayer.
     * @param id
     * @extends IB.Layer
     * @constructor
     */
    IB.TextLayer = function(id) {
        IB.Layer.call(this, id);
        this._node.addClass('ib-textlayer');

        _.extend(this._properties, {
            text: new IB.Properties.Text("Text", "Text layer"),
            font: new IB.Properties.Font("Font", "GOTHIC_14"),
            fg: new IB.Properties.Colour("Text colour", IB.ColourBlack),
            bg: new IB.Properties.Colour("Background", IB.ColourWhite),
            align: new IB.Properties.MultipleChoice("Alignment", {
                "GTextAlignmentLeft": "Left",
                "GTextAlignmentCenter": "Centre",
                "GTextAlignmentRight": "Right"
            }, "GTextAlignmentLeft"),
        });
        this._text = this._properties.text;
        this._textColour = this._properties.fg;
        this._backgroundColour = this._properties.bg;
        this._align = this._properties.align;
        this._font = this._properties.font;
        this._propListener(this._text, 'textChange');
        this._propListener(this._textColour, 'textColourChange');
        this._propListener(this._backgroundColour, 'backgroundColourChange');
        this._propListener(this._align, 'alignmentChange');
        this._propListener(this._font, 'fontChange');

        this.setSize(100, 20);
    };
    IB.TextLayer.prototype = Object.create(IB.Layer.prototype);
    IB.TextLayer.prototype.constructor = IB.TextLayer;
    IB.TextLayer.layerClass = 'TextLayer';
    _.extend(IB.TextLayer.prototype, {
        render: function(parent) {
            IB.Layer.prototype.render.call(this, parent);
            this._node.css({
                'background-color': this._backgroundColour.getValue().css,
                color: this._textColour.getValue().css,
                'text-align': {
                    "GTextAlignmentLeft": "left",
                    "GTextAlignmentCenter": "center",
                    "GTextAlignmentRight": "right"
                }[this._align.getValue()]
            });
            this._node.css(this._font.getCSS());
            this._node.text(this._font.filterText(this._text.getValue()).replace(/ /g, '\u00a0\u200B'));
        },
        setText: function(text) {
            this._text.setValue(text);
        },
        getText: function() {
            return this._text.getValue();
        },
        setTextColour: function(colour) {
            this._textColour.setValue(colour);
        },
        setBackgroundColour: function(colour) {
            this._backgroundColour.setValue(colour);
        },
        generateDeclaration: function() {
            return ["static TextLayer *" + this._ID + ";"];
        },
        generateInitialiser: function() {
            var init = [this._ID + " = text_layer_create(" + this.generateRect() + ");"];
            if(this._backgroundColour.getValue() != IB.ColourWhite) {
                init.push("text_layer_set_background_color(" + this._ID + ", " + this._backgroundColour.getValue().name + ");");
            }
            if(this._textColour.getValue() != IB.ColourBlack) {
                init.push("text_layer_set_text_color(" + this._ID + ", " + this._textColour.getValue().name + ");");
            }
            if(this._text.getValue() != "") {
                init.push("text_layer_set_text(" + this._ID + ", \"" + IB.escapeCString(this.getText()) + "\");");
            }
            if(this._align.getValue() != "GTextAlignLeft") {
                init.push("text_layer_set_text_alignment(" + this._ID + ", " + this._align.getValue() + ");");
            }
            if(this._font.getValue() != "GOTHIC_14") {
                init.push("text_layer_set_font(" + this._ID + ", fonts_get_system_font(FONT_KEY_" + this._font.getValue() + "));");
            }
            return init;
        },
        generateDestructor: function() {
            return ["text_layer_destroy(" + this._ID + ");"];
        },
        readProperties: function(properties) {
            IB.Layer.prototype.readProperties.call(this, properties);
            _.each(properties, function(values, property) {
                switch(property) {
                    case "text_layer_set_background_color":
                        this.setBackgroundColour(IB.ColourMap[values[0][1]]);
                        break;
                    case "text_layer_set_text_color":
                        this.setTextColour(IB.ColourMap[values[0][1]]);
                        break;
                    case "text_layer_set_text":
                        this.setText(JSON.parse(values[0][0]));
                        break;
                    case "text_layer_set_text_alignment":
                        this._align.setValue(values[0][1]);
                        break;
                    case "text_layer_set_font":
                        if(/^fonts_get_system_font\(/.test(values[0])) {
                            this._font.setValue(values[0][0].substring(31, values[0][0].length - 1));
                        }
                        break;
                }
            }, this);
        }
    });

    IB.registry.register(IB.TextLayer);
})();
<|endoftext|>


<commit_before>var signalR = require("../../utils/signalr.1.0.js")

var connection;
var app = getApp()
var socketOpen = false;//WebSocket 打开状态
Page({
  data: {
    messageTip: '',
    messageTextArr: [],
    messageContent: 'TEST',
    userinfo: {}
  },
  //sendMessage
  formSubmit: function (e) {
    var that = this;
    console.log('formSubmit', e);
    var msg = e.detail.value.messageContent;//获得输入文字
    console.log('send message:' + msg);
    if (socketOpen) {

      //如果使用Senparc.WebSocket，必须严格按照以下data数据字段发送（只能多不能少）
      var submitData = JSON.stringify({
        Message: msg,//必填
        SessionId: wx.getStorageSync("sessionId"),//选填，不需要可输入''
        FormId: e.detail.formId//选填formId用于发送模板消息，不需要可输入''
      });

      // wx.sendSocketMessage({
      //   data: submitData
      // });

      connection.invoke("SendMessage", submitData).catch(function (err) {
        return console.error(err.toString());
      });

      that.setData({
        messageContent: ''
      })
    } else {
      that.setData({
        messageTip: 'WebSocket 链接失败，请重新连接！'
      })
    }
  },
  onLoad: function () {
    console.log('onLoad')
    var that = this

    // //连接 Websocket
    // wx.connectSocket({
    //   // url: wx.getStorageSync('wssDomainName') + '/SenparcWebSocket',
    //   url: wx.getStorageSync('wssDomainName') + '/SenparcHub',
    //   header:{
    //     'content-type': 'application/json'
    //   },
    //   method:"GET"
    // });

    connection = new signalR.HubConnectionBuilder().withUrl(wx.getStorageSync('wssDomainName') + "/SenparcHub").build();
    console.log(connection);

    connection.start().then(function () {
      console.log('ws started');
    }).catch(function (err) {
      return console.error(err.toString());
    });

    connection.on("ReceiveMessage", function (message) {
      console.log('收到服务器内容：' + message)
        // var jsonResult = JSON.parse(res.data);
        // var currentIndex = that.data.messageTextArr.length + 1;
        // var newArr = that.data.messageTextArr;
        // newArr.unshift(
        //   {
        //     index: currentIndex,
        //     content: jsonResult.content,
        //     time: jsonResult.time
        //   });
        console.log(that);
        that.setData({
          // messageTextArr: newArr
          messageTextArr: message
        });
    });

    //WebSocket 连接成功
    wx.onSocketOpen(function (res) {
      console.log('WebSocket 连接成功！')
      socketOpen = true;
      that.setData({
        messageTip: 'WebSocket 连接成功！'
      })
    })

    // //收到 WebSocket 推送消息
    // wx.onSocketMessage(function (res) {
    //   console.log('收到服务器内容：' + res.data)
    //   var jsonResult = JSON.parse(res.data);
    //   var currentIndex = that.data.messageTextArr.length + 1;
    //   var newArr = that.data.messageTextArr;
    //   newArr.unshift(
    //     {
    //       index: currentIndex,
    //       content: jsonResult.content,
    //       time: jsonResult.time
    //     });
    //   console.log(that);
    //   that.setData({
    //     messageTextArr: newArr
    //   });
    // })
    //WebSocket 已关闭
    wx.onSocketClose(function (res) {
      console.log('WebSocket 已关闭！')
      socketOpen = false;
    })
    //WebSocket 打开失败
    wx.onSocketError(function (res) {
      console.log('WebSocket连接打开失败，请检查！')
    })
  }
})
<commit_msg>完成signalr基础通讯<commit_after>var signalR = require("../../utils/signalr.1.0.js")

var connection;
var app = getApp()
var socketOpen = false;//WebSocket 打开状态
Page({
  data: {
    messageTip: '',
    messageTextArr: [],
    messageContent: 'TEST',
    userinfo: {}
  },
  //sendMessage
  formSubmit: function (e) {
    var that = this;
    console.log('formSubmit', e);
    var msg = e.detail.value.messageContent;//获得输入文字
    console.log('send message:' + msg);
    if (socketOpen) {

      //如果使用Senparc.WebSocket，必须严格按照以下data数据字段发送（只能多不能少）
      var submitData = JSON.stringify({
        Message: msg,//必填
        SessionId: wx.getStorageSync("sessionId"),//选填，不需要可输入''
        FormId: e.detail.formId//选填formId用于发送模板消息，不需要可输入''
      });

      // wx.sendSocketMessage({
      //   data: submitData
      // });

      connection.invoke("SendText", submitData).catch(function (err) {
        return console.error(err.toString());
      });

      that.setData({
        messageContent: ''
      })
    } else {
      that.setData({
        messageTip: 'WebSocket 链接失败，请重新连接！'
      })
    }
  },
  onLoad: function () {
    console.log('onLoad')
    var that = this

    // //连接 Websocket
    // wx.connectSocket({
    //   // url: wx.getStorageSync('wssDomainName') + '/SenparcWebSocket',
    //   url: wx.getStorageSync('wssDomainName') + '/SenparcHub',
    //   header:{
    //     'content-type': 'application/json'
    //   },
    //   method:"GET"
    // });

    connection = new signalR.HubConnectionBuilder().withUrl(wx.getStorageSync('wssDomainName') + "/SenparcHub").build();
    console.log(connection);

    connection.start().then(function () {
      console.log('ws started');
    }).catch(function (err) {
      return console.error(err.toString());
    });

    connection.on("ReceiveMessage", function (message) {
      console.log('收到服务器内容：' + message)
      var jsonResult = message//JSON.parse(message);
        var currentIndex = that.data.messageTextArr.length + 1;
        var newArr = that.data.messageTextArr;
        newArr.unshift(
          {
            index: currentIndex,
            content: jsonResult,// jsonResult.content,
            time: jsonResult.time
          });
        console.log(that);
        that.setData({
          messageTextArr: newArr
        });
    });

    //WebSocket 连接成功
    wx.onSocketOpen(function (res) {
      console.log('WebSocket 连接成功！')
      socketOpen = true;
      that.setData({
        messageTip: 'WebSocket 连接成功！'
      })
    })

    // //收到 WebSocket 推送消息
    // wx.onSocketMessage(function (res) {
    //   console.log('收到服务器内容：' + res.data)
    //   var jsonResult = JSON.parse(res.data);
    //   var currentIndex = that.data.messageTextArr.length + 1;
    //   var newArr = that.data.messageTextArr;
    //   newArr.unshift(
    //     {
    //       index: currentIndex,
    //       content: jsonResult.content,
    //       time: jsonResult.time
    //     });
    //   console.log(that);
    //   that.setData({
    //     messageTextArr: newArr
    //   });
    // })
    //WebSocket 已关闭
    wx.onSocketClose(function (res) {
      console.log('WebSocket 已关闭！')
      socketOpen = false;
    })
    //WebSocket 打开失败
    wx.onSocketError(function (res) {
      console.log('WebSocket连接打开失败，请检查！')
    })
  }
})
<|endoftext|>


<commit_before>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------

function printError(e) {
    print(e.name);
    print(e.number);
    print(e.description);
}

var isMac = (WScript.Platform && WScript.Platform.OS == 'darwin');

var expects = [
    '#1', // 0
    'In finally',
    'Error: Out of stack space', // 2
    '#2',
    'In finally', // 4
    'Error: Out of stack space',
    '#3', // 6
    'In finally',
    'Error: Out of stack space', // 8
    'testing stack overflow handling with catch block',
    'Error: Out of stack space', // 10
    'testing stack overflow handling with finally block',
    'Error: Out of stack space' ]; // 12

if (!isMac) // last test (sometimes) we hit timeout before we hit stackoverflow.
    expects.push('Error: Out of stack space')

expects.push('END');

var index = 0;
function printLog(str) {
    if (expects[index++] != str) {
        WScript.Echo('At ' + (index - 1) + ' expected \n' + expects[index - 1] + '\nOutput:' + str);
        WScript.Quit(1);
    }
}

for (var i = 1; i < 4; i++) {
    printLog("#" + i);
    try {
        try {
            function f() {
                f();
            }
            f();
        } finally {
            printLog("In finally");
        }
    }
    catch (e) {
        printLog(e);
    }
}

printLog("testing stack overflow handling with catch block");
try {
    function stackOverFlowCatch() {
        try {
            stackOverFlowCatch();
            while (true) {
            }

        }
        catch (e) {
            throw e;
        }
    }
    stackOverFlowCatch();
}
catch (e) {
    printLog(e);
}

printLog("testing stack overflow handling with finally block");
try
{
    function stackOverFlowFinally() {
        try {
            stackOverFlowFinally();
            while (true) {
            }
        }
        finally {
            DoSomething();
        }
    }
    stackOverFlowFinally();
}
catch(e) {
    printLog(e);
}

function DoSomething()
{
}

// 10K is not enough for our osx setup.
// for bigger numbers, we hit to timeout on CI (before we actually hit to S.O)
if (!isMac) {
    try
    {
        var count = 100000;

        var a = {};
        var b = a;

        for (var i = 0; i < count; i++)
        {
            a.x = {};
            a = a.x;
        }
        eval("JSON.stringify(b)");
    }
    catch(e) {
        printLog(e);
    }
}

printLog('END'); // do not remove this

WScript.Echo("Pass");
<commit_msg>[1.8>1.9] [MERGE #4640 @obastemur] stack/error: disable it partially for xplat CI<commit_after>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------

function printError(e) {
    print(e.name);
    print(e.number);
    print(e.description);
}

var isMac = (WScript.Platform && WScript.Platform.OS == 'darwin');
var isWin = (WScript.Platform && WScript.Platform.OS == 'win32');

var expects = [
    '#1', // 0
    'In finally',
    'Error: Out of stack space', // 2
    '#2',
    'In finally', // 4
    'Error: Out of stack space',
    '#3', // 6
    'In finally',
    'Error: Out of stack space' // 8
    ];

if (isWin) {
    expects.push('testing stack overflow handling with catch block'); // 9
    expects.push('Error: Out of stack space'); // 10
}

expects.push('testing stack overflow handling with finally block'); // 11
expects.push('Error: Out of stack space'); // 12

if (!isMac) // last test (sometimes) we hit timeout before we hit stackoverflow.
    expects.push('Error: Out of stack space'); // 13

expects.push('END'); // 14

var index = 0;
function printLog(str) {
    if (expects[index++] != str) {
        WScript.Echo('At ' + (index - 1) + ' expected \n' + expects[index - 1] + '\nOutput:' + str);
        WScript.Quit(1);
    }
}

for (var i = 1; i < 4; i++) {
    printLog("#" + i);
    try {
        try {
            function f() {
                f();
            }
            f();
        } finally {
            printLog("In finally");
        }
    }
    catch (e) {
        printLog(e);
    }
}

if (isWin) { // xplat CI timeouts (it doesn't st. overflows as soon as Windows does)
    printLog("testing stack overflow handling with catch block");
    try {
        function stackOverFlowCatch() {
            try {
                stackOverFlowCatch();
                while (true) { }
            }
            catch (e) {
                throw e;
            }
        }
        stackOverFlowCatch();
    }
    catch (e) {
        printLog(e);
    }
}

printLog("testing stack overflow handling with finally block");
try
{
    function stackOverFlowFinally() {
        try {
            stackOverFlowFinally();
            while (true) {
            }
        }
        finally {
            DoSomething();
        }
    }
    stackOverFlowFinally();
}
catch(e) {
    printLog(e);
}

function DoSomething()
{
}

// 10K is not enough for our osx setup.
// for bigger numbers, we hit to timeout on CI (before we actually hit to S.O)
if (!isMac) {
    try
    {
        var count = 100000;

        var a = {};
        var b = a;

        for (var i = 0; i < count; i++)
        {
            a.x = {};
            a = a.x;
        }
        eval("JSON.stringify(b)");
    }
    catch(e) {
        printLog(e);
    }
}

printLog('END'); // do not remove this

WScript.Echo("Pass");<|endoftext|>


<commit_before>var Crafty = require('./core.js'),
    document = window.document;

/**@
 * #Canvas
 * @category Graphics
 * @trigger Draw - when the entity is ready to be drawn to the stage - {type: "canvas", pos, co, ctx}
 * @trigger NoCanvas - if the browser does not support canvas
 *
 * When this component is added to an entity it will be drawn to the global canvas element. The canvas element (and hence all Canvas entities) is always rendered below any DOM entities.
 *
 * Crafty.canvas.init() will be automatically called if it is not called already to initialize the canvas element.
 *
 * Create a canvas entity like this
 * ~~~
 * var myEntity = Crafty.e("2D, Canvas, Color")
 *      .color("green")
 *      .attr({x: 13, y: 37, w: 42, h: 42});
 *~~~
 */
Crafty.c("Canvas", {

    init: function () {
        if (!Crafty.canvas.context) {
            Crafty.canvas.init();
        }

        //increment the amount of canvas objs
        Crafty.DrawManager.total2D++;
        //Allocate an object to hold this components current region
        this.currentRect = {};
        this._changed = true;
        Crafty.DrawManager.addCanvas(this);

        this.bind("Invalidate", function (e) {
            //flag if changed
            if (this._changed === false) {
                this._changed = true;
                Crafty.DrawManager.addCanvas(this);
            }

        });

        this.bind("Remove", function () {
            Crafty.DrawManager.total2D--;
            this._changed = true;
            Crafty.DrawManager.addCanvas(this);
        });
    },

    /**@
     * #.draw
     * @comp Canvas
     * @sign public this .draw([[Context ctx, ]Number x, Number y, Number w, Number h])
     * @param ctx - Canvas 2D context if drawing on another canvas is required
     * @param x - X offset for drawing a segment
     * @param y - Y offset for drawing a segment
     * @param w - Width of the segment to draw
     * @param h - Height of the segment to draw
     *
     * Method to draw the entity on the canvas element. Can pass rect values for redrawing a segment of the entity.
     */

    // Cache the various objects and arrays used in draw:
    drawVars: {
        type: "canvas",
        pos: {},
        ctx: null,
        coord: [0, 0, 0, 0],
        co: {
            x: 0,
            y: 0,
            w: 0,
            h: 0
        }

    },

    draw: function (ctx, x, y, w, h) {
        if (!this.ready) return;
        if (arguments.length === 4) {
            h = w;
            w = y;
            y = x;
            x = ctx;
            ctx = Crafty.canvas.context;
        }

        var pos = this.drawVars.pos;
        pos._x = (this._x + (x || 0));
        pos._y = (this._y + (y || 0));
        pos._w = (w || this._w);
        pos._h = (h || this._h);

        context = ctx || Crafty.canvas.context;
        coord = this.__coord || [0, 0, 0, 0];
        var co = this.drawVars.co;
        co.x = coord[0] + (x || 0);
        co.y = coord[1] + (y || 0);
        co.w = w || coord[2];
        co.h = h || coord[3];

        if (this._rotation !== 0) {
            context.save();

            context.translate(this._origin.x + this._x, this._origin.y + this._y);
            pos._x = -this._origin.x;
            pos._y = -this._origin.y;

            context.rotate((this._rotation % 360) * (Math.PI / 180));
        }

        if (this._flipX || this._flipY) {
            context.save();
            context.scale((this._flipX ? -1 : 1), (this._flipY ? -1 : 1));
            if (this._flipX) {
                pos._x = -(pos._x + pos._w);
            }
            if (this._flipY) {
                pos._y = -(pos._y + pos._h);
            }
        }

        var globalpha;

        //draw with alpha
        if (this._alpha < 1.0) {
            globalpha = context.globalAlpha;
            context.globalAlpha = this._alpha;
        }

        this.drawVars.ctx = context;
        this.trigger("Draw", this.drawVars);

        if (this._rotation !== 0 || (this._flipX || this._flipY)) {
            context.restore();
        }
        if (globalpha) {
            context.globalAlpha = globalpha;
        }
        return this;
    }
});

/**@
 * #Crafty.canvas
 * @category Graphics
 *
 * Collection of methods to draw on canvas.
 */
Crafty.extend({
    canvas: {
        /**@
         * #Crafty.canvas.context
         * @comp Crafty.canvas
         *
         * This will return the 2D context of the main canvas element.
         * The value returned from `Crafty.canvas._canvas.getContext('2d')`.
         */
        context: null,
        /**@
         * #Crafty.canvas._canvas
         * @comp Crafty.canvas
         *
         * Main Canvas element
         */

        /**@
         * #Crafty.canvas.init
         * @comp Crafty.canvas
         * @sign public void Crafty.canvas.init(void)
         * @trigger NoCanvas - triggered if `Crafty.support.canvas` is false
         *
         * Creates a `canvas` element inside `Crafty.stage.elem`. Must be called
         * before any entities with the Canvas component can be drawn.
         *
         * This method will automatically be called if no `Crafty.canvas.context` is
         * found.
         */
        init: function () {
            //check if canvas is supported
            if (!Crafty.support.canvas) {
                Crafty.trigger("NoCanvas");
                Crafty.stop();
                return;
            }

            //create an empty canvas element
            var c;
            c = document.createElement("canvas");
            c.width = Crafty.viewport.width;
            c.height = Crafty.viewport.height;
            c.style.position = 'absolute';
            c.style.left = "0px";
            c.style.top = "0px";

            Crafty.stage.elem.appendChild(c);
            Crafty.canvas.context = c.getContext('2d');
            Crafty.canvas._canvas = c;

            //Set any existing transformations
            var zoom = Crafty.viewport._scale;
            if (zoom != 1)
                Crafty.canvas.context.scale(zoom, zoom);

            // Set pixelart to current status, and listen for changes
            this._setPixelart(Crafty._pixelartEnabled);
            Crafty.uniqueBind("PixelartSet", this._setPixelart);

            //Bind rendering of canvas context (see drawing.js)
            Crafty.uniqueBind("RenderScene", Crafty.DrawManager.renderCanvas);

            Crafty.uniqueBind("ViewportResize", this._resize);
        },

        // Resize the canvas element to the current viewport
        _resize: function() {
            var c = Crafty.canvas._canvas;
            c.width = Crafty.viewport.width;
            c.height = Crafty.viewport.height;

        },

        _setPixelart: function(enabled){
            var context = Crafty.canvas.context;
            context.imageSmoothingEnabled = !enabled;
            context.mozImageSmoothingEnabled = !enabled;
            context.webkitImageSmoothingEnabled = !enabled;
            context.oImageSmoothingEnabled = !enabled;
            context.msImageSmoothingEnabled = !enabled;
        }

    }
});
<commit_msg>Fix a bug in canvas entity implementation when flipped and rotated<commit_after>var Crafty = require('./core.js'),
    document = window.document;

/**@
 * #Canvas
 * @category Graphics
 * @trigger Draw - when the entity is ready to be drawn to the stage - {type: "canvas", pos, co, ctx}
 * @trigger NoCanvas - if the browser does not support canvas
 *
 * When this component is added to an entity it will be drawn to the global canvas element. The canvas element (and hence all Canvas entities) is always rendered below any DOM entities.
 *
 * Crafty.canvas.init() will be automatically called if it is not called already to initialize the canvas element.
 *
 * Create a canvas entity like this
 * ~~~
 * var myEntity = Crafty.e("2D, Canvas, Color")
 *      .color("green")
 *      .attr({x: 13, y: 37, w: 42, h: 42});
 *~~~
 */
Crafty.c("Canvas", {

    init: function () {
        if (!Crafty.canvas.context) {
            Crafty.canvas.init();
        }

        //increment the amount of canvas objs
        Crafty.DrawManager.total2D++;
        //Allocate an object to hold this components current region
        this.currentRect = {};
        this._changed = true;
        Crafty.DrawManager.addCanvas(this);

        this.bind("Invalidate", function (e) {
            //flag if changed
            if (this._changed === false) {
                this._changed = true;
                Crafty.DrawManager.addCanvas(this);
            }

        });

        this.bind("Remove", function () {
            Crafty.DrawManager.total2D--;
            this._changed = true;
            Crafty.DrawManager.addCanvas(this);
        });
    },

    /**@
     * #.draw
     * @comp Canvas
     * @sign public this .draw([[Context ctx, ]Number x, Number y, Number w, Number h])
     * @param ctx - Canvas 2D context if drawing on another canvas is required
     * @param x - X offset for drawing a segment
     * @param y - Y offset for drawing a segment
     * @param w - Width of the segment to draw
     * @param h - Height of the segment to draw
     *
     * Method to draw the entity on the canvas element. Can pass rect values for redrawing a segment of the entity.
     */

    // Cache the various objects and arrays used in draw:
    drawVars: {
        type: "canvas",
        pos: {},
        ctx: null,
        coord: [0, 0, 0, 0],
        co: {
            x: 0,
            y: 0,
            w: 0,
            h: 0
        }

    },

    draw: function (ctx, x, y, w, h) {
        if (!this.ready) return;
        if (arguments.length === 4) {
            h = w;
            w = y;
            y = x;
            x = ctx;
            ctx = Crafty.canvas.context;
        }

        var pos = this.drawVars.pos;
        pos._x = (this._x + (x || 0));
        pos._y = (this._y + (y || 0));
        pos._w = (w || this._w);
        pos._h = (h || this._h);

        context = ctx || Crafty.canvas.context;
        coord = this.__coord || [0, 0, 0, 0];
        var co = this.drawVars.co;
        co.x = coord[0] + (x || 0);
        co.y = coord[1] + (y || 0);
        co.w = w || coord[2];
        co.h = h || coord[3];

        // If we are going to perform any entity-specific changes to the current context, save the current state
        if (this._flipX || (this._flipY || this._rotation)) {
            context.save();
        }

        // rotate the context about this entity's origin
        if (this._rotation !== 0) {
            context.translate(this._origin.x + this._x, this._origin.y + this._y);
            pos._x = -this._origin.x;
            pos._y = -this._origin.y;
            context.rotate((this._rotation % 360) * (Math.PI / 180));
        }

        // We realize a flipped entity by scaling the context in the opposite direction, then adjusting the position coordinates to match
        if (this._flipX || this._flipY) {
            context.scale((this._flipX ? -1 : 1), (this._flipY ? -1 : 1));
            if (this._flipX) {
                pos._x = -(pos._x + pos._w);
            }
            if (this._flipY) {
                pos._y = -(pos._y + pos._h);
            }
        }

        var globalpha;

        //draw with alpha
        if (this._alpha < 1.0) {
            globalpha = context.globalAlpha;
            context.globalAlpha = this._alpha;
        }

        this.drawVars.ctx = context;
        this.trigger("Draw", this.drawVars);

        // If necessary, restore context
        if (this._rotation !== 0 || (this._flipX || this._flipY)) {
            context.restore();
        }
        if (globalpha) {
            context.globalAlpha = globalpha;
        }
        return this;
    }
});

/**@
 * #Crafty.canvas
 * @category Graphics
 *
 * Collection of methods to draw on canvas.
 */
Crafty.extend({
    canvas: {
        /**@
         * #Crafty.canvas.context
         * @comp Crafty.canvas
         *
         * This will return the 2D context of the main canvas element.
         * The value returned from `Crafty.canvas._canvas.getContext('2d')`.
         */
        context: null,
        /**@
         * #Crafty.canvas._canvas
         * @comp Crafty.canvas
         *
         * Main Canvas element
         */

        /**@
         * #Crafty.canvas.init
         * @comp Crafty.canvas
         * @sign public void Crafty.canvas.init(void)
         * @trigger NoCanvas - triggered if `Crafty.support.canvas` is false
         *
         * Creates a `canvas` element inside `Crafty.stage.elem`. Must be called
         * before any entities with the Canvas component can be drawn.
         *
         * This method will automatically be called if no `Crafty.canvas.context` is
         * found.
         */
        init: function () {
            //check if canvas is supported
            if (!Crafty.support.canvas) {
                Crafty.trigger("NoCanvas");
                Crafty.stop();
                return;
            }

            //create an empty canvas element
            var c;
            c = document.createElement("canvas");
            c.width = Crafty.viewport.width;
            c.height = Crafty.viewport.height;
            c.style.position = 'absolute';
            c.style.left = "0px";
            c.style.top = "0px";

            Crafty.stage.elem.appendChild(c);
            Crafty.canvas.context = c.getContext('2d');
            Crafty.canvas._canvas = c;

            //Set any existing transformations
            var zoom = Crafty.viewport._scale;
            if (zoom != 1)
                Crafty.canvas.context.scale(zoom, zoom);

            // Set pixelart to current status, and listen for changes
            this._setPixelart(Crafty._pixelartEnabled);
            Crafty.uniqueBind("PixelartSet", this._setPixelart);

            //Bind rendering of canvas context (see drawing.js)
            Crafty.uniqueBind("RenderScene", Crafty.DrawManager.renderCanvas);

            Crafty.uniqueBind("ViewportResize", this._resize);
        },

        // Resize the canvas element to the current viewport
        _resize: function() {
            var c = Crafty.canvas._canvas;
            c.width = Crafty.viewport.width;
            c.height = Crafty.viewport.height;

        },

        _setPixelart: function(enabled){
            var context = Crafty.canvas.context;
            context.imageSmoothingEnabled = !enabled;
            context.mozImageSmoothingEnabled = !enabled;
            context.webkitImageSmoothingEnabled = !enabled;
            context.oImageSmoothingEnabled = !enabled;
            context.msImageSmoothingEnabled = !enabled;
        }

    }
});
<|endoftext|>


<commit_before>var ValueOwners = artifacts.require("./ValueOwners.sol");

contract('ValueOwners', function(accounts) {
  it("should set 10000000000000000 Wei in cost", function() {
    return ValueOwners.deployed().then(function(instance) {
      return instance.cost();
    }).then(function(cost) {
      assert.equal(cost.valueOf(),10000000000000000,'Constract cost isn\'t 10000000000000000 Wei');
    });
  });

  it("should return zero balance for the owner address", function() {
    var owner_address = accounts[0];
    return ValueOwners.deployed().then(function(instance) {
      return instance.getBalance.call(owner_address);
    }).then(function(balance) {
      assert.equal(balance.valueOf(), 0, 'Owner balance isn\'t 0');
    });
  });

  it("should return zero balance for the other address", function() {
    var other_address = accounts[1];
    return ValueOwners.deployed().then(function(instance) {
      return instance.getBalance.call(other_address);
    }).then(function(balance) {
      assert.equal(balance.valueOf(), 0, 'Other balance isn\'t 0');
    });
  });

  it("should return new cost after cost was changed by owner", function() {
    return ValueOwners.deployed().then(function(instance) {
      return instance.setCost.call(15000000000000000);
    }).then(function(newCost) {
      assert.equal(newCost, 15000000000000000, 'New cost doesn\' eqals new value 15000000000000000');
    });
  });

});
<commit_msg>Add test for payedAmount function<commit_after>var ValueOwners = artifacts.require("./ValueOwners.sol");

contract('ValueOwners', function(accounts) {
  it("should set 10000000000000000 Wei in cost", function() {
    return ValueOwners.deployed().then(function(instance) {
      return instance.cost();
    }).then(function(cost) {
      assert.equal(cost.valueOf(),10000000000000000,'Constract cost isn\'t 10000000000000000 Wei');
    });
  });

  it("should return zero balance for the owner address", function() {
    var owner_address = accounts[0];
    return ValueOwners.deployed().then(function(instance) {
      return instance.getBalance.call(owner_address);
    }).then(function(balance) {
      assert.equal(balance.valueOf(), 0, 'Owner balance isn\'t 0');
    });
  });

  it("should return zero balance for the other address", function() {
    var other_address = accounts[1];
    return ValueOwners.deployed().then(function(instance) {
      return instance.getBalance.call(other_address);
    }).then(function(balance) {
      assert.equal(balance.valueOf(), 0, 'Other balance isn\'t 0');
    });
  });

  it("should return new cost after cost was changed by owner", function() {
    return ValueOwners.deployed().then(function(instance) {
      return instance.setCost.call(15000000000000000);
    }).then(function(newCost) {
      assert.equal(newCost, 15000000000000000, 'New cost doesn\' equals new value 15000000000000000');
    });
  });

  it("should return zero from payedAmount", function() {
    return ValueOwners.deployed().then(function(instance) {
      return instance.payedAmount.call();
    }).then(function(amount) {
      assert.equal(amount, 0,'Amount isn\'t 0')
    });
  });
});
<|endoftext|>


<commit_before>/*
 * Filter that only returns cases.  Used by the change listener.
 */
function(doc, req)
{
    return (doc["doc_type"] == "CommCareCase");
}
<commit_msg>adding -deleted for couch filter<commit_after>/*
 * Filter that only returns cases.  Used by the change listener.
 */
function(doc, req)
{
    return (doc["doc_type"] == "CommCareCase" || doc["doc_type"]== "CommCareCase-Deleted");
}
<|endoftext|>


<commit_before>'use strict';

var assert      = require('assert');
var util        = require('util');
var _           = require('lodash');
var Promise     = require('bluebird');
var createError = require('create-error');
var http        = require('http');
var needle      = Promise.promisifyAll(require('needle'));
var pkg         = require('../package.json');

function ClearbitClient (config) {
  config = config || {};
  assert(this instanceof ClearbitClient, 'Client must be called with new');

  this.key = config.key || process.env.CLEARBIT_KEY;
  assert(!!this.key, 'An API key must be provided');

  this.Enrichment = require('./enrichment').Enrichment(this);
  this.Company = require('./enrichment/company').Company(this);
  this.Person = require('./enrichment/person').Person(this);
  this.Discovery = require('./discovery').Discovery(this);
  this.Watchlist = require('./watchlist').Watchlist(this);
  this.WatchlistCandidate = require('./watchlist').WatchlistCandidate(this);
  this.WatchlistEntity = require('./watchlist').WatchlistEntity(this);
  this.WatchlistIndividual = require('./watchlist').WatchlistIndividual(this);
}

var ENDPOINT = 'https://%s%s.clearbit.com/v%s';

ClearbitClient.prototype.endpoint = function (options) {
  options = _.defaults(options, {
    version: '1',
    stream: false
  });

  assert(options.api, 'An API must be specified');

  return util.format(
    ENDPOINT,
    options.api,
    options.stream ? '-stream' : '',
    options.version
  );
};

ClearbitClient.prototype.url = function (options) {
  _.defaults(options, {
    path: ''
  });
  return this.endpoint(options) + options.path;
};

ClearbitClient.prototype.request = function (options) {
  options = _.defaults(options, {
    method: 'get'
  });

  return needle.requestAsync(
    options.method,
    this.url(options),
    options.query,
    {
      headers: options.headers,
      timeout: options.stream ? 60000 : 10000,
      username: this.key,
      password: '',
      user_agent: 'ClearbitNode/v' + pkg.version
    }
  )
  .bind(this)
  .spread(function (response, body) {
    if (response.statusCode === 202 || response.statusCode >= 400) {
      var message = body.error ? body.error.message : http.STATUS_CODES[response.statusCode] || 'Unknown';
      throw _.extend(new this.ClearbitError(message), {
        type: body.error ? body.error.type : 'unknown',
        body: body,
        statusCode: response.statusCode
      });
    }
    else {
      return body;
    }
  });
};

ClearbitClient.ClearbitError = ClearbitClient.prototype.ClearbitError = createError('ClearbitError');

module.exports = ClearbitClient;
<commit_msg>Fix Discovery searches<commit_after>'use strict';

var assert      = require('assert');
var util        = require('util');
var _           = require('lodash');
var Promise     = require('bluebird');
var createError = require('create-error');
var http        = require('http');
var needle      = Promise.promisifyAll(require('needle'));
var pkg         = require('../package.json');

function ClearbitClient (config) {
  config = config || {};
  assert(this instanceof ClearbitClient, 'Client must be called with new');

  this.key = config.key || process.env.CLEARBIT_KEY;
  assert(!!this.key, 'An API key must be provided');

  this.Enrichment = require('./enrichment').Enrichment(this);
  this.Company = require('./enrichment/company').Company(this);
  this.Person = require('./enrichment/person').Person(this);
  this.Discovery = require('./discovery').Discovery(this);
  this.Watchlist = require('./watchlist').Watchlist(this);
  this.WatchlistCandidate = require('./watchlist').WatchlistCandidate(this);
  this.WatchlistEntity = require('./watchlist').WatchlistEntity(this);
  this.WatchlistIndividual = require('./watchlist').WatchlistIndividual(this);
}

var ENDPOINT = 'https://%s%s.clearbit.com/v%s';

ClearbitClient.prototype.endpoint = function (options) {
  options = _.defaults(options, {
    version: '1',
    stream: false
  });

  assert(options.api, 'An API must be specified');

  return util.format(
    ENDPOINT,
    options.api,
    options.stream ? '-stream' : '',
    options.version
  );
};

ClearbitClient.prototype.url = function (options) {
  _.defaults(options, {
    path: ''
  });
  return this.endpoint(options) + options.path;
};

ClearbitClient.prototype.request = function (options) {
  options = _.defaults(options, {
    method: 'get'
  });

  return needle.requestAsync(
    options.method,
    this.url(options),
    options.body || options.query,
    {
      json: options.json,
      headers: options.headers,
      timeout: options.stream ? 60000 : 10000,
      username: this.key,
      password: '',
      user_agent: 'ClearbitNode/v' + pkg.version
    }
  )
  .bind(this)
  .spread(function (response, body) {
    if (response.statusCode === 202 || response.statusCode >= 400) {
      var message = body.error ? body.error.message : http.STATUS_CODES[response.statusCode] || 'Unknown';
      throw _.extend(new this.ClearbitError(message), {
        type: body.error ? body.error.type : 'unknown',
        body: body,
        statusCode: response.statusCode
      });
    }
    else {
      return body;
    }
  });
};

ClearbitClient.ClearbitError = ClearbitClient.prototype.ClearbitError = createError('ClearbitError');

module.exports = ClearbitClient;
<|endoftext|>


<commit_before>suite('basic', function() {

  this.timeout(2000);

  var container = document.getElementById('container');

  teardown(function() {
    container.innerHTML = '';
  });

  test('default date', function(done) {
    var fixture = document.createElement('basic-calendar-day');
    container.appendChild(fixture);
    var now = new Date();
    assert(fixture.date instanceof Date);
    assert(now >= fixture.date);
    done();
  });

  test('set date', function(done) {
    var fixture = document.createElement('basic-calendar-day');
    container.appendChild(fixture);
    fixture.date = new Date('14 March 2015');
    flush(function() {
      assert.deepEqual(fixture.date, new Date('March 14, 2015'));
      assert.equal(fixture.$.day.textContent, fixture.date.getDate());
      done();
    });
  });

  test('classList does not contain today', function(done) {
    var fixture = document.createElement('basic-calendar-day');
    container.appendChild(fixture);
    fixture.date = new Date('14 March 2015');
    flush(function() {
      assert.equal(fixture.classList.contains('today'), false);
      done();
    });
  });

  test('classList contains past', function(done) {
    var fixture = document.createElement('basic-calendar-day');
    container.appendChild(fixture);
    fixture.date = new Date('14 March 2015');
    flush(function() {
      assert.equal(fixture.classList.contains('past'), true);
      done();
    });
  });

  test('classList does not contain future', function(done) {
    var fixture = document.createElement('basic-calendar-day');
    container.appendChild(fixture);
    fixture.date = new Date('14 March 2015');
    flush(function() {
      assert.equal(fixture.classList.contains('future'), false);
      done();
    });
  });

  test('classList does not contain firstDayOfMonth', function(done) {
    var fixture = document.createElement('basic-calendar-day');
    container.appendChild(fixture);
    fixture.date = new Date('14 March 2015');
    flush(function() {
      assert.equal(fixture.classList.contains('firstDayOfMonth'), false);
      done();
    });
  });

  test('classList does not contain lastDayOfMonth', function(done) {
    var fixture = document.createElement('basic-calendar-day');
    container.appendChild(fixture);
    fixture.date = new Date('14 March 2015');
    flush(function () {
      assert.equal(fixture.classList.contains('lastDayOfMonth'), false);
      done();
    });
  });

  test('classList does not contain firstWeek', function(done) {
    var fixture = document.createElement('basic-calendar-day');
    container.appendChild(fixture);
    fixture.date = new Date('14 March 2015');
    flush(function() {
      assert.equal(fixture.classList.contains('firstWeek'), false);
      done();
    });
  });

  test('classList does not contain sunday', function(done) {
    var fixture = document.createElement('basic-calendar-day');
    container.appendChild(fixture);
    fixture.date = new Date('14 March 2015');
    flush(function() {
      assert.equal(fixture.classList.contains('sunday'), false);
      done();
    });
  });

  test('classList contains saturday', function(done) {
    var fixture = document.createElement('basic-calendar-day');
    container.appendChild(fixture);
    fixture.date = new Date('14 March 2015');
    flush(function() {
      assert.equal(fixture.classList.contains('saturday'), true);
      done();
    });
  });

  test('classList contains weekend', function(done) {
    var fixture = document.createElement('basic-calendar-day');
    container.appendChild(fixture);
    fixture.date = new Date('14 March 2015');
    flush(function() {
      assert.equal(fixture.classList.contains('weekend'), true);
      done();
    });
  });

  test('classList does not contain weekday', function(done) {
    var fixture = document.createElement('basic-calendar-day');
    container.appendChild(fixture);
    fixture.date = new Date('14 March 2015');
    flush(function() {
      assert.equal(fixture.classList.contains('weekday'), false);
      done();
    });
  });

  test('classList does not contain alternateMonth', function(done) {
    var fixture = document.createElement('basic-calendar-day');
    container.appendChild(fixture);
    fixture.date = new Date('14 March 2015');
    flush(function() {
      assert.equal(fixture.classList.contains('alternateMonth'), false);
      done();
    });
  });

});
<commit_msg>Fix unit test<commit_after>suite('basic', function() {

  this.timeout(2000);

  var container = document.getElementById('container');

  teardown(function() {
    container.innerHTML = '';
  });

  test('default date', function(done) {
    var fixture = document.createElement('basic-calendar-day');
    container.appendChild(fixture);
    var now = new Date();
    assert(fixture.date instanceof Date);
    assert(now >= fixture.date);
    done();
  });

  test('set date', function(done) {
    var fixture = document.createElement('basic-calendar-day');
    container.appendChild(fixture);
    fixture.date = new Date('14 March 2015');
    flush(function() {
      assert.deepEqual(fixture.date, new Date('March 14, 2015'));
      assert.equal(fixture.$.day.textContent, fixture.date.getDate());
      done();
    });
  });

  test('classList does not contain today', function(done) {
    var fixture = document.createElement('basic-calendar-day');
    container.appendChild(fixture);
    fixture.date = new Date('14 March 2015');
    flush(function() {
      assert.equal(fixture.classList.contains('today'), false);
      done();
    });
  });

  test('classList contains past', function(done) {
    var fixture = document.createElement('basic-calendar-day');
    container.appendChild(fixture);
    fixture.date = new Date('14 March 2015');
    flush(function() {
      assert.equal(fixture.classList.contains('past'), true);
      done();
    });
  });

  test('classList does not contain future', function(done) {
    var fixture = document.createElement('basic-calendar-day');
    container.appendChild(fixture);
    fixture.date = new Date('14 March 2015');
    flush(function() {
      assert.equal(fixture.classList.contains('future'), false);
      done();
    });
  });

  test('classList does not contain firstDayOfMonth', function(done) {
    var fixture = document.createElement('basic-calendar-day');
    container.appendChild(fixture);
    fixture.date = new Date('14 March 2015');
    flush(function() {
      assert.equal(fixture.classList.contains('firstDayOfMonth'), false);
      done();
    });
  });

  test('classList does not contain lastDayOfMonth', function(done) {
    var fixture = document.createElement('basic-calendar-day');
    container.appendChild(fixture);
    fixture.date = new Date('14 March 2015');
    flush(function () {
      assert.equal(fixture.classList.contains('lastDayOfMonth'), false);
      done();
    });
  });

  test('classList does not contain firstWeek', function(done) {
    var fixture = document.createElement('basic-calendar-day');
    container.appendChild(fixture);
    fixture.date = new Date('14 March 2015');
    flush(function() {
      assert.equal(fixture.classList.contains('firstWeek'), false);
      done();
    });
  });

  test('classList does not contain sunday', function(done) {
    var fixture = document.createElement('basic-calendar-day');
    container.appendChild(fixture);
    fixture.date = new Date('14 March 2015');
    flush(function() {
      assert.equal(fixture.classList.contains('sunday'), false);
      done();
    });
  });

  test('classList contains saturday', function(done) {
    var fixture = document.createElement('basic-calendar-day');
    container.appendChild(fixture);
    fixture.date = new Date('14 March 2015');
    flush(function() {
      assert.equal(fixture.classList.contains('saturday'), true);
      done();
    });
  });

  test('classList contains weekend', function(done) {
    var fixture = document.createElement('basic-calendar-day');
    container.appendChild(fixture);
    fixture.date = new Date('14 March 2015');
    flush(function() {
      assert.equal(fixture.classList.contains('weekend'), true);
      done();
    });
  });

  test('classList does not contain weekday', function(done) {
    var fixture = document.createElement('basic-calendar-day');
    container.appendChild(fixture);
    fixture.date = new Date('14 March 2015');
    flush(function() {
      assert.equal(fixture.classList.contains('weekday'), false);
      done();
    });
  });

  test('classList does not contain alternateMonth', function(done) {
    var fixture = document.createElement('basic-calendar-day');
    container.appendChild(fixture);
    fixture.date = new Date('14 March 2015');
    flush(function() {
      var today = BasicCalendarDay.today();
      var altMonth = Math.abs(fixture.date.getMonth() - today.getMonth()) % 2 === 1;
      assert.equal(fixture.classList.contains('alternateMonth'), altMonth);
      done();
    });
  });

});
<|endoftext|>


<commit_before>const chai = require('chai');
const React = require('react');
chai.should();

const Button = require('../src/button');
describe('Button', () => {
  it('should pass tests', () => {
    var button = <Button />;
    button.should.exist;
  });
});
<commit_msg>Add actual test for button component<commit_after>const React = require('react');
import {createRenderer} from 'react-addons-test-utils';
import expect, { createSpy, spyOn, isSpy } from 'expect';

const Button = require('../src/button');

describe('Button', () => {
  it('can render an empty button', () => {
    const renderer = createRenderer();
    renderer.render(<Button />);
    const component = renderer.getRenderOutput();

    expect(component.type).toEqual('button');
  });
});
<|endoftext|>


<commit_before>const assert = require('assert')
const Cache = require('../../lib/cache')

describe('Cache', function () {
  describe('query()', function () {
    let cache = new Cache()
    cache.add(100, [{id: '1', t: 70}, {id: '2', t: 60}])
    it('should get data when query ts is larger than data’s ts.', function () {
      assert.deepEqual([{id: '1', t: 70}, {id: '2', t: 60}], cache.query(100, 2))
    })
    it('should get only one data when the limit is 1.', function () {
      assert.deepEqual([{id: '1', t: 70}], cache.query(100, 1))
    })
    it('should get null when the query ts is smaller than data’s ts.', function () {
      assert.deepEqual(null, cache.query(50, 2))
    })
    it('should get null when the limit is larger than data’s length.', function () {
      assert.deepEqual(null, cache.query(100, 3))
    })
  })

  describe('add()', function () {
    let cache = new Cache()
    cache.add(1000, [{id: '1', t: 990}, {id: '2', t: 980}, {id: '3', t: 970}, {id: '4', t: 960}, {id: '5', t: 950}])
    cache.add(950, [{id: '6', t: 940}, {id: '7', t: 930}, {id: '8', t: 925}, {id: '9', t: 920}, {id: '10', t: 915}])
    it('should concat all data when it runs more than twice.', function () {
      assert.deepEqual([{id: '1', t: 990}, {id: '2', t: 980}, {id: '3', t: 970}, {id: '4', t: 960}, {id: '5', t: 950}, {id: '6', t: 940}, {id: '7', t: 930}, {id: '8', t: 925}, {id: '9', t: 920}, {id: '10', t: 915}], cache.query(1000, 10))
    })
  })
})
<commit_msg>Update 'Cache' test<commit_after>const assert = require('assert')
const Cache = require('../../lib/cache')

describe('Cache', function () {
  describe('query()', function () {
    let cache = new Cache()
    cache.add(100, [{id: '1', t: 70}, {id: '2', t: 60}])
    it('should get data when query ts is larger than data’s ts.', function () {
      assert.deepEqual([{id: '1', t: 70}, {id: '2', t: 60}], cache.query(100, 2))
    })
    it('should get only one data when the limit is 1.', function () {
      assert.deepEqual([{id: '1', t: 70}], cache.query(100, 1))
    })
    it('should get null when the query ts is smaller than data’s ts.', function () {
      assert.deepEqual(null, cache.query(50, 2))
    })
    it('should get null when the limit is larger than data’s length.', function () {
      assert.deepEqual(null, cache.query(100, 3))
    })
  })

  describe('add()', function () {
    let cache = new Cache()
    cache.add(1000, [{id: '1', t: 990}, {id: '2', t: 980}, {id: '8', t: 925}, {id: '4', t: 960}, {id: '5', t: 950}])
    cache.add(950, [{id: '6', t: 940}, {id: '7', t: 930}, {id: '3', t: 970}, {id: '9', t: 920}, {id: '10', t: 915}])
    it('should concat all data and sort by ts when it runs more than twice.', function () {
      assert.deepEqual([{id: '1', t: 990}, {id: '2', t: 980}, {id: '3', t: 970}, {id: '4', t: 960}, {id: '5', t: 950}, {id: '6', t: 940}, {id: '7', t: 930}, {id: '8', t: 925}, {id: '9', t: 920}, {id: '10', t: 915}], cache.query(1000, 10))
    })
  })
})
<|endoftext|>


<commit_before>module.exports = {
  extends: [
    'simplabs/configs/ember-qunit',
    'simplabs/plugins/qunit',
  ],
};
<commit_msg>ESLint: Update `parserOptions.ecmaVersion` to allow async/await<commit_after>module.exports = {
  parserOptions: {
    sourceType: 'module',
    ecmaVersion: 2017
  },
  extends: [
    'simplabs/configs/ember-qunit',
    'simplabs/plugins/qunit',
  ],
};
<|endoftext|>


<commit_before>/**
 * THIS IS THE ENTRY POINT FOR THE CLIENT, JUST LIKE server.js IS THE ENTRY POINT FOR THE SERVER.
 */
import 'babel/polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import BrowserHistory from 'react-router/lib/BrowserHistory';
import Location from 'react-router/lib/Location';
import queryString from 'query-string';
import createStore from './redux/create';
import ApiClient from './ApiClient';
import universalRouter from './universalRouter';
import Raven from 'raven-js'

Raven
    .config('https://27ca3f291894466997ae1a5c78b70673@app.getsentry.com/86009')
    .install()

const history = new BrowserHistory();
const client = new ApiClient();

const dest = document.getElementById('content');
const store = createStore(client, window.__data);
const search = document.location.search;
const query = search && queryString.parse(search);
const location = new Location(document.location.pathname, query);
const host = document.location.host

universalRouter(location, history, store, host)
  .then(({component}) => {
    if (__DEVTOOLS__) {
      const { DevTools, DebugPanel, LogMonitor } = require('redux-devtools/lib/react');
      console.info('You will see a "Warning: React attempted to reuse markup in a container but the checksum was' +
        ' invalid." message. That\'s because the redux-devtools are enabled.');
      ReactDOM.render(

        {component}
        <DebugPanel top right bottom key="debugPanel">
          <DevTools store={store} monitor={LogMonitor}/>
        </DebugPanel>

, dest);
    } else {
      ReactDOM.render(component, dest);
    }
  }, (error) => {
    console.error(error);
  });

if (process.env.NODE_ENV !== 'production') {
  window.React = React; // enable debugger
  const reactRoot = window.document.getElementById('content');

  if (!reactRoot || !reactRoot.firstChild || !reactRoot.firstChild.attributes || !reactRoot.firstChild.attributes['data-react-checksum']) {
    console.error('Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.');
  }
}
<commit_msg>Update sentry config dsn<commit_after>/**
 * THIS IS THE ENTRY POINT FOR THE CLIENT, JUST LIKE server.js IS THE ENTRY POINT FOR THE SERVER.
 */
import 'babel/polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import BrowserHistory from 'react-router/lib/BrowserHistory';
import Location from 'react-router/lib/Location';
import queryString from 'query-string';
import createStore from './redux/create';
import ApiClient from './ApiClient';
import universalRouter from './universalRouter';
import Raven from 'raven-js'

Raven
    .config('https://551d08d954074dddb605f9043706ecd8@app.getsentry.com/86008')
    .install()

const history = new BrowserHistory();
const client = new ApiClient();

const dest = document.getElementById('content');
const store = createStore(client, window.__data);
const search = document.location.search;
const query = search && queryString.parse(search);
const location = new Location(document.location.pathname, query);
const host = document.location.host

universalRouter(location, history, store, host)
  .then(({component}) => {
    if (__DEVTOOLS__) {
      const { DevTools, DebugPanel, LogMonitor } = require('redux-devtools/lib/react');
      console.info('You will see a "Warning: React attempted to reuse markup in a container but the checksum was' +
        ' invalid." message. That\'s because the redux-devtools are enabled.');
      ReactDOM.render(

        {component}
        <DebugPanel top right bottom key="debugPanel">
          <DevTools store={store} monitor={LogMonitor}/>
        </DebugPanel>

, dest);
    } else {
      ReactDOM.render(component, dest);
    }
  }, (error) => {
    console.error(error);
  });

if (process.env.NODE_ENV !== 'production') {
  window.React = React; // enable debugger
  const reactRoot = window.document.getElementById('content');

  if (!reactRoot || !reactRoot.firstChild || !reactRoot.firstChild.attributes || !reactRoot.firstChild.attributes['data-react-checksum']) {
    console.error('Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.');
  }
}
<|endoftext|>