<commit_before>(function(angular) {

    var module = angular.module('sensors');

    module.directive('livechart', [function() {
        return {
            restrict: 'E',
            scope: {
                width: '@',
                height: '@',

                data: '='
            },
            link: function(scope, element, attrs) {
                var svg = d3.select(element[0]).append('svg').style('width', '100%');
                var wheelShape = d3.svg.line()
                    .x(function(d) { return d.x; })
                    .y(function(d) { return d.y; })
                    .interpolate('linear')([
                                            {x: -10, y: -25},
                                            {x: 10, y: -25},
                                            {x: 10, y: 25},
                                            {x: -10, y: 25},
                                            ]) + 'Z';
                var sensorBeam = d3.svg.line()
                    .x(function(d) { return d.x; })
                    .y(function(d) { return d.y; })
                    .interpolate('linear')([
                                            {x: 0, y: 0},
                                            {x: -1, y: -10},
                                            {x: 1, y: -10}
                                            ]) + 'Z';

                var robotShape = d3.svg.line()
                    .x(function(d) {return d.x;})
                    .y(function(d) {return d.y;})
                    .interpolate('linear')([
                                            {x: -45, y: -60},
                                            {x: -15, y: -80},
                                            {x:  15, y: -80},
                                            {x:  45, y: -60},
                                            {x:  45, y: 40},
                                            {x:  35, y: 60},
                                            {x: -35, y: 60},
                                            {x:  -45, y: 40}
                                            ]) + 'Z';
                var beamColor = '#ccffcc';
                var group = svg.append('g')
                    .attr("transform", function(d) { return "translate(200,200)"; });

                group.append('path').attr('d', wheelShape).attr('stroke', 'none').attr('fill', 'black')
                    .attr('transform', 'translate(-40,-25)');
                group.append('path').attr('d', wheelShape).attr('stroke', 'none').attr('fill', 'black')
                    .attr('transform', 'translate(40,-25)');
                group.append('path').attr('d', robotShape).attr('stroke', 'none').attr('fill', 'red');
                group.append('g').attr('transform', 'translate(-45,20)')
                    .append('g').attr('transform', 'rotate(-90)')
                    .append('path').attr('class', 'sensor')
                    .attr('d', sensorBeam).attr('stroke', 'none').attr('fill', beamColor)
                    .attr('transform', 'scale(10,10)');
                group.append('g').attr('transform', 'translate(-35,-65)')
                    .append('g').attr('transform', 'rotate(-45)')
                    .append('path').attr('class', 'sensor')
                    .attr('d', sensorBeam).attr('stroke', 'none').attr('fill', beamColor)
                    .attr('transform', 'scale(10,10)');
                group.append('g').attr('transform', 'translate(0,-75)')
                    .append('g').attr('transform', 'rotate(-0)')
                    .append('path').attr('class', 'sensor')
                    .attr('d', sensorBeam).attr('stroke', 'none').attr('fill', beamColor)
                    .attr('transform', 'scale(10,10)');
                group.append('g').attr('transform', 'translate(35,-65)')
                    .append('g').attr('transform', 'rotate(45)')
                    .append('path').attr('class', 'sensor')
                    .attr('d', sensorBeam).attr('stroke', 'none').attr('fill', beamColor)
                    .attr('transform', 'scale(10,10)');
                group.append('g').attr('transform', 'translate(45,20)')
                    .append('g').attr('transform', 'rotate(90)')
                    .append('path').attr('class', 'sensor')
                    .attr('d', sensorBeam).attr('stroke', 'none').attr('fill', beamColor)
                    .attr('transform', 'scale(10,10)');

                var width = attrs.width || 300;
                var height = attrs.height || 300;

                var xScale = d3.scale.linear().domain([0, 150]).range([0, width]);
                var yScale = d3.scale.linear().domain([0, 4096]).range([0, height]);

                function update(selection) {
                    selection.attr('transform', function(d) { return 'scale(' + ( 5000/(d+1) ) + ')';});
                }

                scope.$watch('data', function() {
                    var data = scope.data || [];
                    var paths = svg.selectAll('.sensor').data(data);

                    paths.call(update);
                });
            }
        };
    }]);
})(angular);<commit_msg>fixed position of head sensor<commit_after>(function(angular) {

    var module = angular.module('sensors');

    module.directive('livechart', [function() {
        return {
            restrict: 'E',
            scope: {
                width: '@',
                height: '@',

                data: '='
            },
            link: function(scope, element, attrs) {
                var svg = d3.select(element[0]).append('svg').style('width', '100%');
                var wheelShape = d3.svg.line()
                    .x(function(d) { return d.x; })
                    .y(function(d) { return d.y; })
                    .interpolate('linear')([
                                            {x: -10, y: -25},
                                            {x: 10, y: -25},
                                            {x: 10, y: 25},
                                            {x: -10, y: 25},
                                            ]) + 'Z';
                var sensorBeam = d3.svg.line()
                    .x(function(d) { return d.x; })
                    .y(function(d) { return d.y; })
                    .interpolate('linear')([
                                            {x: 0, y: 0},
                                            {x: -1, y: -10},
                                            {x: 1, y: -10}
                                            ]) + 'Z';

                var robotShape = d3.svg.line()
                    .x(function(d) {return d.x;})
                    .y(function(d) {return d.y;})
                    .interpolate('linear')([
                                            {x: -45, y: -60},
                                            {x: -15, y: -80},
                                            {x:  15, y: -80},
                                            {x:  45, y: -60},
                                            {x:  45, y: 40},
                                            {x:  35, y: 60},
                                            {x: -35, y: 60},
                                            {x:  -45, y: 40}
                                            ]) + 'Z';
                var beamColor = '#ccffcc';
                var group = svg.append('g')
                    .attr("transform", function(d) { return "translate(200,200)"; });

                group.append('path').attr('d', wheelShape).attr('stroke', 'none').attr('fill', 'black')
                    .attr('transform', 'translate(-40,-25)');
                group.append('path').attr('d', wheelShape).attr('stroke', 'none').attr('fill', 'black')
                    .attr('transform', 'translate(40,-25)');
                group.append('path').attr('d', robotShape).attr('stroke', 'none').attr('fill', 'red');
                group.append('g').attr('transform', 'translate(-45,20)')
                    .append('g').attr('transform', 'rotate(-90)')
                    .append('path').attr('class', 'sensor')
                    .attr('d', sensorBeam).attr('stroke', 'none').attr('fill', beamColor)
                    .attr('transform', 'scale(10,10)');
                group.append('g').attr('transform', 'translate(-35,-65)')
                    .append('g').attr('transform', 'rotate(-45)')
                    .append('path').attr('class', 'sensor')
                    .attr('d', sensorBeam).attr('stroke', 'none').attr('fill', beamColor)
                    .attr('transform', 'scale(10,10)');
                group.append('g').attr('transform', 'translate(0,-80)')
                    .append('g').attr('transform', 'rotate(-0)')
                    .append('path').attr('class', 'sensor')
                    .attr('d', sensorBeam).attr('stroke', 'none').attr('fill', beamColor)
                    .attr('transform', 'scale(10,10)');
                group.append('g').attr('transform', 'translate(35,-65)')
                    .append('g').attr('transform', 'rotate(45)')
                    .append('path').attr('class', 'sensor')
                    .attr('d', sensorBeam).attr('stroke', 'none').attr('fill', beamColor)
                    .attr('transform', 'scale(10,10)');
                group.append('g').attr('transform', 'translate(45,20)')
                    .append('g').attr('transform', 'rotate(90)')
                    .append('path').attr('class', 'sensor')
                    .attr('d', sensorBeam).attr('stroke', 'none').attr('fill', beamColor)
                    .attr('transform', 'scale(10,10)');

                var width = attrs.width || 300;
                var height = attrs.height || 300;

                var xScale = d3.scale.linear().domain([0, 150]).range([0, width]);
                var yScale = d3.scale.linear().domain([0, 4096]).range([0, height]);

                function update(selection) {
                    selection.attr('transform', function(d) { return 'scale(' + ( 5000/(d+1) ) + ')';});
                }

                scope.$watch('data', function() {
                    var data = scope.data || [];
                    var paths = svg.selectAll('.sensor').data(data);

                    paths.call(update);
                });
            }
        };
    }]);
})(angular);<|endoftext|>


<commit_before>$(function() {
    // the widget definition, where "custom" is the namespace,
    // "colorize" the widget name
    $.widget("sjl.jsnake", {
	// default options
	options: {
	    update_interval: 500
	},

	// These double as character codes for the keypresses.
	LEFT: 37,
	UP: 38,
	RIGHT: 39,
	DOWN: 40,

	_create: function () {
	    var ctx = this.element[0].getContext("2d");
	    this._board_width = 50;
	    this._board_height = 50;

	    this._x = Math.round(this._board_width/2);
	    this._y = Math.round(this._board_height/2);

	    this._valid_directions = [this.LEFT, this.RIGHT,
				     this.DOWN, this.UP];

	    this._direction = this.RIGHT;

	    if (ctx) {
		this.element.css("border", "1px solid black");
		setTimeout($.proxy(this.update, this),
			   this.options.update_interval);
		this._square_side = this.element.width()/this._board_width;
		this._ctx = ctx;
		$(document).on('keydown',
				$.proxy(function (e) {
				    if (this._valid_directions.indexOf(
					e.which) != -1)
					this._change_direction(e.which);
				} ,
					this));
	    }
	},

	_change_direction: function (new_direction) {
	    this._direction = new_direction;
	},

	_clear_square: function (x, y) {
	    this._ctx.clearRect(x * this._square_side, y * this._square_side,
				this._square_side, this._square_side);
	},

	_draw_square: function (x, y) {
	    this._ctx.fillStyle = "rgb(200, 0, 0)";
	    this._ctx.fillRect(x * this._square_side, y * this._square_side,
			       this._square_side, this._square_side);
	},

	_snake_still_legal: function () {
	    if (this._x < 0)
		return false;
	    if (this._x > this._board_width)
		return false;
	    if (this._y < 0)
		return false;
	    if (this._y > this._board_height)
		return false;
	    return true;
	},

	_move_snake: function () {
	    this._clear_square(this._x, this._y);

	    switch (this._direction) {
		case this.LEFT:
		this._x--;
		break;
		case this.RIGHT:
		this._x++;
		break;
		case this.UP:
		this._y--;
		break;
		case this.DOWN:
		this._y++;
		break;
	    }
	    if (this._snake_still_legal()) {
		this._draw_square(this._x, this._y);
		return false;
	    } else {
		return true;
	    }
	},

	update: function () {
	    var at_end = this._move_snake();
	    if (!at_end) {
		setTimeout($.proxy(this.update, this),
			   this.options.update_interval);
	    } else {
		alert("dead meat.");
	    }
	}
    });
});
<commit_msg>Removed obsolete comments.<commit_after>$(function() {
    $.widget("sjl.jsnake", {
	options: {
	    update_interval: 500
	},

	// These double as character codes for the keypresses.
	LEFT: 37,
	UP: 38,
	RIGHT: 39,
	DOWN: 40,

	_create: function () {
	    var ctx = this.element[0].getContext("2d");
	    this._board_width = 50;
	    this._board_height = 50;

	    this._x = Math.round(this._board_width/2);
	    this._y = Math.round(this._board_height/2);

	    this._valid_directions = [this.LEFT, this.RIGHT,
				     this.DOWN, this.UP];

	    this._direction = this.RIGHT;

	    if (ctx) {
		this.element.css("border", "1px solid black");
		setTimeout($.proxy(this.update, this),
			   this.options.update_interval);
		this._square_side = this.element.width()/this._board_width;
		this._ctx = ctx;
		$(document).on('keydown',
				$.proxy(function (e) {
				    if (this._valid_directions.indexOf(
					e.which) != -1)
					this._change_direction(e.which);
				} ,
					this));
	    }
	},

	_change_direction: function (new_direction) {
	    this._direction = new_direction;
	},

	_clear_square: function (x, y) {
	    this._ctx.clearRect(x * this._square_side, y * this._square_side,
				this._square_side, this._square_side);
	},

	_draw_square: function (x, y) {
	    this._ctx.fillStyle = "rgb(200, 0, 0)";
	    this._ctx.fillRect(x * this._square_side, y * this._square_side,
			       this._square_side, this._square_side);
	},

	_snake_still_legal: function () {
	    if (this._x < 0)
		return false;
	    if (this._x > this._board_width)
		return false;
	    if (this._y < 0)
		return false;
	    if (this._y > this._board_height)
		return false;
	    return true;
	},

	_move_snake: function () {
	    this._clear_square(this._x, this._y);

	    switch (this._direction) {
		case this.LEFT:
		this._x--;
		break;
		case this.RIGHT:
		this._x++;
		break;
		case this.UP:
		this._y--;
		break;
		case this.DOWN:
		this._y++;
		break;
	    }
	    if (this._snake_still_legal()) {
		this._draw_square(this._x, this._y);
		return false;
	    } else {
		return true;
	    }
	},

	update: function () {
	    var at_end = this._move_snake();
	    if (!at_end) {
		setTimeout($.proxy(this.update, this),
			   this.options.update_interval);
	    } else {
		alert("dead meat.");
	    }
	}
    });
});
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Thu Nov 24 2016 00:04:01 GMT+0100 (WAT)
module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      './src/scripts/inverted-index.js',
      './jasmine/spec/app-test.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      // source files, that you wanna generate coverage for
      // do not include tests or libraries
      // (these files will be instrumented by Istanbul)
      'src/inverted-index.js': ['coverage']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', 'coverage',],

    coverageReporter: {
      type: 'lcov', // lcov or lcovonly are required for generating lcov.info files
      dir: 'coverage/'
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity,

    customLaunchers: {
      Chrome_travis_ci: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    }
  })
}<commit_msg>feature(search):Applyfeedback from peer review<commit_after>// Karma configuration
// Generated on Thu Nov 24 2016 00:04:01 GMT+0100 (WAT)
module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: './src',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      './scripts/inverted-index.js',
      '../jasmine/spec/app-test.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      // source files, that you wanna generate coverage for
      // do not include tests or libraries
      // (these files will be instrumented by Istanbul)
      'src/inverted-index.js': ['coverage']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', 'coverage',],

    coverageReporter: {
      type: 'lcov', // lcov or lcovonly are required for generating lcov.info files
      dir: 'coverage/'
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity,

    customLaunchers: {
      Chrome_travis_ci: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    }
  })
}<|endoftext|>


<commit_before>var pull = require('pull-stream')

var Handshake = require('pull-handshake')
var State = require('./state')

var challenge_length = 64
var client_auth_length = 16+32+64
var server_auth_length = 16+64
var mac_length = 16

//client is Alice
//create the client stream with the public key you expect to connect to.
exports.client =
exports.createClientStream = function (alice, app_key, timeout) {

  return function (bob_pub, cb) {
    var state = new State(app_key, alice, bob_pub)

    console.log(timeout)
    var stream = Handshake({timeout: timeout}, cb)
    var shake = stream.handshake
    delete stream.handshake

    function abort(err, reason) {
      if(err && err !== true) shake.abort(err, cb)
      else                    shake.abort(new Error(reason), cb)
    }

    shake.write(state.createChallenge())

    shake.read(challenge_length, function (err, msg) {
      if(err) return abort(err, 'challenge not accepted')
      //create the challenge first, because we need to generate a local key
      if(!state.verifyChallenge(msg))
        return abort(null, 'wrong protocol (version?)')

      shake.write(state.createClientAuth())

      shake.read(server_auth_length, function (err, boxed_sig) {
        if(err) return abort(err, 'hello not accepted')

        if(!state.verifyServerAccept(boxed_sig))
          return abort(null, 'server not authenticated')

        cb(null, shake.rest(), state.cleanSecrets())
      })
    })

    return stream
  }
}

//server is Bob.
exports.server =
exports.createServerStream = function (bob, authorize, app_key, timeout) {

  return function (cb) {
    var state = new State(app_key, bob)
    var stream = Handshake({timeout: timeout}, cb)

    var shake = stream.handshake
    delete stream.handshake

    function abort (err, reason) {
      if(err && err !== true) shake.abort(err, cb)
      else                    shake.abort(new Error(reason), cb)
    }

    shake.read(challenge_length, function (err, challenge) {
      if(err) return abort(err, 'expected challenge')
      if(!state.verifyChallenge(challenge))
        return shake.abort(new Error('wrong protocol/version'))

      shake.write(state.createChallenge())
      shake.read(client_auth_length, function (err, hello) {
        if(err) return abort(err, 'expected hello')
        if(!state.verifyClientAuth(hello)) {
          //we know who the client was, but chose not to answer:
          if(state.remote.public)
            return abort(null, 'unauthenticated client:' + state.remote.public.toString('hex'), cb)
          //client dialed wrong number... (we don't know who they where)
          else
            return abort(null, 'wrong number')
        }
        //check if the user wants to speak to alice.
        authorize(state.remote.public, function (err, auth) {
          if(auth == null && !err) err = new Error('client unauthorized')
          if(!auth) return abort(err, 'client authentication rejected')
          state.auth = auth
          shake.write(state.createServerAccept())
          cb(null, shake.rest(), state.cleanSecrets())
        })
      })
    })
    return stream
  }
}

<commit_msg>remove logging<commit_after>var pull = require('pull-stream')

var Handshake = require('pull-handshake')
var State = require('./state')

var challenge_length = 64
var client_auth_length = 16+32+64
var server_auth_length = 16+64
var mac_length = 16

//client is Alice
//create the client stream with the public key you expect to connect to.
exports.client =
exports.createClientStream = function (alice, app_key, timeout) {

  return function (bob_pub, cb) {
    var state = new State(app_key, alice, bob_pub)

    var stream = Handshake({timeout: timeout}, cb)
    var shake = stream.handshake
    delete stream.handshake

    function abort(err, reason) {
      if(err && err !== true) shake.abort(err, cb)
      else                    shake.abort(new Error(reason), cb)
    }

    shake.write(state.createChallenge())

    shake.read(challenge_length, function (err, msg) {
      if(err) return abort(err, 'challenge not accepted')
      //create the challenge first, because we need to generate a local key
      if(!state.verifyChallenge(msg))
        return abort(null, 'wrong protocol (version?)')

      shake.write(state.createClientAuth())

      shake.read(server_auth_length, function (err, boxed_sig) {
        if(err) return abort(err, 'hello not accepted')

        if(!state.verifyServerAccept(boxed_sig))
          return abort(null, 'server not authenticated')

        cb(null, shake.rest(), state.cleanSecrets())
      })
    })

    return stream
  }
}

//server is Bob.
exports.server =
exports.createServerStream = function (bob, authorize, app_key, timeout) {

  return function (cb) {
    var state = new State(app_key, bob)
    var stream = Handshake({timeout: timeout}, cb)

    var shake = stream.handshake
    delete stream.handshake

    function abort (err, reason) {
      if(err && err !== true) shake.abort(err, cb)
      else                    shake.abort(new Error(reason), cb)
    }

    shake.read(challenge_length, function (err, challenge) {
      if(err) return abort(err, 'expected challenge')
      if(!state.verifyChallenge(challenge))
        return shake.abort(new Error('wrong protocol/version'))

      shake.write(state.createChallenge())
      shake.read(client_auth_length, function (err, hello) {
        if(err) return abort(err, 'expected hello')
        if(!state.verifyClientAuth(hello)) {
          //we know who the client was, but chose not to answer:
          if(state.remote.public)
            return abort(null, 'unauthenticated client:' + state.remote.public.toString('hex'), cb)
          //client dialed wrong number... (we don't know who they where)
          else
            return abort(null, 'wrong number')
        }
        //check if the user wants to speak to alice.
        authorize(state.remote.public, function (err, auth) {
          if(auth == null && !err) err = new Error('client unauthorized')
          if(!auth) return abort(err, 'client authentication rejected')
          state.auth = auth
          shake.write(state.createServerAccept())
          cb(null, shake.rest(), state.cleanSecrets())
        })
      })
    })
    return stream
  }
}

<|endoftext|>


<commit_before>function Patch() {
    let pointList = [];

    this.node = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');

    this.state = 'normal';

    function build(arg) {
        let res = [];
        for (let i = 0, l = arg.length; i < l; i++) {
            res.push(arg[i].join(','));
        }
        return res.join(' ');
    }

    this.attribute = function (key, val) {
        if (val === undefined) return node.getAttribute(key);
        this.node.setAttribute(key, val);
    };

    this.getPoint = function (i) {
        return pointList[i]
    };

    this.addPoint = function (x, y) {
        pointList.push([x, y]);
        this.attribute('points', build(pointList));
    };

    this.setPoints = function (points) {
        this.attribute('points', build(points));
    };

    this.setPoint = function (i, x, y) {
        pointList[i] = [x, y];
        this.attribute('points', build(pointList));
        // this.invalidate.apply(this);
    };

    this.onclick = function () {
        console.log('default onclick patch');
    };

    this.invalidate = function () {
        this.node.setAttribute('class', this.state);
    };

    this.points = function () {
        for (let i = 0, l = arguments.length; i < l; i += 2) {
            pointList.push([arguments[i], arguments[i + 1]]);
        }
        this.attribute('points', build(pointList));
    };

    // initialize 'points':
    this.points.apply(this, arguments);
}

function Handle(x, y, type) {
    this.node = document.createElementNS('http://www.w3.org/2000/svg', 'circle');

    this.radius = 5;

    this.x = x;
    this.y = y;

    this.type = type;

    this.invalidate = function () {
        this.node.setAttribute('cx', this.x);
        this.node.setAttribute('cy', this.y);
        this.node.setAttribute('r', this.radius);
        this.node.setAttribute('class', this.type);
    };

    this.invalidate.apply(this);
}

function Path() {
    this.node = document.createElementNS('http://www.w3.org/2000/svg', 'path');

    this.points = [];

    this.closePath = false;

    this.invalidate = function () {
        let d = this.build(this.points);

        console.log(d);

        this.node.setAttribute('d', d);
    };

    this.setPoints = function (points) {
        this.points = points;
        this.invalidate.apply(this);
    };

    this.build = function (points) {

        let res = [];

        for (let i = 1, l = points.length; i < l; i++) {
            res.push(points[i].join(' '));
        }

        if (this.closePath) {
            return 'M ' + points[0].join(' ') + ' L ' + res.join(' L ') + ' Z';
        } else {
            return 'M ' + points[0].join(' ') + ' L ' + res.join(' L ');
        }

    }

}

function Polygon(startX, startY, polygonId) {
    this.pointsList = [[startX, startY]];

    this.handles = [];

    this.node = document.createElementNS('http://www.w3.org/2000/svg', 'g');

    this.patch = new Patch();
    this.node.append(this.patch.node);

    // this.patch.onclick = this.onclick;

    this.path = new Path();
    this.node.append(this.path.node);

    let handle = new Handle(startX, startY, 'first');
    this.handles.push(handle);

    this.node.append(handle.node);

    this.polygonId = polygonId;

    this.onPolygonClick = function (polygon) {
        console.log('default onclick polygon');
    };

    this.attribute = function (key, val) {
        if (val === undefined) return this.node.getAttribute(key); // FIXME: Does this node need to be changed to this.node?
        this.node.setAttribute(key, val);
    };

    this.addPoint = function (x, y) {
        this.pointsList.push([x, y]);

        let handle = new Handle(x, y, 'other');
        this.handles.push(handle);

        this.node.append(handle.node);

        this.path.setPoints(this.pointsList);
    };

    this.shouldClose = function (x, y) {
        let x0 = this.pointsList[0][0];
        let y0 = this.pointsList[0][1];

        let dist = Math.sqrt((x0 - x) * (x0 - x) + (y0 - y) * (y0 - y));

        return dist < 8;
    };

    this.onclick = function () {
        this.onPolygonClick(this);
    };

    this.close = function () {
        this.patch.setPoints(this.pointsList);
        this.patch.invalidate();

        this.path.closePath = true;

        this.path.invalidate();

        for (let i in this.handles) {
            this.handles[i].type = 'normal';
            this.handles[i].invalidate();
        }
    };

    this.setSelected = function (selected) {

        let type = 'normal';

        if (selected) {
            type = 'selected';
        }

        this.patch.state = type;
        this.patch.invalidate();

        for (let i in this.handles) {
            this.handles[i].type = type;
            this.handles[i].invalidate();
        }

        console.log(type);

    };

    // Setup event listeners
    this.patch.node.addEventListener('click', this.onclick.bind(this), true);
}
<commit_msg>fixed quotes issues on polygon_primitives.js<commit_after>function Patch() {
    let pointList = [];

    this.node = document.createElementNS("http://www.w3.org/2000/svg", "polygon");

    this.state = "normal";

    function build(arg) {
        let res = [];
        for (let i = 0, l = arg.length; i < l; i++) {
            res.push(arg[i].join(","));
        }
        return res.join(" ");
    }

    this.attribute = function (key, val) {
        if (val === undefined) return node.getAttribute(key);
        this.node.setAttribute(key, val);
    };

    this.getPoint = function (i) {
        return pointList[i]
    };

    this.addPoint = function (x, y) {
        pointList.push([x, y]);
        this.attribute("points", build(pointList));
    };

    this.setPoints = function (points) {
        this.attribute("points", build(points));
    };

    this.setPoint = function (i, x, y) {
        pointList[i] = [x, y];
        this.attribute("points", build(pointList));
        // this.invalidate.apply(this);
    };

    this.onclick = function () {
        console.log("default onclick patch");
    };

    this.invalidate = function () {
        this.node.setAttribute("class", this.state);
    };

    this.points = function () {
        for (let i = 0, l = arguments.length; i < l; i += 2) {
            pointList.push([arguments[i], arguments[i + 1]]);
        }
        this.attribute("points", build(pointList));
    };

    // initialize "points":
    this.points.apply(this, arguments);
}

function Handle(x, y, type) {
    this.node = document.createElementNS("http://www.w3.org/2000/svg", "circle");

    this.radius = 5;

    this.x = x;
    this.y = y;

    this.type = type;

    this.invalidate = function () {
        this.node.setAttribute("cx", this.x);
        this.node.setAttribute("cy", this.y);
        this.node.setAttribute("r", this.radius);
        this.node.setAttribute("class", this.type);
    };

    this.invalidate.apply(this);
}

function Path() {
    this.node = document.createElementNS("http://www.w3.org/2000/svg", "path");

    this.points = [];

    this.closePath = false;

    this.invalidate = function () {
        let d = this.build(this.points);

        console.log(d);

        this.node.setAttribute("d", d);
    };

    this.setPoints = function (points) {
        this.points = points;
        this.invalidate.apply(this);
    };

    this.build = function (points) {

        let res = [];

        for (let i = 1, l = points.length; i < l; i++) {
            res.push(points[i].join(" "));
        }

        if (this.closePath) {
            return "M " + points[0].join(" ") + " L " + res.join(" L ") + " Z";
        } else {
            return "M " + points[0].join(" ") + " L " + res.join(" L ");
        }

    }

}

function Polygon(startX, startY, polygonId) {
    this.pointsList = [[startX, startY]];

    this.handles = [];

    this.node = document.createElementNS("http://www.w3.org/2000/svg", "g");

    this.patch = new Patch();
    this.node.append(this.patch.node);

    // this.patch.onclick = this.onclick;

    this.path = new Path();
    this.node.append(this.path.node);

    let handle = new Handle(startX, startY, "first");
    this.handles.push(handle);

    this.node.append(handle.node);

    this.polygonId = polygonId;

    this.onPolygonClick = function (polygon) {
        console.log("default onclick polygon");
    };

    this.attribute = function (key, val) {
        if (val === undefined) return this.node.getAttribute(key); // FIXME: Does this node need to be changed to this.node?
        this.node.setAttribute(key, val);
    };

    this.addPoint = function (x, y) {
        this.pointsList.push([x, y]);

        let handle = new Handle(x, y, "other");
        this.handles.push(handle);

        this.node.append(handle.node);

        this.path.setPoints(this.pointsList);
    };

    this.shouldClose = function (x, y) {
        let x0 = this.pointsList[0][0];
        let y0 = this.pointsList[0][1];

        let dist = Math.sqrt((x0 - x) * (x0 - x) + (y0 - y) * (y0 - y));

        return dist < 8;
    };

    this.onclick = function () {
        this.onPolygonClick(this);
    };

    this.close = function () {
        this.patch.setPoints(this.pointsList);
        this.patch.invalidate();

        this.path.closePath = true;

        this.path.invalidate();

        for (let i in this.handles) {
            this.handles[i].type = "normal";
            this.handles[i].invalidate();
        }
    };

    this.setSelected = function (selected) {

        let type = "normal";

        if (selected) {
            type = "selected";
        }

        this.patch.state = type;
        this.patch.invalidate();

        for (let i in this.handles) {
            this.handles[i].type = type;
            this.handles[i].invalidate();
        }

        console.log(type);

    };

    // Setup event listeners
    this.patch.node.addEventListener("click", this.onclick.bind(this), true);
}
<|endoftext|>


<commit_before>// Simulate config options from your production environment by
// customising the .env file in your project's root folder.
require('dotenv').load();

// Require keystone
var keystone = require('keystone');

// Initialise Keystone with your project's configuration.
// See http://keystonejs.com/guide/config for available options
// and documentation.

var params = {
	'name': 'Saoye',
	'brand': '骚也',
	'less': 'public',
	'static': 'public',
	'favicon': 'public/favicon.ico',
	'views': 'templates/views',
	'view engine': 'jade',
	'emails': 'templates/emails',
	'auto update': true,
	'session': true,
	'auth': true,
	'user model': 'User',
	'signin logo': '/images/saoye_logo_white.png'
};
if (process.env.MONGOLAB_URI)
    params.mongo = process.env.MONGOLAB_URI;

keystone.init(params);

// Load your project's Models
keystone.import('models');

// Setup common locals for your templates. The following are required for the
// bundled templates and layouts. Any runtime locals (that should be set uniquely
// for each request) should be added to ./routes/middleware.js

keystone.set('locals', {
	_: require('underscore'),
	env: keystone.get('env'),
	utils: keystone.utils,
	editable: keystone.content.editable,
	ga_property: keystone.get('ga property'),
	ga_domain: keystone.get('ga domain')
});

// Load your project's Routes
keystone.set('routes', require('./routes'));

// Configure the navigation bar in Keystone's Admin UI

keystone.set('nav', {
	'文章及分类': ['posts', 'post-categories'],
	'作者': 'authors',
	'后台用户': 'users'
});

// WYSIWYG editor settings
keystone.set('wysiwyg images', true);
keystone.set('wysiwyg additional buttons', 'underline strikethrough sub sup blockquote hr');
keystone.set('wysiwyg additional plugins', 'hr, textcolor');

// Google analytics
if (process.env.GA_PROPERTY && process.env.GA_DOMAIN) {
	keystone.set('ga property', process.env.GA_PROPERTY);
	keystone.set('ga domain', process.env.GA_DOMAIN);
}

// Add a new resource to the root file
keystone.set('static', ['public', 'files']);

// Set S3 configuration.
if (process.env.S3_BUCKET && process.env.S3_KEY && process.env.S3_SECRET) {
	keystone.set('s3 config', {
		bucket: process.env.S3_BUCKET,
		key: process.env.S3_KEY,
		secret: process.env.S3_SECRET,
		'default headers': {
			'x-amz-meta-X-Default-Header': 'Custom Default Value'
		}
	});
}

// Start Keystone to connect to your database and initialise the web server

keystone.start();
<commit_msg>Remove Google analytics from admin UI.<commit_after>// Simulate config options from your production environment by
// customising the .env file in your project's root folder.
require('dotenv').load();

// Require keystone
var keystone = require('keystone');

// Initialise Keystone with your project's configuration.
// See http://keystonejs.com/guide/config for available options
// and documentation.

var params = {
	'name': 'Saoye',
	'brand': '骚也',
	'less': 'public',
	'static': 'public',
	'favicon': 'public/favicon.ico',
	'views': 'templates/views',
	'view engine': 'jade',
	'emails': 'templates/emails',
	'auto update': true,
	'session': true,
	'auth': true,
	'user model': 'User',
	'signin logo': '/images/saoye_logo_white.png'
};
if (process.env.MONGOLAB_URI)
    params.mongo = process.env.MONGOLAB_URI;

keystone.init(params);

// Load your project's Models
keystone.import('models');

// Setup common locals for your templates. The following are required for the
// bundled templates and layouts. Any runtime locals (that should be set uniquely
// for each request) should be added to ./routes/middleware.js
keystone.set('locals', {
	_: require('underscore'),
	env: keystone.get('env'),
	utils: keystone.utils,
	editable: keystone.content.editable,
	ga_property: process.env.GA_PROPERTY,
	ga_domain: process.env.GA_DOMAIN
});

// Load your project's Routes
keystone.set('routes', require('./routes'));

// Configure the navigation bar in Keystone's Admin UI

keystone.set('nav', {
	'文章及分类': ['posts', 'post-categories'],
	'作者': 'authors',
	'后台用户': 'users'
});

// WYSIWYG editor settings
keystone.set('wysiwyg images', true);
keystone.set('wysiwyg additional buttons', 'underline strikethrough sub sup blockquote hr');
keystone.set('wysiwyg additional plugins', 'hr, textcolor');

// Add a new resource to the root file
keystone.set('static', ['public', 'files']);

// Set S3 configuration.
if (process.env.S3_BUCKET && process.env.S3_KEY && process.env.S3_SECRET) {
	keystone.set('s3 config', {
		bucket: process.env.S3_BUCKET,
		key: process.env.S3_KEY,
		secret: process.env.S3_SECRET,
		'default headers': {
			'x-amz-meta-X-Default-Header': 'Custom Default Value'
		}
	});
}

// Start Keystone to connect to your database and initialise the web server

keystone.start();
<|endoftext|>


<commit_before>// Karma configuration

const angular = require('rollup-plugin-angular');
const commonjs = require('rollup-plugin-commonjs');
const nodeResolve = require('rollup-plugin-node-resolve');
const typescript = require('rollup-plugin-typescript');

// rollup-plugin-angular addons
const sass = require('node-sass');
const CleanCSS = require('clean-css');
const htmlMinifier = require('html-minifier');

const cssmin = new CleanCSS();
const htmlminOpts = {
  caseSensitive: true,
  collapseWhitespace: true,
  removeComments: true,
};

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      // Make sure to disable Karma’s file watcher
      // because the preprocessor will use its own.
      { pattern: 'test/*.ts', watched: false },
      { pattern: 'src/*.spec.ts', watched: false },
      { pattern: 'src/**/*.spec.ts', watched: false }
    ],

    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-firefox-launcher'),
      require('karma-coverage'),
      require('karma-rollup-preprocessor'),
    ],

    // list of files to exclude
    exclude: [],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'test/*.ts': ['rollup'],
      'src/*.spec.ts': ['rollup'],
      'src/**/*.spec.ts': ['rollup']
    },

    rollupPreprocessor: {
      // will help to prevent conflicts between different tests entries
      name: 'ngx-prism.core',
      format: 'umd',
      sourcemap: 'inline',
      // rollup settings. See Rollup documentation
      plugins: [
        angular({
          preprocessors: {
            template: template => htmlMinifier.minify(template, htmlminOpts),
            style: scss => {
              const css = sass.renderSync({ data: scss }).css;
              return cssmin.minify(css).styles;
            },
          }
        }),
        commonjs(),
        nodeResolve({
          // use "module" field for ES6 module if possible
          module: true, // Default: true

          // use "jsnext:main" if possible
          // – see https://github.com/rollup/rollup/wiki/jsnext:main
          jsnext: true,  // Default: false

          // use "main" field or index.js, even if it's not an ES6 module
          // (needs to be converted from CommonJS to ES6
          // – see https://github.com/rollup/rollup-plugin-commonjs
          main: true,  // Default: true

          // some package.json files have a `browser` field which
          // specifies alternative files to load for people bundling
          // for the browser. If that's you, use this option, otherwise
          // pkg.browser will be ignored
          browser: true,  // Default: false

          // not all files you want to resolve are .js files
          extensions: [ '.js', '.json' ],  // Default: ['.js']

          // whether to prefer built-in modules (e.g. `fs`, `path`) or
          // local ones with the same names
          preferBuiltins: true,  // Default: true

          // Lock the module search in this path (like a chroot). Module defined
          // outside this path will be mark has external
          jail: '/', // Default: '/'

          // If true, inspect resolved files to check that they are
          // ES2015 modules
          modulesOnly: false, // Default: false

          // Any additional options that should be passed through
          // to node-resolve
          customResolveOptions: {}
        }),
        typescript({
          typescript: require('./node_modules/typescript')
        })
      ]
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', 'coverage', 'kjhtml'],

    // optionally, configure the reporter
    coverageReporter: {
      type : 'html',
      dir : 'coverage/'
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    mime: {
      'text/x-typescript': ['ts','tsx']
    },

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Firefox'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}
<commit_msg>test(karma.conf): change files, sort plugins, remove settings from angular<commit_after>// Karma configuration

const angular = require('rollup-plugin-angular');
const commonjs = require('rollup-plugin-commonjs');
const nodeResolve = require('rollup-plugin-node-resolve');
const typescript = require('rollup-plugin-typescript');

// rollup-plugin-angular addons
const sass = require('node-sass');
const CleanCSS = require('clean-css');
const htmlMinifier = require('html-minifier');

const cssmin = new CleanCSS();
const htmlminOpts = {
  caseSensitive: true,
  collapseWhitespace: true,
  removeComments: true,
};

const rpaConfig = {
  preprocessors: {
    template: template => htmlMinifier.minify(template, htmlminOpts),
    style: scss => {
      const css = sass.renderSync({ data: scss }).css;
      return cssmin.minify(css).styles;
    },
  }
};

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      // Make sure to disable Karma’s file watcher
      // because the preprocessor will use its own.
      { pattern: 'test/index.ts', watched: false },
      { pattern: 'test/*.spec.ts', watched: false },
      { pattern: 'src/*.spec.ts', watched: false },
      { pattern: 'src/**/*.spec.ts', watched: false }
    ],

    plugins: [
      require('karma-chrome-launcher'),
      require('karma-coverage'),
      require('karma-firefox-launcher'),
      require('karma-jasmine'),
      require('karma-jasmine-html-reporter'),
      require('karma-rollup-preprocessor'),
    ],

    // list of files to exclude
    exclude: [],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'test/*.ts': ['rollup'],
      'src/*.spec.ts': ['rollup'],
      'src/**/*.spec.ts': ['rollup']
    },

    rollupPreprocessor: {
      // will help to prevent conflicts between different tests entries
      name: 'ngx-prism.core',
      format: 'umd',
      sourcemap: 'inline',
      // rollup settings. See Rollup documentation
      plugins: [
        angular({}),
        commonjs(),
        nodeResolve({
          // use "module" field for ES6 module if possible
          module: true, // Default: true

          // use "jsnext:main" if possible
          // – see https://github.com/rollup/rollup/wiki/jsnext:main
          jsnext: true,  // Default: false

          // use "main" field or index.js, even if it's not an ES6 module
          // (needs to be converted from CommonJS to ES6
          // – see https://github.com/rollup/rollup-plugin-commonjs
          main: true,  // Default: true

          // some package.json files have a `browser` field which
          // specifies alternative files to load for people bundling
          // for the browser. If that's you, use this option, otherwise
          // pkg.browser will be ignored
          browser: true,  // Default: false

          // not all files you want to resolve are .js files
          extensions: [ '.js', '.json' ],  // Default: ['.js']

          // whether to prefer built-in modules (e.g. `fs`, `path`) or
          // local ones with the same names
          preferBuiltins: true,  // Default: true

          // Lock the module search in this path (like a chroot). Module defined
          // outside this path will be mark has external
          jail: '/', // Default: '/'

          // If true, inspect resolved files to check that they are
          // ES2015 modules
          modulesOnly: false, // Default: false

          // Any additional options that should be passed through
          // to node-resolve
          customResolveOptions: {}
        }),
        typescript({
          typescript: require('./node_modules/typescript')
        })
      ]
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress', 'coverage', 'kjhtml'],

    // optionally, configure the reporter
    coverageReporter: {
      type : 'html',
      dir : 'coverage/'
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    mime: {
      'text/x-typescript': ['ts','tsx']
    },

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Firefox'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}
<|endoftext|>


<commit_before>var HARjson =
<?php
if ( array_key_exists('u', $_GET) ) {
	$target = $_GET["u"];
	echo file_get_contents($target) . ";\n";
}
else if ( array_key_exists('f', $_GET) ) {
	// TODO - remove this - not used since March 24, 2011
	require_once("utils.inc");
	$target = $_GET["f"];
	echo getHarFileContents($target) . ";\n";
}
?>

<commit_msg>fix security issue by constructing the HAR file URL using wptHarFileUrl (rather than straight from querystring param)<commit_after>var HARjson =
<?php
require_once("utils.inc");

$wptid = getParam("wptid");
$wptrun = getParam("wptrun");
$bCached = getParam("cached", 0);
if ( $wptid && $wptrun ) {
	$target = wptHarFileUrl($wptid, $wptrun, $bCached);
	echo file_get_contents($target) . ";\n";
}
else if ( array_key_exists('u', $_GET) ) {
	dprint("ERROR: harviewer.js was accessed using the *deprecated* \"u\" querystring parameter.");
}
else if ( array_key_exists('f', $_GET) ) {
	dprint("ERROR: harviewer.js was accessed using the *deprecated* \"f\" querystring parameter.");
}
?>

<|endoftext|>


<commit_before>// Karma configuration
// Generated on Tue Jul 21 2015 22:34:30 GMT-0400 (EDT)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    plugins: [
        'karma-jasmine',
        'karma-firefox-launcher',
        'karma-mocha-reporter',
        'karma-coverage'
    ],

    // list of files / patterns to load in the browser
    files: [
      'push.js',
      'push_tests.js'
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
        'push.js': ['coverage']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['mocha', 'coverage'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Firefox'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true
  });
};
<commit_msg>Changed coverage to lcov to work with coveralls<commit_after>// Karma configuration
// Generated on Tue Jul 21 2015 22:34:30 GMT-0400 (EDT)

module.exports = function(config) {
    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: '',

        coverageReporter: {
            // specify a common output directory
            dir: 'coverage',
            reporters: [{
                type: 'lcov',
                subdir: '.'
            }]
        },

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ['jasmine'],

        plugins: [
            'karma-jasmine',
            'karma-firefox-launcher',
            'karma-mocha-reporter',
            'karma-coverage'
        ],

        // list of files / patterns to load in the browser
        files: [
            'push.js',
            'push_tests.js'
        ],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            'push.js': ['coverage']
        },

        // test results reporter to use
        // possible values: 'dots', 'progress'
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ['mocha', 'coverage'],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: false,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ['Firefox'],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: true
    });
};
<|endoftext|>


<commit_before>class BoardSpace {
  constructor() {
    this.state = 'empty'; // possible states: empty, one, both
    this.player = undefined;
  }

  move(player) {
    if (this.state === 'empty') {
      this.state = 'one';
      this.player = player;
      return true;
    }
    else if (this.state === 'one' && this.player === player) {
      this.state = 'both';
      return true;
    }
    return false;
  }

  getState() {
    return this.state;
  }
}

class Board {
  constructor(numSpaces) {
    this.spaces = Array(numSpaces).fill(new BoardSpace());
  }

  move(player, spaceIndex) {
    return this.spaces[spaceIndex].move(player);
  }

  getState(spaceIndex) {
    return this.spaces[spaceIndex].getState();
  }
}

class Player {
  constructor(id) {
    this.id = id;
  }
}

class Game {
  constructor() {
    this.board = new Board(18);
    this.players = [];
    this.currentPlayer = undefined;
    this.gameState = 'starting'; // possible states: starting, playing, end
  }

  broadcastState(isReadyForNextTurn) {
    var event = new CustomEvent('broadcaststate', {
      'readyForNextTurn': isReadyForNextTurn,
      'nextPlayer': this.currentPlayer ? this.currentPlayer.id : undefined,
      'board': this.board,
      'gameState': this.gameState
    });

    this.dispatchEvent(event);
  }

  addPlayer(player) {
    this.players.push(player);
    this.broadcastState();
  }

  removePlayer(id) {
    for (let i = 0; i < this.players.length; i++) {
      if (id === this.players[i].id) {
        this.players.splice(i, 1) // remove this.players[i]
      }
    }
    this.broadcastState();
  }

  startGame() {
    this.gameState = 'playing';
    this.broadcastState();
  }

  // returns true on success
  nextTurn() {
    // no players in player array
    if (this.players.length == 0) {
      return false;
    }

    // current player isn't defined
    if (this.currentPlayer == undefined) {
      this.currentPlayer = players[0];
      return true;
    }

    var currentPlayerIndex = this.players.indexOf(this.currentPlayer);
    // current player isn't part of the player array
    if (currentPlayerIndex == -1) {
      return false;
    }

    // normal case, move the player along
    this.currentPlayer = this.players[(currentPlayerIndex + 1) % this.players.length];
    return true;
  }
}
<commit_msg>progress<commit_after>const uuid4 = function () {
  // https://gist.github.com/kaizhu256/4482069
  //// return uuid of form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
  var uuid = '', ii;
  for (ii = 0; ii < 32; ii += 1) {
    switch (ii) {
    case 8:
    case 20:
      uuid += '-';
      uuid += (Math.random() * 16 | 0).toString(16);
      break;
    case 12:
      uuid += '-';
      uuid += '4';
      break;
    case 16:
      uuid += '-';
      uuid += (Math.random() * 4 | 8).toString(16);
      break;
    default:
      uuid += (Math.random() * 16 | 0).toString(16);
    }
  }
  return uuid;
};

const rollDie = function (value) {
  return Math.floor(Math.random() * value) + 1;
}

class BoardSpace {
  constructor() {
    this.state = 'empty'; // possible states: empty, one, both
    this.player = undefined;
  }

  move(player) {
    if (this.state === 'empty') {
      this.state = 'one';
      this.player = player;
      return true;
    }
    else if (this.state === 'one' && this.player === player) {
      this.state = 'both';
      return true;
    }
    return false;
  }
}

class Board {
  constructor(numSpaces) {
    this.spaces = Array(numSpaces).fill(new BoardSpace());
  }

  move(player, spaceIndex) {
    return this.spaces[spaceIndex].move(player);
  }

  getState(spaceIndex) {
    return this.spaces[spaceIndex].getState();
  }
}

class Player {
  constructor(name, color) {
    this.id = uuid4();
    this.name = name;
    this.color = color;
  }
}

class Game {
  constructor() {
    this.board = new Board(18);
    this.players = [];
    this.currentPlayer = undefined;
    this.gameState = 'starting'; // possible states: starting, playing, end
  }

  broadcastState() {
    const state = {
      board: board.spaces.map(item => Object.assign({}, item)),
      players: players.map(player => Object.assign({}, player)),
      currentPlayer: typeof currentPlayer == 'undefined' ? undefined : currentPlayer.id,
      gameState: gameState
    };

    window.dispatch(new CustomEvent('knockout-gamestate', {
      detail: state
    }));
  }

  addPlayer(name, color) {
    if (gameState != 'starting')
      return false;

    players.push(new Player(name, color));
    broadcastState();
    return true;
  }

  removePlayer(id) {
    if (gameState != 'starting')
      return false;

    for (let i = 0; i < this.players.length; i++) {
      if (id === this.players[i].id) {
        this.players.splice(i, 1) // remove this.players[i]
      }
    }
    this.broadcastState();
    return true;
  }

  startGame() {
    if (players.length < 2)
      return false;

    this.gameState = 'playing';
    nextTurn();
  }

  nextTurn() {
    if (this.gameState != 'playing')
      return false;

    const currentPlayerIndex = players.indexOf(this.currentPlayer);
    this.currentPlayer = this.players[(currentPlayerIndex + 1) % this.players.length];

    const turn = {
      player: currentPlayer.id,
      dice: rollDie(6) + rollDie(6) + rollDie(6)
    };

    window.dispatch(new CustomEvent('knockout-nextturn', {
      detail: turn
    }));

    broadcastState();
    return true;
  }
}
<|endoftext|>


<commit_before>
// Karma Unit Test Runner Configuration

module.exports = function(config) {
    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: "",

        browserNoActivityTimeout: 0,

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ["jasmine"],

        // list of files / patterns to load in the browser
        files: [

            // Application Source Files
            // This list should match the order defined in index.html
            "www/js/build-vars.js",
            "www/lib/ionic/js/ionic.bundle.min.js",
            "www/lib/angular-mocks/angular-mocks.js",
            "www/lib/lodash/lodash.js",
            "www/lib/moment/moment.js",
            "www/lib/nprogress/nprogress.js",
            "www/js/bundle.js",
            "www/js/boot1.js",

            // Tests
            "tests/bundle.tests.js",

            // Allow the source maps and source for the TypeScript test files to be served
            // so they can be used for debugging tests, but do not include them as script
            // references in the browser instance.
            {
                pattern: "tests/**/*.js.map",
                included: false,
                watched: false,
                served: true
            },
            {
                pattern: "tests/**/*.ts",
                included: false,
                watched: false,
                served: true
            }
        ],

        // list of files to exclude
        exclude: [
        ],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
        },

        // test results reporter to use
        // possible values: "dots", "progress"
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ["progress"],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ["PhantomJS"],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false
    })
}
<commit_msg>Fixed unit tests<commit_after>
// Karma Unit Test Runner Configuration

module.exports = function(config) {
    config.set({

        // base path that will be used to resolve all patterns (eg. files, exclude)
        basePath: "",

        browserNoActivityTimeout: 0,

        // frameworks to use
        // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
        frameworks: ["jasmine"],

        // list of files / patterns to load in the browser
        files: [

            // Application Source Files
            // This list should match the order defined in index.html
            "www/js/build-vars.js",
            "www/lib/ionic/js/ionic.bundle.min.js",
            "www/lib/angular-mocks/angular-mocks.js",
            "www/lib/lodash/lodash.js",
            "www/lib/moment/moment.js",
            "www/lib/nprogress/nprogress.js",
            "www/js/templates.js",
            "www/js/bundle.js",
            "www/js/boot1.js",

            // Tests
            "tests/bundle.tests.js",

            // Allow the source maps and source for the TypeScript test files to be served
            // so they can be used for debugging tests, but do not include them as script
            // references in the browser instance.
            {
                pattern: "tests/**/*.js.map",
                included: false,
                watched: false,
                served: true
            },
            {
                pattern: "tests/**/*.ts",
                included: false,
                watched: false,
                served: true
            }
        ],

        // list of files to exclude
        exclude: [
        ],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
        },

        // test results reporter to use
        // possible values: "dots", "progress"
        // available reporters: https://npmjs.org/browse/keyword/karma-reporter
        reporters: ["progress"],

        // web server port
        port: 9876,

        // enable / disable colors in the output (reporters and logs)
        colors: true,

        // level of logging
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: config.LOG_INFO,

        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // start these browsers
        // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
        browsers: ["PhantomJS"],

        // Continuous Integration mode
        // if true, Karma captures browsers, runs the tests and exits
        singleRun: false
    })
}
<|endoftext|>


<commit_before>var BigNumber = require('bignumber.js'),
    db = require('../db')

module.exports = function putRecord(store, data, cb) {

  var key = data.StreamName, metaDb = store.metaDb, streamDb = store.getStreamDb(data.StreamName)

  metaDb.lock(key, function(release) {
    cb = release(cb)

    store.getStream(data.StreamName, function(err, stream) {
      if (err) return cb(err)

      if (!~['ACTIVE', 'UPDATING'].indexOf(stream.StreamStatus)) {
        return cb(db.clientError('ResourceNotFoundException',
          'Stream ' + data.StreamName + ' under account ' + metaDb.awsAccountId + ' not found.'))
      }

      var hashKey, shardIx, shardId, shardCreateTime

      if (data.ExplicitHashKey != null) {
        hashKey = new BigNumber(data.ExplicitHashKey)

        if (hashKey.cmp(0) < 0 || hashKey.cmp(new BigNumber(2).pow(128)) >= 0) {
          return cb(db.clientError('InvalidArgumentException',
            'Invalid ExplicitHashKey. ExplicitHashKey must be in the range: [0, 2^128-1]. ' +
            'Specified value was ' + data.ExplicitHashKey))
        }
      } else {
        hashKey = db.partitionKeyToHashKey(data.PartitionKey)
      }

      if (data.SequenceNumberForOrdering != null) {
        try {
          var seqObj = db.parseSequence(data.SequenceNumberForOrdering)
          if (seqObj.seqTime > Date.now()) throw new Error('Sequence time in the future')
        } catch (e) {
          return cb(e.message == 'Unknown version: 3' ? db.serverError() : db.clientError('InvalidArgumentException',
              'ExclusiveMinimumSequenceNumber ' + data.SequenceNumberForOrdering + ' used in PutRecord on stream ' +
              data.StreamName + ' under account ' + metaDb.awsAccountId + ' is invalid.'))
        }
      }

      for (var i = 0; i < stream.Shards.length; i++) {
        if (stream.Shards[i].SequenceNumberRange.EndingSequenceNumber == null &&
            hashKey.cmp(stream.Shards[i].HashKeyRange.StartingHashKey) >= 0 &&
            hashKey.cmp(stream.Shards[i].HashKeyRange.EndingHashKey) <= 0) {
          shardIx = i
          shardId = stream.Shards[i].ShardId
          shardCreateTime = db.parseSequence(
            stream.Shards[i].SequenceNumberRange.StartingSequenceNumber).shardCreateTime
          break
        }
      }

      var seqIxIx = Math.floor(shardIx / 5), now = Math.max(Date.now(), shardCreateTime)

      // Ensure that the first record will always be above the stream start sequence
      if (!stream._seqIx[seqIxIx])
        stream._seqIx[seqIxIx] = shardCreateTime == now ? 1 : 0

      var seqNum = db.stringifySequence({
        shardCreateTime: shardCreateTime,
        shardIx: shardIx,
        seqIx: stream._seqIx[seqIxIx],
        seqTime: now,
      })

      var streamKey = db.shardIxToHex(shardIx) + '/' + seqNum

      stream._seqIx[seqIxIx]++

      metaDb.put(key, stream, function(err) {
        if (err) return cb(err)

        var record = {
          PartitionKey: data.PartitionKey,
          Data: data.Data,
          ApproximateArrivalTimestamp: now / 1000,
        }

        streamDb.put(streamKey, record, function(err) {
          if (err) return cb(err)
          cb(null, {ShardId: shardId, SequenceNumber: seqNum})
        })
      })
    })
  })
}
<commit_msg>Version 3 no longer throws an InternalFailure<commit_after>var BigNumber = require('bignumber.js'),
    db = require('../db')

module.exports = function putRecord(store, data, cb) {

  var key = data.StreamName, metaDb = store.metaDb, streamDb = store.getStreamDb(data.StreamName)

  metaDb.lock(key, function(release) {
    cb = release(cb)

    store.getStream(data.StreamName, function(err, stream) {
      if (err) return cb(err)

      if (!~['ACTIVE', 'UPDATING'].indexOf(stream.StreamStatus)) {
        return cb(db.clientError('ResourceNotFoundException',
          'Stream ' + data.StreamName + ' under account ' + metaDb.awsAccountId + ' not found.'))
      }

      var hashKey, shardIx, shardId, shardCreateTime

      if (data.ExplicitHashKey != null) {
        hashKey = new BigNumber(data.ExplicitHashKey)

        if (hashKey.cmp(0) < 0 || hashKey.cmp(new BigNumber(2).pow(128)) >= 0) {
          return cb(db.clientError('InvalidArgumentException',
            'Invalid ExplicitHashKey. ExplicitHashKey must be in the range: [0, 2^128-1]. ' +
            'Specified value was ' + data.ExplicitHashKey))
        }
      } else {
        hashKey = db.partitionKeyToHashKey(data.PartitionKey)
      }

      if (data.SequenceNumberForOrdering != null) {
        try {
          var seqObj = db.parseSequence(data.SequenceNumberForOrdering)
          if (seqObj.seqTime > Date.now()) throw new Error('Sequence time in the future')
        } catch (e) {
          return cb(db.clientError('InvalidArgumentException',
              'ExclusiveMinimumSequenceNumber ' + data.SequenceNumberForOrdering + ' used in PutRecord on stream ' +
              data.StreamName + ' under account ' + metaDb.awsAccountId + ' is invalid.'))
        }
      }

      for (var i = 0; i < stream.Shards.length; i++) {
        if (stream.Shards[i].SequenceNumberRange.EndingSequenceNumber == null &&
            hashKey.cmp(stream.Shards[i].HashKeyRange.StartingHashKey) >= 0 &&
            hashKey.cmp(stream.Shards[i].HashKeyRange.EndingHashKey) <= 0) {
          shardIx = i
          shardId = stream.Shards[i].ShardId
          shardCreateTime = db.parseSequence(
            stream.Shards[i].SequenceNumberRange.StartingSequenceNumber).shardCreateTime
          break
        }
      }

      var seqIxIx = Math.floor(shardIx / 5), now = Math.max(Date.now(), shardCreateTime)

      // Ensure that the first record will always be above the stream start sequence
      if (!stream._seqIx[seqIxIx])
        stream._seqIx[seqIxIx] = shardCreateTime == now ? 1 : 0

      var seqNum = db.stringifySequence({
        shardCreateTime: shardCreateTime,
        shardIx: shardIx,
        seqIx: stream._seqIx[seqIxIx],
        seqTime: now,
      })

      var streamKey = db.shardIxToHex(shardIx) + '/' + seqNum

      stream._seqIx[seqIxIx]++

      metaDb.put(key, stream, function(err) {
        if (err) return cb(err)

        var record = {
          PartitionKey: data.PartitionKey,
          Data: data.Data,
          ApproximateArrivalTimestamp: now / 1000,
        }

        streamDb.put(streamKey, record, function(err) {
          if (err) return cb(err)
          cb(null, {ShardId: shardId, SequenceNumber: seqNum})
        })
      })
    })
  })
}
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Fri Dec 05 2014 16:49:29 GMT-0500 (EST)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jspm', 'jasmine'],

    jspm: {
      // Edit this to your needs
      loadFiles: ['src/**/*.js', 'test/**/*.js']
    },

    // list of files / patterns to load in the browser
    files: [],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'test/**/*.js': ['babel'],
      'src/**/*.js': ['babel']
    },
    'babelPreprocessor': {
      options: {
        sourceMap: 'inline',
        presets: [ 'es2015-loose', 'stage-1'],
        plugins: [
          'syntax-flow',
          'transform-decorators-legacy',
          'transform-flow-strip-types'
        ]
      }
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};
<commit_msg>chore(karma): polyfill tests<commit_after>// Karma configuration
// Generated on Fri Dec 05 2014 16:49:29 GMT-0500 (EST)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jspm', 'jasmine'],

    jspm: {
      // Edit this to your needs
      loadFiles: [
        'test/setup.js',
        'src/**/*.js',
        'test/**/*.js'
      ]
    },

    // list of files / patterns to load in the browser
    files: [],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'test/**/*.js': ['babel'],
      'src/**/*.js': ['babel']
    },
    'babelPreprocessor': {
      options: {
        sourceMap: 'inline',
        presets: [ 'es2015-loose', 'stage-1'],
        plugins: [
          'syntax-flow',
          'transform-decorators-legacy',
          'transform-flow-strip-types'
        ]
      }
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};
<|endoftext|>


<commit_before>import Ember from 'ember';
import WithConfigMixin from 'ember-idx-utils/mixin/with-config';
import Modal from 'ember-idx-modal/modal';
var computed = Ember.computed;
var COMPONENT_NAME = 'view:em-wysiwyg-action-link-modal';

export default Ember.Component.extend(WithConfigMixin, {
  tagName: 'a',
  classNameBindings: ['styleClasses', 'activeClasses'],
  linkHref: '',
  initModal: (function() {
    var container = this.get('container');
    if(!container.lookupFactory(COMPONENT_NAME)) {
      container._registry.register(COMPONENT_NAME, Modal.extend({
        layoutName: 'components/em-wysiwyg-action-link-modal',
        configName: 'bs',
        parentView: this,
        linkHref: computed.alias('parentView.linkHref'),
        actions: {
          addLink: function() {
            (this.get('parentView') || this.get('_parentView')).send('addLink');
          }
        }
      }));
    }
    this.set('modal', container.lookup(COMPONENT_NAME));
    return this.get('modal').append();
  }).on('init'),
  styleClasses: (function() {
    var _ref;
    return (_ref = this.get('config.wysiwyg.actionClasses')) != null ? _ref.join(" ") : void 0;
  }).property(),
  activeClasses: (function() {
    var _ref;
    if (this.get('active')) {
      return (_ref = this.get('config.wysiwyg.actionActiveClasses')) != null ? _ref.join(" ") : void 0;
    }
  }).property('active'),
  actions: {
    addLink: function() {
      this.get('editor').restoreSelection();
      this.get('editor').$().focus();
      if (this.get('linkHref')) {
        document.execCommand('CreateLink', 0, this.get('linkHref'));
      } else {
        document.execCommand('unlink', 0);
      }
      this.get('editor').saveSelection();
      this.get('wysiwyg').trigger('update_actions');
      return this.get('modal').close();
    }
  },
  click: function() {
    return this.get('modal').open();
  },
  wysiwyg: computed.alias('parentView.wysiwyg'),
  editor: computed.alias('wysiwyg.editor'),
  listenToUpdate: (function() {
    return this.get('wysiwyg').on('update_actions', (function(_this) {
      return function() {
        var container;
        container = _this.get('editor.selectionRange').commonAncestorContainer;
        if (container.nodeType === 3) {
          container = container.parentNode;
        }
        if (container.nodeName === "A") {
          _this.set('linkHref', Ember.$(container).attr('href'));
          return _this.set('active', true);
        } else {
          _this.set('linkHref', '');
          return _this.set('active', false);
        }
      };
    })(this));
  }).on('init')
});
<commit_msg>use registry instead of _registry if available (#10)<commit_after>import Ember from 'ember';
import WithConfigMixin from 'ember-idx-utils/mixin/with-config';
import Modal from 'ember-idx-modal/modal';
var computed = Ember.computed;
var COMPONENT_NAME = 'view:em-wysiwyg-action-link-modal';

export default Ember.Component.extend(WithConfigMixin, {
  tagName: 'a',
  classNameBindings: ['styleClasses', 'activeClasses'],
  linkHref: '',
  initModal: (function() {
    var container = this.get('container');
    if(!container.lookupFactory(COMPONENT_NAME)) {
      (container.registry || container._registry).register(COMPONENT_NAME, Modal.extend({
        layoutName: 'components/em-wysiwyg-action-link-modal',
        configName: 'bs',
        parentView: this,
        linkHref: computed.alias('parentView.linkHref'),
        actions: {
          addLink: function() {
            (this.get('parentView') || this.get('_parentView')).send('addLink');
          }
        }
      }));
    }
    this.set('modal', container.lookup(COMPONENT_NAME));
    return this.get('modal').append();
  }).on('init'),
  styleClasses: (function() {
    var _ref;
    return (_ref = this.get('config.wysiwyg.actionClasses')) != null ? _ref.join(" ") : void 0;
  }).property(),
  activeClasses: (function() {
    var _ref;
    if (this.get('active')) {
      return (_ref = this.get('config.wysiwyg.actionActiveClasses')) != null ? _ref.join(" ") : void 0;
    }
  }).property('active'),
  actions: {
    addLink: function() {
      this.get('editor').restoreSelection();
      this.get('editor').$().focus();
      if (this.get('linkHref')) {
        document.execCommand('CreateLink', 0, this.get('linkHref'));
      } else {
        document.execCommand('unlink', 0);
      }
      this.get('editor').saveSelection();
      this.get('wysiwyg').trigger('update_actions');
      return this.get('modal').close();
    }
  },
  click: function() {
    return this.get('modal').open();
  },
  wysiwyg: computed.alias('parentView.wysiwyg'),
  editor: computed.alias('wysiwyg.editor'),
  listenToUpdate: (function() {
    return this.get('wysiwyg').on('update_actions', (function(_this) {
      return function() {
        var container;
        container = _this.get('editor.selectionRange').commonAncestorContainer;
        if (container.nodeType === 3) {
          container = container.parentNode;
        }
        if (container.nodeName === "A") {
          _this.set('linkHref', Ember.$(container).attr('href'));
          return _this.set('active', true);
        } else {
          _this.set('linkHref', '');
          return _this.set('active', false);
        }
      };
    })(this));
  }).on('init')
});
<|endoftext|>


<commit_before>var isMatch = require("../../src/isMatch");
var chanceFactory = require("chance");
var chance = chanceFactory();

describe("isMatch Suite", function() {
  var criteria, input, act, result;

  beforeEach(function() {
    act = function() {
      result = isMatch(input, criteria);
    };
  });

  describe("when the input and the criteria are both integers", function() {
    describe("that are the same", function() {
      beforeEach(function() {
        input = 2;
        criteria = 2;
        act();
      });

      it("then criteria is a match", function() {
        expect(result).to.be.true;
      });
    });

    describe("that are not the same", function() {
      beforeEach(function() {
        input = 2;
        criteria = 3;
        act();
      });

      it("then the criteria is not a match", function() {
        expect(result).to.be.false;
      });
    });
  });

  describe("when the input is null and the criteria is an object", function() {
    beforeEach(function() {
      input = null;
      criteria = {};
      act();
    });

    it("then the criteria is not a match", function() {
      expect(result).to.be.false;
    });
  });

  describe("when the input and the criteria are both objects", function() {
    describe("and the input and criteria are both empty objects", function() {
      beforeEach(function() {
        input = {};
        criteria = {};
        act();
      });

      it("then the criteria is a match", function() {
        expect(result).to.be.true;
      });

    });

    describe("and the input has a few flat properties", function() {
      beforeEach(function() {
        input = {
          prop1: chance.string(),
          prop2: chance.string(),
          prop3: chance.string()
        };
      });

      describe("and the criteria is empty", function() {
        beforeEach(function() {
          criteria = {};
          act();
        });

        it("then the criteria is a match", function() {
          expect(result).to.be.true;
        });
      });

      describe("and the criteria has one property whose does not match", function() {
        beforeEach(function() {
          criteria = {
            prop1: chance.string()
          };

          act();
        });

        it("then the criteria is not a match", function() {
          expect(result).to.be.false;
        });
      });

      describe("and the criteria has one property that does not exist in the input", function() {
        beforeEach(function() {
          criteria = {
            prop4: chance.string()
          };

          act();
        });

        it("then the criteria is not a match", function() {
          expect(result).to.be.false;
        });
      });

      describe("and the criteria has one property that does match", function() {
        beforeEach(function() {
          criteria = {
            prop1: input.prop1
          };

          act();
        });

        it("then the criteria is a match", function() {
          expect(result).to.be.true;
        });
      });
    });

    describe("and the input is a nested structure with one array and a map", function() {
      beforeEach(function() {
        input = {
          prop1: chance.string(),
          prop2: {
            "prop2--1": chance.string(),
            "prop2--2": {
              "prop2--2--1": ["a"],
              "prop2--2--2": {
                "prop2--2--2--1": chance.string()
              }
            }
          }
        };
      });

      describe("and the criteria has a top level property", function() {
        beforeEach(function() {
          criteria = {
            prop1: input.prop1
          };

          act();
        });

        it("then the criteria is a match", function() {
          expect(result).to.be.true;
        });
      });

      describe("and the criteria has a nested map that matches", function() {
        beforeEach(function() {
          criteria = {
            prop2: {
              "prop2--1": input.prop2["prop2--1"]
            }
          };

          act();
        });

        it("then the criteria is a match", function() {
          expect(result).to.be.true;
        });
      });

      describe("and the criteria has a nested map that does not match", function() {
        beforeEach(function() {
          criteria = {
            prop2: {
              "prop2--1": chance.string()
            }
          };

          act();
        });

        it("then the criteria is not a match", function() {
          expect(result).to.be.false;
        });
      });

      describe("and the criteria has a nested array that matches", function() {
        beforeEach(function() {
          criteria = {
            prop2: {
              "prop2--2": {
                "prop2--2--1": ["a"]
              }
            }
          };

          act();
        });

        it("then the criteria is a match", function() {
          expect(result).to.be.true;
        });
      });

      describe("and the criteria has a nested array that does not match", function() {
        beforeEach(function() {
          criteria = {
            prop2: {
              "prop2--2": {
                "prop2--2--1": ["b"]
              }
            }
          };

          act();
        });

        it("then the criteria is not a match", function() {
          expect(result).to.be.false;
        });
      });

      describe("and the criteria has a nested array with two items and one does not match", function() {
        beforeEach(function() {
          criteria = {
            prop2: {
              "prop2--2": {
                "prop2--2--1": ["a", "b"]
              }
            }
          };

          act();
        });

        it("then the criteria is not a match", function() {
          expect(result).to.be.false;
        });
      });

    });
  });
});

<commit_msg>Added more unit tests to take into account array indexes<commit_after>var isMatch = require("../../src/isMatch");
var chanceFactory = require("chance");
var chance = chanceFactory();

describe("isMatch Suite", function() {
  var criteria, input, act, result;

  beforeEach(function() {
    act = function() {
      result = isMatch(input, criteria);
    };
  });

  describe("when the input and the criteria are both integers", function() {
    describe("that are the same", function() {
      beforeEach(function() {
        input = 2;
        criteria = 2;
        act();
      });

      it("then criteria is a match", function() {
        expect(result).to.be.true;
      });
    });

    describe("that are not the same", function() {
      beforeEach(function() {
        input = 2;
        criteria = 3;
        act();
      });

      it("then the criteria is not a match", function() {
        expect(result).to.be.false;
      });
    });
  });

  describe("when the input is null and the criteria is an object", function() {
    beforeEach(function() {
      input = null;
      criteria = {};
      act();
    });

    it("then the criteria is not a match", function() {
      expect(result).to.be.false;
    });
  });

  describe("when the input and the criteria are both objects", function() {
    describe("and the input and criteria are both empty objects", function() {
      beforeEach(function() {
        input = {};
        criteria = {};
        act();
      });

      it("then the criteria is a match", function() {
        expect(result).to.be.true;
      });

    });

    describe("and the input has a few flat properties", function() {
      beforeEach(function() {
        input = {
          prop1: chance.string(),
          prop2: chance.string(),
          prop3: chance.string()
        };
      });

      describe("and the criteria is empty", function() {
        beforeEach(function() {
          criteria = {};
          act();
        });

        it("then the criteria is a match", function() {
          expect(result).to.be.true;
        });
      });

      describe("and the criteria has one property with a different value than the input", function() {
        beforeEach(function() {
          criteria = {
            prop1: chance.string()
          };

          act();
        });

        it("then the criteria is not a match", function() {
          expect(result).to.be.false;
        });
      });

      describe("and the criteria has one property that does not exist in the input", function() {
        beforeEach(function() {
          criteria = {
            prop4: chance.string()
          };

          act();
        });

        it("then the criteria is not a match", function() {
          expect(result).to.be.false;
        });
      });

      describe("and the criteria has one property with the same value as the input", function() {
        beforeEach(function() {
          criteria = {
            prop1: input.prop1
          };

          act();
        });

        it("then the criteria is a match", function() {
          expect(result).to.be.true;
        });
      });
    });

    describe("and the input is a structure with 2 levels of nested map and array", function() {
      beforeEach(function() {
        input = {
          prop1: 3.14,
          prop2: [4, 8],
          prop3: {
            "prop3--1": [23]
          }
        }
      });

      describe("and the criteria has a property with the same value as the input", function() {
        beforeEach(function() {
          criteria = {
            prop1: 3.14
          };

          act();
        });

        it("then the criteria is a match", function() {
          expect(result).to.be.true;
        });
      });

      describe("and the criteria has an array with an item in the same position as the input", function() {
        beforeEach(function() {
          criteria = {
            prop2: [4]
          };

          act();
        });

        it("then the criteria is a match", function() {
          expect(result).to.be.true;
        });
      });

      describe("and the criteria has an array with an item in a different position than the input", function() {
        beforeEach(function() {
          criteria = {
            prop2: [8]
          };

          act();
        });

        it("then the criteria is not a match", function() {
          expect(result).to.be.false;
        });
      });

      describe("and the criteria has an array with an item that does not exist in the input", function() {
        beforeEach(function() {
          criteria = {
            prop2: [1]
          };

          act();
        });

        it("then the criteria is not a match", function() {
          expect(result).to.be.false;
        });
      });

      describe("and the criteria has a property in the nested map with an array that is in the input", function() {
        beforeEach(function() {
          criteria = {
            prop3: {
              "prop3--1": [23]
            }
          };

          act();
        });

        it("then the criteria is a match", function() {
          expect(result).to.be.true;
        });
      });
    });

    describe("and the input is a structure with 4 levels of nested map and array", function() {
      beforeEach(function() {
        input = {
          prop1: chance.string(),
          prop2: {
            "prop2--1": chance.string(),
            "prop2--2": {
              "prop2--2--1": ["a"],
              "prop2--2--2": {
                "prop2--2--2--1": chance.string()
              }
            }
          }
        };
      });

      describe("and the criteria has a top level property as in the input", function() {
        beforeEach(function() {
          criteria = {
            prop1: input.prop1
          };

          act();
        });

        it("then the criteria is a match", function() {
          expect(result).to.be.true;
        });
      });

      describe("and the criteria has a nested map as in the input", function() {
        beforeEach(function() {
          criteria = {
            prop2: {
              "prop2--1": input.prop2["prop2--1"]
            }
          };

          act();
        });

        it("then the criteria is a match", function() {
          expect(result).to.be.true;
        });
      });

      describe("and the criteria has a nested map different than the input", function() {
        beforeEach(function() {
          criteria = {
            prop2: {
              "prop2--1": chance.string()
            }
          };

          act();
        });

        it("then the criteria is not a match", function() {
          expect(result).to.be.false;
        });
      });

      describe("and the criteria has a nested array as in the input", function() {
        beforeEach(function() {
          criteria = {
            prop2: {
              "prop2--2": {
                "prop2--2--1": ["a"]
              }
            }
          };

          act();
        });

        it("then the criteria is a match", function() {
          expect(result).to.be.true;
        });
      });

      describe("and the criteria has a nested array different than the input", function() {
        beforeEach(function() {
          criteria = {
            prop2: {
              "prop2--2": {
                "prop2--2--1": ["b"]
              }
            }
          };

          act();
        });

        it("then the criteria is not a match", function() {
          expect(result).to.be.false;
        });
      });

      describe("and the criteria has a nested array with two items one of which is not in the input", function() {
        beforeEach(function() {
          criteria = {
            prop2: {
              "prop2--2": {
                "prop2--2--1": ["a", "b"]
              }
            }
          };

          act();
        });

        it("then the criteria is not a match", function() {
          expect(result).to.be.false;
        });
      });

    });
  });
});

<|endoftext|>