<commit_before>//this is a class
//game.PlayerEntity is a class that is why there both capital
//me.Entity is a class
game.PlayerEntity = me.Entity.extend({
	//this is a constructer function
	//melon js uses this contructer on most things for setutp
	//you need x y and settings
	//you're initializing the basic guy
	//super is reaching into the constructer of me.Entity you need settings
	//getShape function is returning a rectangle shape
	//the numbers of the width and height of the box
	//polygon is a method
	init: function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			image: "player",
			width: 64,
			height: 64,
			spritewidth: "64",
			spriteheight: "64",
			getShape: function(){
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);

		//choosing a velocity for the player
		//moving 5 units to the right
		//y is 20 so character is on the floor
		this.body.setVelocity(5, 20);
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

		//this.renderable.addAnimation adds animation using the pictures
		//80 miliseconds is the speed you go through each picture
		//the number is what picture from orcSpear.png the program uses
		this.renderable.addAnimation("idle", [78]);
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);

		//this is the animation it starts at (facing the screen)
		this.renderable.setCurrentAnimation("idle");
	},

	update: function(delta){
		//checking if the right key is pressed
		if(me.input.isKeyPressed("right")){
			//if the key is pressed this is what happens
			//adds the position of my x by the velocity defined above in
			//setVelocity() and multiplying it by me.timer.tick
			//me.timer.tick makes the movement look smooth
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			//this is so the character faces the right when moving to the right (if this isnt here the character faces the left when walking to the right)
			this.flipX(true);
		}
		//if you stop pressing the right key
		else if (me.input.isKeyPressed("left")){
			this.body.vel.x -=this.body.accel.x * me.timer.tick;
			this.flipX(false);
		}
		else{
			//it wont move
			this.body.vel.x = 0;
		}

		if(me.input.isKeyPressed("jump") && !this.falling){
			this.jumping = true;
			this.body.vel.y -= this.body.accel.y * me.timer.tick;
		}

		//this will run only if the character is moving
		if(this.body.vel.x !== 0){
			//this if statement checks what happening with the character
			////if its not moving it'll walk
			//if it isnt it'll walk
			if(!this.renderable.isCurrentAnimation("walk")){
				this.renderable.setCurrentAnimation("walk");
			}
		}
		else if(me.input.isKeyPressed("attack")){
			if(!this.renderable.isCurrentAnimation("attack")){
				console.log(!this.renderable.isCurrentAnimation("attack"));
				this.renderable.setCurrentAnimation("attack", "idle");
				this.renderable.setAnimationFrame();
			}
		}
		//this will run if the velocity is not 0
		//this will make the walking stop
		else{
			this.renderable.setCurrentAnimation("idle");
		}

		//delta is the change of time its happened
		this.body.update(delta);

		//calling the parent class
		//this is updating the super class so the animations can update
		this._super(me.Entity, "update", [delta]);
		return true;
	}
});

//this is a class
//making a constructor with ._super
//setting the picture and size
//getShape is returning a rectangle
//toPolygon is there so you can use it
game.PlayerBaseEntity = me.Entity.extend({
	init : function (x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			image : "tower",
			width : 100,
			height : 100,
			spritewidth : "100",
			spriteheight : "100",
			getShape: function(){
				return (new me.Rect (0, 0, 70, 70)).toPolygon();
			}
		}]);
		//this variable is saying the tower isnt broken
		this.broken = false;
		//this variable is setting the health to 10
		this.health = 10;
		//this variable is saying it'll always update whether or not your looking at it
		this.alwaysUpdate = true;
		//this variable is so if somebody runs into the tower you can collide with it
		this.body.onCollision = this.onCollision.bind(this);

		//the type allows you to use it when doing other collisions and you can check what your running into
		this.type = "PlayerBaseEntity";

		this.renderable.addAnimation("idle", [0]);
		this.renderable.addAnimation("broken", [1]);
		this.renderable.setCurrentAnimation("idle");
	},

	update:function(delta) {
		//this runs when the health is less than or equal to zero
		if(this.health<=0){
			//if its true your character is dead
			this.broken = true;
			this.renderable.setCurrentAnimation("broken");
		}
		//then it updates delta (the time)
		this.body.update(delta);

		//calling the super
		//updating and returning
		this._super(me.Entity, "update", [delta]);
		return true;
	},

	//for colliding
	onCollision: function(){

	}

});

//this is a class for the enemy base
//almost the same the class above
game.EnemyBaseEntity = me.Entity.extend({
	init : function (x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			image : "tower",
			width : 100,
			height : 100,
			spritewidth : "100",
			spriteheight : "100",
			getShape: function(){
				return (new me.Rect (0, 0, 70, 70)).toPolygon();
			}
		}]);
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "EnemyBaseEntity";

		this.renderable.addAnimation("idle", [0]);
		this.renderable.addAnimation("broken", [1]);
		this.renderable.setCurrentAnimation("idle");

	},

	update:function(delta) {
		if(this.health<=0){
			this.broken = true;
			this.renderable.setCurrentAnimation("broken");
		}
		this.body.update(delta);

		this._super(me.Entity, "update", [delta]);
		return true;
	},

	onCollision: function(){

	}

});<commit_msg>finished video 15 no comments { Colliding with Bases from the Left & Right }<commit_after>//this is a class
//game.PlayerEntity is a class that is why there both capital
//me.Entity is a class
game.PlayerEntity = me.Entity.extend({
	//this is a constructer function
	//melon js uses this contructer on most things for setutp
	//you need x y and settings
	//you're initializing the basic guy
	//super is reaching into the constructer of me.Entity you need settings
	//getShape function is returning a rectangle shape
	//the numbers of the width and height of the box
	//polygon is a method
	init: function(x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			image: "player",
			width: 64,
			height: 64,
			spritewidth: "64",
			spriteheight: "64",
			getShape: function(){
				return(new me.Rect(0, 0, 64, 64)).toPolygon();
			}
		}]);

		//choosing a velocity for the player
		//moving 5 units to the right
		//y is 20 so character is on the floor
		this.body.setVelocity(5, 20);
		this.facing = "right";
		me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

		//this.renderable.addAnimation adds animation using the pictures
		//80 miliseconds is the speed you go through each picture
		//the number is what picture from orcSpear.png the program uses
		this.renderable.addAnimation("idle", [78]);
		this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
		this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);

		//this is the animation it starts at (facing the screen)
		this.renderable.setCurrentAnimation("idle");
	},

	update: function(delta){
		//checking if the right key is pressed
		if(me.input.isKeyPressed("right")){
			//if the key is pressed this is what happens
			//adds the position of my x by the velocity defined above in
			//setVelocity() and multiplying it by me.timer.tick
			//me.timer.tick makes the movement look smooth
			this.body.vel.x += this.body.accel.x * me.timer.tick;
			//this is so the character faces the right when moving to the right (if this isnt here the character faces the left when walking to the right)
			this.facing = "right";
			this.flipX(true);
		}
		//if you stop pressing the right key
		else if (me.input.isKeyPressed("left")){
			this.facing = "left";
			this.body.vel.x -=this.body.accel.x * me.timer.tick;
			this.flipX(false);
		}
		else{
			//it wont move
			this.body.vel.x = 0;
		}

		if(me.input.isKeyPressed("jump") && !this.body.falling && !this.body.jumping){
			this.body.jumping = true;
			this.body.vel.y -= this.body.accel.y * me.timer.tick;
		}

		//this will run only if the character is moving
		if(this.body.vel.x !== 0){
			//this if statement checks what happening with the character
			////if its not moving it'll walk
			//if it isnt it'll walk
			if(!this.renderable.isCurrentAnimation("walk")){
				this.renderable.setCurrentAnimation("walk");
			}
		}
		else if(me.input.isKeyPressed("attack")){
			if(!this.renderable.isCurrentAnimation("attack")){
				console.log(!this.renderable.isCurrentAnimation("attack"));
				this.renderable.setCurrentAnimation("attack", "idle");
				this.renderable.setAnimationFrame();
			}
		}
		//this will run if the velocity is not 0
		//this will make the walking stop
		else{
			this.renderable.setCurrentAnimation("idle");
		}

		me.collision.check(this, true, this.collideHandler.bind(this), true);
		//delta is the change of time its happened
		this.body.update(delta);

		//calling the parent class
		//this is updating the super class so the animations can update
		this._super(me.Entity, "update", [delta]);
		return true;
	},

	collideHandler: function(response){
		if(response.b.type==='EnemyBaseEntity'){
			var ydif = this.pos.y - response.b.pos.y;
			var xdif = this.pos.x - response.b.pos.x;

			console.log("xdif " + xdif + " ydif " + ydif);

			if(xdif>-35 && this.facing==='right' && (xdif<0)){
				this.body.vel.x = 0;
				this.pos.x = this.pos.x -1;
			}
			else if(xdif<70 && this.facing==='left' && (xdif>0)){
				this.body.vel.x = 0;
				this.pos.x = this.pos.x +1;
			}
		}
	}
});

//this is a class
//making a constructor with ._super
//setting the picture and size
//getShape is returning a rectangle
//toPolygon is there so you can use it
game.PlayerBaseEntity = me.Entity.extend({
	init : function (x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			image : "tower",
			width : 100,
			height : 100,
			spritewidth : "100",
			spriteheight : "100",
			getShape: function(){
				return (new me.Rect (0, 0, 70, 70)).toPolygon();
			}
		}]);
		//this variable is saying the tower isnt broken
		this.broken = false;
		//this variable is setting the health to 10
		this.health = 10;
		//this variable is saying it'll always update whether or not your looking at it
		this.alwaysUpdate = true;
		//this variable is so if somebody runs into the tower you can collide with it
		this.body.onCollision = this.onCollision.bind(this);

		//the type allows you to use it when doing other collisions and you can check what your running into
		this.type = "PlayerBaseEntity";

		this.renderable.addAnimation("idle", [0]);
		this.renderable.addAnimation("broken", [1]);
		this.renderable.setCurrentAnimation("idle");
	},

	update:function(delta) {
		//this runs when the health is less than or equal to zero
		if(this.health<=0){
			//if its true your character is dead
			this.broken = true;
			this.renderable.setCurrentAnimation("broken");
		}
		//then it updates delta (the time)
		this.body.update(delta);

		//calling the super
		//updating and returning
		this._super(me.Entity, "update", [delta]);
		return true;
	},

	//for colliding
	onCollision: function(){

	}

});

//this is a class for the enemy base
//almost the same the class above
game.EnemyBaseEntity = me.Entity.extend({
	init : function (x, y, settings){
		this._super(me.Entity, 'init', [x, y, {
			image : "tower",
			width : 100,
			height : 100,
			spritewidth : "100",
			spriteheight : "100",
			getShape: function(){
				return (new me.Rect (0, 0, 70, 70)).toPolygon();
			}
		}]);
		this.broken = false;
		this.health = 10;
		this.alwaysUpdate = true;
		this.body.onCollision = this.onCollision.bind(this);

		this.type = "EnemyBaseEntity";

		this.renderable.addAnimation("idle", [0]);
		this.renderable.addAnimation("broken", [1]);
		this.renderable.setCurrentAnimation("idle");

	},

	update:function(delta) {
		if(this.health<=0){
			this.broken = true;
			this.renderable.setCurrentAnimation("broken");
		}
		this.body.update(delta);

		this._super(me.Entity, "update", [delta]);
		return true;
	},

	onCollision: function(){

	}

});<|endoftext|>


<commit_before>var gulp = require('gulp-help')(require('gulp'), {description: ''});
var $ = require('gulp-load-plugins')();
var through = require('through2');
var runSequence = require('run-sequence');
var del = require('del');
var buildBranch = require('buildbranch');
var webpackMiddleware = require('webpack-dev-middleware');
var webpack = require('webpack');
var path = require('path');

var webpackConfigTemplate = {
  entry: {
    index: './src/scripts/index.js',
    thirdparty: [
      /* consider es6-shim or transpiler instead */
      'Array.prototype.find',
      'Array.prototype.findIndex',
      'String.prototype.endsWith',
      'smoothscroll',
      'raf.js',
      'd3',
      'moment',
      'pikaday',
      'query-string',
      'superagent',
      'vue',
      'fastclick',
      'http-status',
      'grapnel',
      'strkio-storage-githubgist'
    ]
  },
  resolve: {
    modulesDirectories: ['bower_components', 'node_modules'],
    alias: {
      superagent: 'superagent/superagent.js'
    }
  },
  externals: {
    jsonify: 'JSON'
  },
  module: {
    noParse: [/(d3|moment|pikaday|query-string|superagent|vue|fastclick)/],
    loaders: [
      {
        test: /\.html/,
        loader: 'html',
        query: {
          removeRedundantAttributes: false // because of foundation
        }
      }
    ]
  },
  plugins: [
    new webpack.ResolverPlugin(
      new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin(
        '.bower.json', ['main']
      )
    ),
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
  ]
};

var optimize = false;

var src = {
  js: ['gulpfile.js', 'src/scripts/**/*.js'],
  css: 'src/stylesheets/**/*.css',
  html: 'src/*.html'
};

gulp.task('build', function (cb) {
  optimize = true;
  runSequence(
    'clean', [
      'build:favicon',
      'build:fonts',
      'build:html',
      'build:scripts',
      'build:stylesheets'
    ],
    'build:rev',
    'build:manifest',
    cb);
});

gulp.task('build:favicon', function () {
  gulp.src('src/favicon.ico')
    .pipe(gulp.dest('build'));
});

gulp.task('build:fonts', function () {
  return gulp.src('src/fonts/*.ttf', {base: 'src'})
    .pipe(gulp.dest('build'));
});

gulp.task('build:html', function () {
  var htmlminConfig = {};
  var preprocessctx = {};
  if (optimize) {
    htmlminConfig.removeComments = true;
    htmlminConfig.collapseWhitespace = true;
    preprocessctx.NODE_ENV = 'production';
  }
  return gulp.src(src.html)
    .pipe($.preprocess({context: preprocessctx}))
    .pipe($.htmlmin(htmlminConfig))
    .pipe(gulp.dest('build'));
});

gulp.task('build:manifest', function () {
  return gulp.src(['build/**'])
    .pipe($.manifest({
      hash: true,
      filename: 'cache.manifest',
      exclude: ['cache.manifest', '404.html']
    }))
    .pipe(gulp.dest('build'));
});

gulp.task('build:rev', function (cb) {
  var revved = [];
  var filter = $.filter(['**', '!index.html', '!404.html']);
  gulp.src([
    'build/scripts/*.js',
    'build/stylesheets/*.css',
    'build/favicon.ico',
    'build/index.html'
  ], {base: path.join(__dirname, 'build')})
    .pipe(filter)
    .pipe($.rev())
    .pipe(filter.restore())
    .pipe(through.obj(function (file, enc, callback) {
      if (file.revOrigPath) {
        revved.push(file.revOrigPath);
      }
      this.push(file);
      callback();
    }))
    .pipe($.revReplace({replaceInExtensions: '.html'}))
    .pipe(gulp.dest('build'))
    .on('end', function () {
      del(revved, cb);
    });
});

gulp.task('build:scripts', function (cb) {
  var webpackConfig = Object.create(webpackConfigTemplate);
  if (optimize) {
    webpackConfig.plugins || (webpackConfig.plugins = []);
    webpackConfig.plugins.push(new webpack.DefinePlugin({
      __DEV__: false
    }));
    webpackConfig.plugins.push(new webpack.optimize.CommonsChunkPlugin(
      'thirdparty', 'build/scripts/thirdparty.js'));
    webpackConfig.plugins.push(new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    }));
    delete webpackConfig.entry['dev-mode'];
  }
  webpackConfig.output = {filename: 'build/scripts/[name].js'};
  webpack(webpackConfig, function (err, stats) {
    if (err) {
      return cb(err);
    }
    console.log(stats.toString());
    cb();
  });
});

gulp.task('build:stylesheets', function () {
  return gulp.src([
    'src/stylesheets/index.css',
    'src/stylesheets/thirdparty.css' // todo: replace with concat
  ], {base: 'src'})
    .pipe($.myth())
    .on('error', console.log)
    .pipe(optimize ? $.csso() : through.obj())
    .pipe(gulp.dest('build'));
});

gulp.task('clean', function (cb) {
  del(['build'], {force: true}, cb);
});

gulp.task('deploy', function (cb) {
  buildBranch({
    ignore: ['bower_components'],
    folder: 'build',
    domain: 'strk.io',
    branch: 'master'
  }, cb);
});

gulp.task('lint', ['lint:scripts']);

gulp.task('lint:scripts', function () {
  return gulp.src(src.js)
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.jscs());
});

gulp.task('serve', ['clean'], function (cb) {
  var webpackConfig = Object.create(webpackConfigTemplate);
  webpackConfig.devtool = 'eval'; // http://webpack.github.io/docs/configuration.html#devtool
  webpackConfig.output = {path: '/', filename: 'scripts/[name].js'};
  webpackConfig.plugins || (webpackConfig.plugins = []);
  webpackConfig.plugins.push(new webpack.DefinePlugin({
    __DEV__: true
  }));
  webpackConfig.plugins.push(new webpack.optimize.CommonsChunkPlugin(
    'thirdparty', 'scripts/thirdparty.js'));
  runSequence(['build:stylesheets', 'build:html'], function () {
    $.connect.server({
      root: ['build', 'src', '.'],
      port: 8000,
      middleware: function () {
        return [
          webpackMiddleware(webpack(webpackConfig))
        ];
      }
    });
    gulp.watch(src.css, ['build:stylesheets']);
    gulp.watch(src.js, ['lint:scripts']);
    gulp.watch(src.html, ['build:html']);
    cb();
  });
});

gulp.task('serve:build', function () {
  $.connect.server({root: 'build', port: 8000});
});
<commit_msg>Directed webpack at unminified version of grapnel<commit_after>var gulp = require('gulp-help')(require('gulp'), {description: ''});
var $ = require('gulp-load-plugins')();
var through = require('through2');
var runSequence = require('run-sequence');
var del = require('del');
var buildBranch = require('buildbranch');
var webpackMiddleware = require('webpack-dev-middleware');
var webpack = require('webpack');
var path = require('path');

var webpackConfigTemplate = {
  entry: {
    index: './src/scripts/index.js',
    thirdparty: [
      /* consider es6-shim or transpiler instead */
      'Array.prototype.find',
      'Array.prototype.findIndex',
      'String.prototype.endsWith',
      'smoothscroll',
      'raf.js',
      'd3',
      'moment',
      'pikaday',
      'query-string',
      'superagent',
      'vue',
      'fastclick',
      'http-status',
      'grapnel',
      'strkio-storage-githubgist'
    ]
  },
  resolve: {
    modulesDirectories: ['bower_components', 'node_modules'],
    alias: {
      superagent: 'superagent/superagent.js',
      grapnel: 'grapnel/src/grapnel.js'
    }
  },
  externals: {
    jsonify: 'JSON'
  },
  module: {
    noParse: [
      /(d3|moment|pikaday|query-string|superagent|vue|fastclick|grapnel)/
    ],
    loaders: [
      {
        test: /\.html/,
        loader: 'html',
        query: {
          removeRedundantAttributes: false // because of foundation
        }
      }
    ]
  },
  plugins: [
    new webpack.ResolverPlugin(
      new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin(
        '.bower.json', ['main']
      )
    ),
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
  ]
};

var optimize = false;

var src = {
  js: ['gulpfile.js', 'src/scripts/**/*.js'],
  css: 'src/stylesheets/**/*.css',
  html: 'src/*.html'
};

gulp.task('build', function (cb) {
  optimize = true;
  runSequence(
    'clean', [
      'build:favicon',
      'build:fonts',
      'build:html',
      'build:scripts',
      'build:stylesheets'
    ],
    'build:rev',
    'build:manifest',
    cb);
});

gulp.task('build:favicon', function () {
  gulp.src('src/favicon.ico')
    .pipe(gulp.dest('build'));
});

gulp.task('build:fonts', function () {
  return gulp.src('src/fonts/*.ttf', {base: 'src'})
    .pipe(gulp.dest('build'));
});

gulp.task('build:html', function () {
  var htmlminConfig = {};
  var preprocessctx = {};
  if (optimize) {
    htmlminConfig.removeComments = true;
    htmlminConfig.collapseWhitespace = true;
    preprocessctx.NODE_ENV = 'production';
  }
  return gulp.src(src.html)
    .pipe($.preprocess({context: preprocessctx}))
    .pipe($.htmlmin(htmlminConfig))
    .pipe(gulp.dest('build'));
});

gulp.task('build:manifest', function () {
  return gulp.src(['build/**'])
    .pipe($.manifest({
      hash: true,
      filename: 'cache.manifest',
      exclude: ['cache.manifest', '404.html']
    }))
    .pipe(gulp.dest('build'));
});

gulp.task('build:rev', function (cb) {
  var revved = [];
  var filter = $.filter(['**', '!index.html', '!404.html']);
  gulp.src([
    'build/scripts/*.js',
    'build/stylesheets/*.css',
    'build/favicon.ico',
    'build/index.html'
  ], {base: path.join(__dirname, 'build')})
    .pipe(filter)
    .pipe($.rev())
    .pipe(filter.restore())
    .pipe(through.obj(function (file, enc, callback) {
      if (file.revOrigPath) {
        revved.push(file.revOrigPath);
      }
      this.push(file);
      callback();
    }))
    .pipe($.revReplace({replaceInExtensions: '.html'}))
    .pipe(gulp.dest('build'))
    .on('end', function () {
      del(revved, cb);
    });
});

gulp.task('build:scripts', function (cb) {
  var webpackConfig = Object.create(webpackConfigTemplate);
  if (optimize) {
    webpackConfig.plugins || (webpackConfig.plugins = []);
    webpackConfig.plugins.push(new webpack.DefinePlugin({
      __DEV__: false
    }));
    webpackConfig.plugins.push(new webpack.optimize.CommonsChunkPlugin(
      'thirdparty', 'build/scripts/thirdparty.js'));
    webpackConfig.plugins.push(new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    }));
    delete webpackConfig.entry['dev-mode'];
  }
  webpackConfig.output = {filename: 'build/scripts/[name].js'};
  webpack(webpackConfig, function (err, stats) {
    if (err) {
      return cb(err);
    }
    console.log(stats.toString());
    cb();
  });
});

gulp.task('build:stylesheets', function () {
  return gulp.src([
    'src/stylesheets/index.css',
    'src/stylesheets/thirdparty.css' // todo: replace with concat
  ], {base: 'src'})
    .pipe($.myth())
    .on('error', console.log)
    .pipe(optimize ? $.csso() : through.obj())
    .pipe(gulp.dest('build'));
});

gulp.task('clean', function (cb) {
  del(['build'], {force: true}, cb);
});

gulp.task('deploy', function (cb) {
  buildBranch({
    ignore: ['bower_components'],
    folder: 'build',
    domain: 'strk.io',
    branch: 'master'
  }, cb);
});

gulp.task('lint', ['lint:scripts']);

gulp.task('lint:scripts', function () {
  return gulp.src(src.js)
    .pipe($.jshint())
    .pipe($.jshint.reporter('jshint-stylish'))
    .pipe($.jscs());
});

gulp.task('serve', ['clean'], function (cb) {
  var webpackConfig = Object.create(webpackConfigTemplate);
  webpackConfig.devtool = 'eval'; // http://webpack.github.io/docs/configuration.html#devtool
  webpackConfig.output = {path: '/', filename: 'scripts/[name].js'};
  webpackConfig.plugins || (webpackConfig.plugins = []);
  webpackConfig.plugins.push(new webpack.DefinePlugin({
    __DEV__: true
  }));
  webpackConfig.plugins.push(new webpack.optimize.CommonsChunkPlugin(
    'thirdparty', 'scripts/thirdparty.js'));
  runSequence(['build:stylesheets', 'build:html'], function () {
    $.connect.server({
      root: ['build', 'src', '.'],
      port: 8000,
      middleware: function () {
        return [
          webpackMiddleware(webpack(webpackConfig))
        ];
      }
    });
    gulp.watch(src.css, ['build:stylesheets']);
    gulp.watch(src.js, ['lint:scripts']);
    gulp.watch(src.html, ['build:html']);
    cb();
  });
});

gulp.task('serve:build', function () {
  $.connect.server({root: 'build', port: 8000});
});
<|endoftext|>


<commit_before>game.PlayerEntity = me.Entity.extend({
    init: function(x, y, settings){
        this._super(me.Entity, 'init', [x, y, {
                image: "player",
                width: 64,
                height: 64,
                spritewidth: "64",
                spriteheight: "64",
                getShape: function(){
                    return(new me.Rect(0, 0, 100, 70)).toPolygon();
                }
        }]);

    this.body.setVelocity(5, 20);
    me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

    this.renderable.addAnimation("idle", [78]);
    this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
    this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);

    this.renderable.setCurrentAnimation("idle");
    },

    update: function(delta){
        if(me.input.isKeyPressed("right")){
           // adds to the position of my x by the velocity defined above in
           //setVelocity() and multiplying it by timer.tick.
           //me.timer.tick makes the movement look smooth
            this.body.vel.x -= this.body.accel.x * me.timer.tick;
            this.flipX(true);
        }else{
            this.body.vel.x = 0;
        }

          if(me.input.isKeyPressed("attack")){

            if(!this.renderable.isCurrentAnimation("attack")){
                console.log(!this.renderable.isCurrentAnimation("attack"));
                //Sets the current animation to attack and once that is over
                //goes back to the idle animation
                this.renderable.setCurrentAnimation("attack", "idle");
               //Makes it so that the next time we start this sequence we begin
               //from the first animation, not wherever we left off when we
               //switched to another animation
                this.renderable.setAnimationFrame();
            }
        }
    else if(this.body.vel.x !== 0){
    if(!this.renderable.isCurrentAnimation("walk")){
        this.renderable.isCurrentAnimation("walk");
    }
    }else{
        this.renderable.setCurrentAnimation("idle");
    }
             if(me.input.isKeyPressed("attack")){

            if(!this.renderable.isCurrentAnimation("attack")){
                console.log(!this.renderable.isCurrentAnimation("attack"));
                //Sets the current animation to attack and once that is over
                //goes back to the idle animation
                this.renderable.setCurrentAnimation("attack", "idle");
               //Makes it so that the next time we start this sequence we begin
               //from the first animation, not wherever we left off when we
               //switched to another animation
                this.renderable.setAnimationFrame();
            }
        }

        this.body.update(delta);

       this._super(me.Entity, "update", [delta]);
        return true;

    }
});

game.PlayerBaseEntity =  me.Entity.extend({
    init : function(x, y, settings){
        this._super(me.Entity, 'init', [x, y, {
                image: "tower",
                width: 100,
                height: 100,
                spritewidth: "100",
                spriteheight: "100",
                getShape: function(){
                    return (new me.Rect(0, 0, 100, 70)).toPolygon();
                }
        }]);
        this.broken = false;
        this.health = 10;
        this.alwaysUpdate = true;
        this.body.onCollision = this.onCollision.bind(this);
        console.log("init");
        this.type = "PlayerBaseEntity";

         this.renderable.addAnimation("idle", [0]);
         this.renderable.addAnimation("broken", [1]);
         this.renderable.setCurrentAnimation("idle");
    },

    update:function(){
      if(this.health<=0){
          this.broken = true;
          this.renderable.setCurrentAnimation("broken");
      }
      this.body.update(delta);

      this._super(me.Entity, "update", [delta]);
      return true;
    },

    onCollision: function(){

    }

});

game.EnemyBaseEntity =  me.Entity.extend({
    init : function(x, y, settings){
        this._super(me.Entity, 'init', [x, y, {
                image: "tower",
                width: 100,
                height: 100,
                spritewidth: "100",
                spriteheight: "100",
                getShape: function(){
                    return (new me.Rect(0, 0, 100, 100)).toPolygon();
                }
        }]);
        this.broken = false;
        this.health = 10;
        this.alwaysUpdate = true;
        this.body.onCollision = this.onCollision.bind(this);

        this.type = "EnemyBaseEntity";

         this.renderable.addAnimation("idle", [0]);
         this.renderable.addAnimation("broken", [1]);
         this.renderable.setCurrentAnimation("idle");
    },

    update:function(){
      if(this.health<=0){
          this.broken = true;
          this.renderable.setCurrentAnimation("broken");
      }
      this.body.update(delta);

      this._super(me.Entity, "update", [delta]);
      return true;
    },

    onCollision: function(){

    }

});<commit_msg>gygyggygyg gygygygygygygyg<commit_after>game.PlayerEntity = me.Entity.extend({
    init: function(x, y, settings){
        this._super(me.Entity, 'init', [x, y, {
                image: "player",
                width: 64,
                height: 64,
                spritewidth: "64",
                spriteheight: "64",
                getShape: function(){
                    return(new me.Rect(0, 0, 100, 70)).toPolygon();
                }
        }]);

    this.body.setVelocity(5, 20);
    me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

    this.renderable.addAnimation("idle", [78]);
    this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
    this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);

    this.renderable.setCurrentAnimation("idle");
    },

    update: function(delta){
        if(me.input.isKeyPressed("right")){
           // adds to the position of my x by the velocity defined above in
           //setVelocity() and multiplying it by timer.tick.
           //me.timer.tick makes the movement look smooth
            this.body.vel.x -= this.body.accel.x * me.timer.tick;
            this.flipX(true);
        }else if(me.input.isKeyPressed("left")){
            this.body..vel.x -=this.body.accel.x * me.timer.tick;
            this.flipX(false);
        }else{
            this.body.vel.x = 0;
        }

        if(me.input.isKeyPressed("jump") && !this.jumping && !this.falling){
           this.jumping = true;
           this.body.vel.y -= this.body.accel.y * me.timer.tick;
        }

          if(me.input.isKeyPressed("attack")){

            if(!this.renderable.isCurrentAnimation("attack")){
                console.log(!this.renderable.isCurrentAnimation("attack"));
                //Sets the current animation to attack and once that is over
                //goes back to the idle animation
                this.renderable.setCurrentAnimation("attack", "idle");
               //Makes it so that the next time we start this sequence we begin
               //from the first animation, not wherever we left off when we
               //switched to another animation
                this.renderable.setAnimationFrame();
            }
        }
    else if(this.body.vel.x !== 0){
    if(!this.renderable.isCurrentAnimation("walk")){
        this.renderable.isCurrentAnimation("walk");
    }
    }else{
        this.renderable.setCurrentAnimation("idle");
    }
             if(me.input.isKeyPressed("attack")){

            if(!this.renderable.isCurrentAnimation("attack")){
                console.log(!this.renderable.isCurrentAnimation("attack"));
                //Sets the current animation to attack and once that is over
                //goes back to the idle animation
                this.renderable.setCurrentAnimation("attack", "idle");
               //Makes it so that the next time we start this sequence we begin
               //from the first animation, not wherever we left off when we
               //switched to another animation
                this.renderable.setAnimationFrame();
            }
        }

        this.body.update(delta);

       this._super(me.Entity, "update", [delta]);
        return true;

    }
});

game.PlayerBaseEntity =  me.Entity.extend({
    init : function(x, y, settings){
        this._super(me.Entity, 'init', [x, y, {
                image: "tower",
                width: 100,
                height: 100,
                spritewidth: "100",
                spriteheight: "100",
                getShape: function(){
                    return (new me.Rect(0, 0, 100, 70)).toPolygon();
                }
        }]);
        this.broken = false;
        this.health = 10;
        this.alwaysUpdate = true;
        this.body.onCollision = this.onCollision.bind(this);
        console.log("init");
        this.type = "PlayerBaseEntity";

         this.renderable.addAnimation("idle", [0]);
         this.renderable.addAnimation("broken", [1]);
         this.renderable.setCurrentAnimation("idle");
    },

    update:function(){
      if(this.health<=0){
          this.broken = true;
          this.renderable.setCurrentAnimation("broken");
      }
      this.body.update(delta);

      this._super(me.Entity, "update", [delta]);
      return true;
    },

    onCollision: function(){

    }

});

game.EnemyBaseEntity =  me.Entity.extend({
    init : function(x, y, settings){
        this._super(me.Entity, 'init', [x, y, {
                image: "tower",
                width: 100,
                height: 100,
                spritewidth: "100",
                spriteheight: "100",
                getShape: function(){
                    return (new me.Rect(0, 0, 100, 100)).toPolygon();
                }
        }]);
        this.broken = false;
        this.health = 10;
        this.alwaysUpdate = true;
        this.body.onCollision = this.onCollision.bind(this);

        this.type = "EnemyBaseEntity";

         this.renderable.addAnimation("idle", [0]);
         this.renderable.addAnimation("broken", [1]);
         this.renderable.setCurrentAnimation("idle");
    },

    update:function(){
      if(this.health<=0){
          this.broken = true;
          this.renderable.setCurrentAnimation("broken");
      }
      this.body.update(delta);

      this._super(me.Entity, "update", [delta]);
      return true;
    },

    onCollision: function(){

    }

});<|endoftext|>


<commit_before>/*var gulp = require('gulp');
gulp.task('default',function(){
  console.log('Hello Gulp!');
});*/

var tslint = require('gulp-tslint');
gulp.task('lint',function(){
  return gulp.src(['./source/ts/**/**.ts','./test/**/**.test.ts']).pipe(tslint()).pipe(tslint.report('verbose'));
});

var ts = require('gulp-typescript');
var tsProject = ts.createProject({
  removeComments : true,
  noImplicitAny : true,
  target : 'ES3',
  module : 'commonjs',
  declarationFiles : false
});

gulp.task('tsc',function(){
  return gulp.src('./source/ts/**/**.ts')
    .pipe(ts(tsProject))
    .js.pipe(gulp.dest('./temp/source/js'));
});

var tsTestProject = ts.createProject({
  removeComments : true,
  noImplicitAny : true,
  target : 'ES3',
  module:'commonjs',
  declarationFiles false
});

gulp.task('tsc-test',function(){
  return gulp.src('./test/**/**.test.ts')
    .pipe(ts(tsTestProject))
    .js.pipe(gulp.dest('./temp/test/'));
});

var browserify = require('browserify'),
    transform = require('vinyl-transform'),
    uglify = require('gulp-uglify'),
    sourcemaps = require('gulp-sourcemaps');

var browserified = transform(function(filename){
  var b =browserify({entries: filename,debug: true});
  return b.bundle();
});

gulp.task('bundle-js',function(){
  return gulp.src('./temp/source/js/main.js')
    .pipe(browserified)
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(uglify())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./dist/source/js/'));
});

gulp.task('bundle-test',function(){
  return gulp.src('./temp/test/**/**.test.js')
    .pipe(browserified)
    .pipe(gulp.dest('./dist/test'));
});

var karma = require("gulp-karma");
gulp.task('karma',function(cb){
  gulp.src('./dist/test/**/**.test.js')
    .pipe(karma({
      configFile: 'karma.conf.js',
      action: 'run'
    }))
    .on('end',cb)
    .on('error',function(err){
      throw err;
    });
});

var runSequence = require('run-sequence');
gulp.task('default',function(cb){
  runSequence(
    'lint',
    ['tsc','tsc-tests'],
    ['bundle-js','bundle-test'],
    'karma',
    'browser-sync',
    cb
  );
});

gulp.task('bundle',function(cb){
  runSequence('build',[
    'bundle-js','bundle-test'
  ],cb);
});

gulp.task('test',function(cb){
  runSequence('bundle',['karma'],cb);
});

var browserSync = require('browser-sync');
gulp.task('browser-sync',['test'],function(){
  browserSync({
    server:{
      baseDir:"./dist"
    }
  });
return gulp.watch([
  "./dist/source/js/**/*.js",
  "./dist/source/css/**.css",
  "./dist/test/**/**.test.js",
  "./dist/data/**/**",
  "./index.html"
],[browserSync.reload]);
});

gulp.task('default',['lint','tsc','tsc-tests','bundle-js','bundle-test']);
<commit_msg>gulp edited<commit_after>/*var gulp = require('gulp');
gulp.task('default',function(){
  console.log('Hello Gulp!');
});*/

var tslint = require('gulp-tslint');
gulp.task('lint',function(){
  return gulp.src(['./source/ts/**/**.ts','./test/**/**.test.ts']).pipe(tslint()).pipe(tslint.report('verbose'));
});

var ts = require('gulp-typescript');
var tsProject = ts.createProject({
  removeComments : true,
  noImplicitAny : true,
  target : 'ES3',
  module : 'commonjs',
  declarationFiles : false
});

gulp.task('tsc',function(){
  return gulp.src('./source/ts/**/**.ts')
    .pipe(ts(tsProject))
    .js.pipe(gulp.dest('./temp/source/js'));
});

var tsTestProject = ts.createProject({
  removeComments : true,
  noImplicitAny : true,
  target : 'ES3',
  module:'commonjs',
  declarationFiles false
});

gulp.task('tsc-test',function(){
  return gulp.src('./test/**/**.test.ts')
    .pipe(ts(tsTestProject))
    .js.pipe(gulp.dest('./temp/test/'));
});

var browserify = require('browserify'),
    transform = require('vinyl-transform'),
    uglify = require('gulp-uglify'),
    sourcemaps = require('gulp-sourcemaps');

var browserified = transform(function(filename){
  var b =browserify({entries: filename,debug: true});
  return b.bundle();
});

gulp.task('bundle-js',function(){
  return gulp.src('./temp/source/js/main.js')
    .pipe(browserified)
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(uglify())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./dist/source/js/'));
});

gulp.task('bundle-test',function(){
  return gulp.src('./temp/test/**/**.test.js')
    .pipe(browserified)
    .pipe(gulp.dest('./dist/test'));
});

var karma = require("gulp-karma");
gulp.task('karma',function(cb){
  gulp.src('./dist/test/**/**.test.js')
    .pipe(karma({
      configFile: 'karma.conf.js',
      action: 'run'
    }))
    .on('end',cb)
    .on('error',function(err){
      throw err;
    });
});

var runSequence = require('run-sequence');
gulp.task('default',function(cb){
  runSequence(
    'lint',
    ['tsc','tsc-tests'],
    ['bundle-js','bundle-test'],
    'karma',
    'browser-sync',
    cb
  );
});

gulp.task('bundle',function(cb){
  runSequence('build',[
    'bundle-js','bundle-test'
  ],cb);
});

gulp.task('test',function(cb){
  runSequence('bundle',['karma'],cb);
});

var browserSync = require('browser-sync');
gulp.task('browser-sync',['test'],function(){
  browserSync({
    server:{
      baseDir:"./dist"
    }
  });
return gulp.watch([
  "./dist/source/js/**/*.js",
  "./dist/source/css/**.css",
  "./dist/test/**/**.test.js",
  "./dist/data/**/**",
  "./index.html"
],[browserSync.reload]);

});

gulp.task('default',['lint','tsc','tsc-tests','bundle-js','bundle-test']);
<|endoftext|>


<commit_before>game.PlayerEntity = me.Entity.extend({
    init: function(x, y, settings) {
        this._super(me.Entity, 'init', [x, y, {
                image: "player",
                width: 64,
                height: 62,
                spritewidth: "64",
                spriteheight: "64",
                getShape: function() {
                    return(new me.Rect(0, 0, 64, 64)).toPolygon();
                }
            }]);

        this.body.setVelocity(5, 20);
        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

        this.renderable.addAnimation("idle", [78]);
        this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
        this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);

        this.renderable.setCurrentAnimation("idle")
    },
    update: function(delta) {
        if (me.input.isKeyPressed("right")) {
            //sets the position of my x by adding the velocity defined above in
            //setVelocity()and multiplying it be me.timer.tick
            //me.timer.tick makes the movement look move
            this.body.vel.x += this.body.accel.x * me.timer.tick;
            this.flipX(true);

        }
        else if(me.input.isKeyPressed("left")){
            this.body.vel.x -=this.body.accel.x * me.timer.tick;
            this.flipX(false);
        }else{
            this.body.vel.x = 0;
        }

        if(me.input.isKeyPressed("jump")  && !this.jumping && !this.falling){
           this.jumping = true;
           this.body.vel.y -= this.accel.y * me.timer.tick;
        }

        if (me.input.isKeyPressed("attack")) {
            if (!this.renderable.isCurrentAnimation("attack")) {

                //sets the current animation to attack and when its over
                //goes back to current animation
                this.renderable.setCurrentAnimation("attack");
                //makes it so that the next time we start this sequence we begin
                //from the first animation, not wherever we left off to another animation
                this.renderable.setAnimationFrame();
            }
        }
        else if (this.body.vel.x !== 0) {
            if (!this.renderable.isCurrentAnimation("walk")) {
                this.renderable.setCurrentAnimation("walk");
            }
        }
        else {
            this.renderable.setCurrentAnimation("idle");
        }

        this.body.update(delta);

        this._super(me.Entity, "update", [delta]);
        return true;
    }
});

game.PlayerBaseEntity = me.Entity.extend({
    init: function(x, y, settings) {
        this._super(me.Entity, 'init', [x, y, {
                image: "tower",
                width: 100,
                height: 100,
                spritewidth: "100",
                spriteheight: "100",
                getShape: function() {
                    return (new me.Rect(0, 0, 100, 80)).toPolygon();
                }
            }]);
        this.broken = false;
        this.health = 10;
        this.alwaysUpdate = true;
        this.body.onCollision = this.onCollision.bind(this)

        this.type = "PlayerBaseEntity";

        this.renderable.addAnimation("idle", [0]);
        this.renderable.addAnimation("broken", [1]);
        this.renderable.setCurrentAnimation("idle");
    },
    update: function(delta) {
        if (this.health <= 0) {
            this.broken = true;
            this.renderable.setCurrentAnimation("broken")
        }
        this.body.update(delta);

        this._super(me.Entity, "update", [delta]);
        return true;
    },
    onCollision: function() {

    }

});

game.EnemyBaseEntity = me.Entity.extend({
    init: function(x, y, settings) {
        this._super(me.Entity, 'init', [x, y, {
                image: "tower",
                width: 100,
                height: 100,
                spritewidth: "100",
                spriteheight: "100",
                getShape: function() {
                    return (new me.Rect(0, 0, 100, 85)).toPolygon();
                }
            }]);
        this.broken = false;
        this.health = 10;
        this.alwaysUpdate = true;
        this.body.onCollision = this.onCollision.bind(this)

        this.type = "EnemyBaseEntity";

        this.renderable.addAnimation("idle", [0]);
        this.renderable.addAnimation("broken", [1]);
        this.renderable.setCurrentAnimation("idle");
    },
    update: function(delta) {
        if (this.health <= 0) {
            this.broken = true;
            this.renderable.setCurrentAnimation("broken");
            t
        }
        this.body.update(delta);

        this._super(me.Entity, "update", [delta]);
        return true;
    },
    onCollision: function() {

    }

});<commit_msg>made my player jump one time a load<commit_after>game.PlayerEntity = me.Entity.extend({
    init: function(x, y, settings) {
        this._super(me.Entity, 'init', [x, y, {
                image: "player",
                width: 64,
                height: 62,
                spritewidth: "64",
                spriteheight: "64",
                getShape: function() {
                    return(new me.Rect(0, 0, 64, 64)).toPolygon();
                }
            }]);

        this.body.setVelocity(5, 20);
        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

        this.renderable.addAnimation("idle", [78]);
        this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80);
        this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80);

        this.renderable.setCurrentAnimation("idle")
    },
    update: function(delta) {
        if (me.input.isKeyPressed("right")) {
            //sets the position of my x by adding the velocity defined above in
            //setVelocity()and multiplying it be me.timer.tick
            //me.timer.tick makes the movement look move
            this.body.vel.x += this.body.accel.x * me.timer.tick;
            this.flipX(true);

        }
        else if(me.input.isKeyPressed("left")){
            this.body.vel.x -=this.body.accel.x * me.timer.tick;
            this.flipX(false);
        }else{
            this.body.vel.x = 0;
        }

        if(me.input.isKeyPressed("jump")  && !this.jumping && !this.falling){
           this.jumping = true;
           this.body.vel.y -= this.body.accel.y * me.timer.tick;
        }

        if (me.input.isKeyPressed("attack")) {
            if (!this.renderable.isCurrentAnimation("attack")) {

                //sets the current animation to attack and when its over
                //goes back to current animation
                this.renderable.setCurrentAnimation("attack");
                //makes it so that the next time we start this sequence we begin
                //from the first animation, not wherever we left off to another animation
                this.renderable.setAnimationFrame();
            }
        }
        else if (this.body.vel.x !== 0) {
            if (!this.renderable.isCurrentAnimation("walk")) {
                this.renderable.setCurrentAnimation("walk");
            }
        }
        else {
            this.renderable.setCurrentAnimation("idle");
        }

        this.body.update(delta);

        this._super(me.Entity, "update", [delta]);
        return true;
    }
});

game.PlayerBaseEntity = me.Entity.extend({
    init: function(x, y, settings) {
        this._super(me.Entity, 'init', [x, y, {
                image: "tower",
                width: 100,
                height: 100,
                spritewidth: "100",
                spriteheight: "100",
                getShape: function() {
                    return (new me.Rect(0, 0, 100, 80)).toPolygon();
                }
            }]);
        this.broken = false;
        this.health = 10;
        this.alwaysUpdate = true;
        this.body.onCollision = this.onCollision.bind(this)

        this.type = "PlayerBaseEntity";

        this.renderable.addAnimation("idle", [0]);
        this.renderable.addAnimation("broken", [1]);
        this.renderable.setCurrentAnimation("idle");
    },
    update: function(delta) {
        if (this.health <= 0) {
            this.broken = true;
            this.renderable.setCurrentAnimation("broken")
        }
        this.body.update(delta);

        this._super(me.Entity, "update", [delta]);
        return true;
    },
    onCollision: function() {

    }

});

game.EnemyBaseEntity = me.Entity.extend({
    init: function(x, y, settings) {
        this._super(me.Entity, 'init', [x, y, {
                image: "tower",
                width: 100,
                height: 100,
                spritewidth: "100",
                spriteheight: "100",
                getShape: function() {
                    return (new me.Rect(0, 0, 100, 85)).toPolygon();
                }
            }]);
        this.broken = false;
        this.health = 10;
        this.alwaysUpdate = true;
        this.body.onCollision = this.onCollision.bind(this)

        this.type = "EnemyBaseEntity";

        this.renderable.addAnimation("idle", [0]);
        this.renderable.addAnimation("broken", [1]);
        this.renderable.setCurrentAnimation("idle");
    },
    update: function(delta) {
        if (this.health <= 0) {
            this.broken = true;
            this.renderable.setCurrentAnimation("broken");
            t
        }
        this.body.update(delta);

        this._super(me.Entity, "update", [delta]);
        return true;
    },
    onCollision: function() {

    }

});<|endoftext|>


<commit_before>var gulp = require('gulp');
var mocha = require('gulp-mocha');

gulp.task('default', ['test']);

gulp.task('test', function(){
  var reporter = 'dot'; // nyan
  return gulp.src('*/*.js', {read: false})
    .pipe(mocha({reporter: reporter, growl: true}));
});

gulp.task('watch', function(){
  gulp.start('test');
  // TODO: Negeate test/data/tmp/
  gulp.watch('**/*.js', ['test']);
});
<commit_msg>fix gulp file<commit_after>var gulp = require('gulp');
var mocha = require('gulp-mocha');

gulp.task('default', ['test']);

gulp.task('test', function(){
  var reporter = 'dot'; // nyan
  return gulp.src('test/*.js', {read: false})
    .pipe(mocha({reporter: reporter, growl: true}));
});

gulp.task('watch', function(){
  gulp.start('test');
  // TODO: Negeate test/data/tmp/
  gulp.watch('**/*.js', ['test']);
});
<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 University of California San Diego
 * Author: Jim Robinson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

import {numberFormatter} from "../util/stringUtils.js"

/**
 * Created by jrobinson on 4/7/16.
 */

const transcriptTypes = new Set(['transcript', 'primary_transcript', 'processed_transcript', 'mRNA', 'mrna']);
const cdsTypes = new Set(['CDS', 'cds']);
const codonTypes = new Set(['start_codon', 'stop_codon']);
const utrTypes = new Set(['5UTR', '3UTR', 'UTR', 'five_prime_UTR', 'three_prime_UTR', "3'-UTR", "5'-UTR"]);
const exonTypes = new Set(['exon', 'coding-exon']);
const intronType = 'intron';
const DEFAULT_NAME_FIELDS = ["name", "alias", "id", "gene", "locus", "gene_name"];   // lowercased, from IGV desktop
const transcriptModelTypes = new Set();
for (let cltn of [transcriptTypes, cdsTypes, codonTypes, utrTypes, exonTypes]) {
    for (let t of cltn) {
        transcriptModelTypes.add(t);
    }
}

class GFFHelper {
    constructor(options) {
        this.format = options.format;
        if (options.filterTypes) {
            this.filterTypes = new Set(options.filterTypes)
        }
    }

    combineFeatures(features) {
        let combinedFeatures;
        if ("gff3" === this.format) {
            const tmp = this.combineFeaturesById(features);
            combinedFeatures = this.combineFeaturesGFF(tmp);
        } else {
            combinedFeatures = this.combineFeaturesGTF(features);
        }
        combinedFeatures.sort(function (a, b) {
            return a.start - b.start;
        })
        return combinedFeatures;
    }

    combineFeaturesById(features) {
        const combinedFeatures = [];
        const chrIdHash = {};
        for (let f of features) {
            if (f.id === undefined) {
                combinedFeatures.push(f);
            } else {
                let idHash = chrIdHash[f.chr];
                if (!idHash) {
                    idHash = {};
                    chrIdHash[f.chr] = idHash;
                }
                if (idHash.hasOwnProperty(f.id)) {
                    const sf = idHash[f.id];
                    if (sf.hasOwnProperty("exons")) {
                        sf.start = Math.min(sf.start, f.start);
                        sf.end = Math.max(sf.end, f.end);
                        sf.exons.push(f);
                    } else {
                        const cf = {
                            id: f.id,
                            type: f.type,
                            chr: f.chr,
                            strand: f.strand,
                            start: Math.min(f.start, sf.start),
                            end: Math.max(f.end, sf.end),
                            exons: [sf, f]
                        };
                        if (f.parent && f.parent.trim() !== "") {
                            cf.parent = f.parent;
                        }
                        idHash[f.id] = cf;
                    }
                } else {
                    idHash[f.id] = f;
                }
            }
        }
        for (let key of Object.keys(chrIdHash)) {
            const idHash = chrIdHash[key];
            for (let id of Object.keys(idHash)) {
                combinedFeatures.push(idHash[id])
            }
        }
        return combinedFeatures;
    }

    combineFeaturesGTF(features) {

        const transcripts = Object.create(null)
        const combinedFeatures = []
        const consumedFeatures = new Set();
        const filterTypes = this.filterTypes;

        features = features.filter(f => filterTypes === undefined || !filterTypes.has(f.type))

        // 1. Build dictionary of transcripts
        for (let f of features) {
            if (transcriptTypes.has(f.type)) {
                const transcriptId = f.id
                if (undefined !== transcriptId) {
                    const gffTranscript = new GFFTranscript(f);
                    transcripts[transcriptId] = gffTranscript;
                    combinedFeatures.push(gffTranscript);
                    consumedFeatures.add(f)
                }
            }
        }

        // Add exons
        for (let f of features) {
            if (exonTypes.has(f.type)) {
                const id = f.id;   // transcript_id,  GTF groups all features with the same ID, does not have a parent/child hierarchy
                if (id) {
                    let transcript = transcripts[id];
                    if (transcript === undefined) {
                        transcript = new GFFTranscript(f);    // GTF does not require an explicit transcript record
                        transcripts[id] = transcript;
                        combinedFeatures.push(transcript);
                    }
                    transcript.addExon(f);
                    consumedFeatures.add(f)
                }
            }
        }

        // Apply CDS and UTR
        for (let f of features) {
            if (cdsTypes.has(f.type) || utrTypes.has(f.type) || codonTypes.has(f.type)) {
                const id = f.id;
                if (id) {
                    let transcript = transcripts[id];
                    if (transcript === undefined) {
                        transcript = new GFFTranscript(f);
                        transcripts[id] = transcript;
                        combinedFeatures.push(transcript);
                    }
                    if (utrTypes.has(f.type)) {
                        transcript.addUTR(f);
                    } else if (cdsTypes.has(f.type)) {
                        transcript.addCDS(f);
                    } else if (codonTypes.has(f.type)) {
                        // Ignore for now
                    }
                    consumedFeatures.add(f)
                }
            }
        }

        // Finish transcripts
        for (let f of combinedFeatures) {
            if (typeof f.finish === "function") {
                f.finish();
            }
        }

        // Add other features
        const others = features.filter(f => !consumedFeatures.has(f))
        for (let f of others) {
            combinedFeatures.push(f);
        }

        return combinedFeatures;

    }

    combineFeaturesGFF(features) {

        // Build dictionary of genes (optional)
        const genes = features.filter(f => "gene" === f.type);
        const geneMap = Object.create(null);
        for (let g of genes) {
            geneMap[g.id] = g;
        }

        // 1. Build dictionary of transcripts
        const transcripts = Object.create(null)
        const combinedFeatures = []
        const consumedFeatures = new Set();
        const filterTypes = this.filterTypes;

        features = features.filter(f => filterTypes === undefined || !filterTypes.has(f.type))

        for (let f of features) {
            if (transcriptTypes.has(f.type)) {
                const transcriptId = f.id; // getAttribute(f.attributeString, "transcript_id", /\s+/);
                if (undefined !== transcriptId) {
                    const gffTranscript = new GFFTranscript(f);
                    transcripts[transcriptId] = gffTranscript;
                    combinedFeatures.push(gffTranscript);
                    consumedFeatures.add(f);
                    gffTranscript.gene = geneMap[f.parent];
                }
            }
        }

        // Add exons
        for (let f of features) {
            if (exonTypes.has(f.type)) {
                const parents = getParents(f);
                if (parents) {
                    for (let id of parents) {
                        let transcript = transcripts[id];
                        if (transcript !== undefined) {
                            transcript.addExon(f);
                            consumedFeatures.add(f)
                        }
                    }
                }
            }
        }

        // Apply CDS and UTR
        for (let f of features) {
            if (cdsTypes.has(f.type) || utrTypes.has(f.type) || codonTypes.has(f.type)) {
                const parents = getParents(f);
                if (parents) {
                    for (let id of parents) {
                        let transcript = transcripts[id];
                        if (transcript !== undefined) {
                            if (utrTypes.has(f.type)) {
                                transcript.addUTR(f);
                            } else if (cdsTypes.has(f.type)) {
                                transcript.addCDS(f);
                            } else if (codonTypes.has(f.type)) {
                                // Ignore for now
                            }
                            consumedFeatures.add(f);
                        }
                    }
                }
            }
        }

        // Introns are ignored, but are consumed
        const introns = features.filter(f => intronType === f.type);
        for (let i of introns) {
            const parents = getParents(i);
            for (let id of parents) {
                if (transcripts[id]) {
                    consumedFeatures.add(i);
                    break;
                }
            }
        }

        // Finish transcripts
        combinedFeatures.forEach(function (f) {
            if (typeof f.finish === "function") {
                f.finish();
            }
        })

        // Add other features
        const others = features.filter(f => !consumedFeatures.has(f))
        for (let f of others) {
            combinedFeatures.push(f);
        }

        return combinedFeatures;

        function getParents(f) {
            if (f.parent && f.parent.trim() !== "") {
                return f.parent.trim().split(",");
            } else {
                return null;
            }
        }
    }
}

var GFFTranscript = function (feature) {
    Object.assign(this, feature);
    this.exons = [];
}

GFFTranscript.prototype.addExon = function (feature) {

    this.exons.push(feature)

    // Expand feature --  for transcripts not explicitly represented in the file
    this.start = Math.min(this.start, feature.start);
    this.end = Math.max(this.end, feature.end);
}

GFFTranscript.prototype.addCDS = function (cds) {

    let exon
    const exons = this.exons;

    // Find exon containing CDS
    for (let i = 0; i < exons.length; i++) {
        if (exons[i].start <= cds.start && exons[i].end >= cds.end) {
            exon = exons[i];
            break;
        }
    }

    if (exon) {
        exon.cdStart = exon.cdStart ? Math.min(cds.start, exon.cdStart) : cds.start;
        exon.cdEnd = exon.cdEnd ? Math.max(cds.end, exon.cdEnd) : cds.end;
        if (!exon.children) {
            exon.children = []
        }
        exon.children.push(cds)
    } else {
        cds.cdStart = cds.start
        cds.cdEnd = cds.end
        exons.push(cds)
    }

    // Expand feature --  for transcripts not explicitly represented in the file (gtf files)
    this.start = Math.min(this.start, cds.start);
    this.end = Math.max(this.end, cds.end);

    this.cdStart = this.cdStart ? Math.min(cds.start, this.cdStart) : cds.start;
    this.cdEnd = this.cdEnd ? Math.max(cds.end, this.cdEnd) : cds.end;
}

GFFTranscript.prototype.addUTR = function (utr) {

    let exon
    const exons = this.exons;

    // Find exon containing CDS
    for (let i = 0; i < exons.length; i++) {
        if (exons[i].start <= utr.start && exons[i].end >= utr.end) {
            exon = exons[i];
            break;
        }
    }

    if (exon) {
        if (utr.start === exon.start && utr.end === exon.end) {
            exon.utr = true;
        } else {
            if (utr.end < exon.end) {
                exon.cdStart = utr.end
            }
            if (utr.start > exon.start) {
                exon.cdEnd = utr.start
            }
        }
        if (!exon.children) {
            exon.children = []
        }
        exon.children.push(utr)

    } else {
        utr.utr = true
        exons.push(utr)
    }

    // Expand feature --  for transcripts not explicitly represented in the file
    this.start = Math.min(this.start, utr.start);
    this.end = Math.max(this.end, utr.end);

}

GFFTranscript.prototype.finish = function () {

    var cdStart = this.cdStart;
    var cdEnd = this.cdEnd;

    this.exons.sort(function (a, b) {
        return a.start - b.start;
    })

    // Search for UTR exons that were not explicitly tagged
    if (cdStart) {
        this.exons.forEach(function (exon) {
            if (exon.end < cdStart || exon.start > cdEnd) exon.utr = true;
        });
    }
}

GFFTranscript.prototype.popupData = function (genomicLocation) {

    const kvs = this.attributeString.split(';')
    const pd = []

    // If feature has an associated gene list its attributes first
    if (this.gene && typeof this.gene.popupData === 'function') {
        const gd = this.gene.popupData(genomicLocation);
        for (let e of gd) {
            pd.push(e);
        }
        pd.push("
");
    }
    if (this.name) {
        pd.push({name: 'name', value: this.name})
    }
    pd.push({name: 'type', value: this.type})
    for (let kv of kvs) {
        var t = kv.trim().split(this.delim, 2);
        if (t.length === 2 && t[1] !== undefined) {
            const key = t[0].trim();
            if ('name' === key.toLowerCase()) continue;
            let value = t[1].trim();
            //Strip off quotes, if any
            if (value.startsWith('"') && value.endsWith('"')) {
                value = value.substr(1, value.length - 2);
            }
            pd.push({name: key, value: value});
        }
    }
    pd.push({name: 'position', value: `${this.chr}:${numberFormatter(this.start + 1)}-${numberFormatter(this.end)}`})

    // If clicked over an exon add its attributes
    for (let exon of this.exons) {
        if (genomicLocation >= exon.start && genomicLocation < exon.end) {
            pd.push("
")
            const exonData = exon.popupData(genomicLocation)
            for (let att of exonData) {
                pd.push(att)
            }

            if (exon.children) {
                for (let c of exon.children) {
                    pd.push("
")
                    const exonData = c.popupData(genomicLocation)
                    for (let att of exonData) {
                        pd.push(att)
                    }
                }
            }
        }
    }

    return pd;
}

export default GFFHelper;
<commit_msg>null check for exon popup data<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 University of California San Diego
 * Author: Jim Robinson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

import {numberFormatter} from "../util/stringUtils.js"

/**
 * Created by jrobinson on 4/7/16.
 */

const transcriptTypes = new Set(['transcript', 'primary_transcript', 'processed_transcript', 'mRNA', 'mrna']);
const cdsTypes = new Set(['CDS', 'cds']);
const codonTypes = new Set(['start_codon', 'stop_codon']);
const utrTypes = new Set(['5UTR', '3UTR', 'UTR', 'five_prime_UTR', 'three_prime_UTR', "3'-UTR", "5'-UTR"]);
const exonTypes = new Set(['exon', 'coding-exon']);
const intronType = 'intron';
const DEFAULT_NAME_FIELDS = ["name", "alias", "id", "gene", "locus", "gene_name"];   // lowercased, from IGV desktop
const transcriptModelTypes = new Set();
for (let cltn of [transcriptTypes, cdsTypes, codonTypes, utrTypes, exonTypes]) {
    for (let t of cltn) {
        transcriptModelTypes.add(t);
    }
}

class GFFHelper {
    constructor(options) {
        this.format = options.format;
        if (options.filterTypes) {
            this.filterTypes = new Set(options.filterTypes)
        }
    }

    combineFeatures(features) {
        let combinedFeatures;
        if ("gff3" === this.format) {
            const tmp = this.combineFeaturesById(features);
            combinedFeatures = this.combineFeaturesGFF(tmp);
        } else {
            combinedFeatures = this.combineFeaturesGTF(features);
        }
        combinedFeatures.sort(function (a, b) {
            return a.start - b.start;
        })
        return combinedFeatures;
    }

    combineFeaturesById(features) {
        const combinedFeatures = [];
        const chrIdHash = {};
        for (let f of features) {
            if (f.id === undefined) {
                combinedFeatures.push(f);
            } else {
                let idHash = chrIdHash[f.chr];
                if (!idHash) {
                    idHash = {};
                    chrIdHash[f.chr] = idHash;
                }
                if (idHash.hasOwnProperty(f.id)) {
                    const sf = idHash[f.id];
                    if (sf.hasOwnProperty("exons")) {
                        sf.start = Math.min(sf.start, f.start);
                        sf.end = Math.max(sf.end, f.end);
                        sf.exons.push(f);
                    } else {
                        const cf = {
                            id: f.id,
                            type: f.type,
                            chr: f.chr,
                            strand: f.strand,
                            start: Math.min(f.start, sf.start),
                            end: Math.max(f.end, sf.end),
                            exons: [sf, f]
                        };
                        if (f.parent && f.parent.trim() !== "") {
                            cf.parent = f.parent;
                        }
                        idHash[f.id] = cf;
                    }
                } else {
                    idHash[f.id] = f;
                }
            }
        }
        for (let key of Object.keys(chrIdHash)) {
            const idHash = chrIdHash[key];
            for (let id of Object.keys(idHash)) {
                combinedFeatures.push(idHash[id])
            }
        }
        return combinedFeatures;
    }

    combineFeaturesGTF(features) {

        const transcripts = Object.create(null)
        const combinedFeatures = []
        const consumedFeatures = new Set();
        const filterTypes = this.filterTypes;

        features = features.filter(f => filterTypes === undefined || !filterTypes.has(f.type))

        // 1. Build dictionary of transcripts
        for (let f of features) {
            if (transcriptTypes.has(f.type)) {
                const transcriptId = f.id
                if (undefined !== transcriptId) {
                    const gffTranscript = new GFFTranscript(f);
                    transcripts[transcriptId] = gffTranscript;
                    combinedFeatures.push(gffTranscript);
                    consumedFeatures.add(f)
                }
            }
        }

        // Add exons
        for (let f of features) {
            if (exonTypes.has(f.type)) {
                const id = f.id;   // transcript_id,  GTF groups all features with the same ID, does not have a parent/child hierarchy
                if (id) {
                    let transcript = transcripts[id];
                    if (transcript === undefined) {
                        transcript = new GFFTranscript(f);    // GTF does not require an explicit transcript record
                        transcripts[id] = transcript;
                        combinedFeatures.push(transcript);
                    }
                    transcript.addExon(f);
                    consumedFeatures.add(f)
                }
            }
        }

        // Apply CDS and UTR
        for (let f of features) {
            if (cdsTypes.has(f.type) || utrTypes.has(f.type) || codonTypes.has(f.type)) {
                const id = f.id;
                if (id) {
                    let transcript = transcripts[id];
                    if (transcript === undefined) {
                        transcript = new GFFTranscript(f);
                        transcripts[id] = transcript;
                        combinedFeatures.push(transcript);
                    }
                    if (utrTypes.has(f.type)) {
                        transcript.addUTR(f);
                    } else if (cdsTypes.has(f.type)) {
                        transcript.addCDS(f);
                    } else if (codonTypes.has(f.type)) {
                        // Ignore for now
                    }
                    consumedFeatures.add(f)
                }
            }
        }

        // Finish transcripts
        for (let f of combinedFeatures) {
            if (typeof f.finish === "function") {
                f.finish();
            }
        }

        // Add other features
        const others = features.filter(f => !consumedFeatures.has(f))
        for (let f of others) {
            combinedFeatures.push(f);
        }

        return combinedFeatures;

    }

    combineFeaturesGFF(features) {

        // Build dictionary of genes (optional)
        const genes = features.filter(f => "gene" === f.type);
        const geneMap = Object.create(null);
        for (let g of genes) {
            geneMap[g.id] = g;
        }

        // 1. Build dictionary of transcripts
        const transcripts = Object.create(null)
        const combinedFeatures = []
        const consumedFeatures = new Set();
        const filterTypes = this.filterTypes;

        features = features.filter(f => filterTypes === undefined || !filterTypes.has(f.type))

        for (let f of features) {
            if (transcriptTypes.has(f.type)) {
                const transcriptId = f.id; // getAttribute(f.attributeString, "transcript_id", /\s+/);
                if (undefined !== transcriptId) {
                    const gffTranscript = new GFFTranscript(f);
                    transcripts[transcriptId] = gffTranscript;
                    combinedFeatures.push(gffTranscript);
                    consumedFeatures.add(f);
                    gffTranscript.gene = geneMap[f.parent];
                }
            }
        }

        // Add exons
        for (let f of features) {
            if (exonTypes.has(f.type)) {
                const parents = getParents(f);
                if (parents) {
                    for (let id of parents) {
                        let transcript = transcripts[id];
                        if (transcript !== undefined) {
                            transcript.addExon(f);
                            consumedFeatures.add(f)
                        }
                    }
                }
            }
        }

        // Apply CDS and UTR
        for (let f of features) {
            if (cdsTypes.has(f.type) || utrTypes.has(f.type) || codonTypes.has(f.type)) {
                const parents = getParents(f);
                if (parents) {
                    for (let id of parents) {
                        let transcript = transcripts[id];
                        if (transcript !== undefined) {
                            if (utrTypes.has(f.type)) {
                                transcript.addUTR(f);
                            } else if (cdsTypes.has(f.type)) {
                                transcript.addCDS(f);
                            } else if (codonTypes.has(f.type)) {
                                // Ignore for now
                            }
                            consumedFeatures.add(f);
                        }
                    }
                }
            }
        }

        // Introns are ignored, but are consumed
        const introns = features.filter(f => intronType === f.type);
        for (let i of introns) {
            const parents = getParents(i);
            for (let id of parents) {
                if (transcripts[id]) {
                    consumedFeatures.add(i);
                    break;
                }
            }
        }

        // Finish transcripts
        combinedFeatures.forEach(function (f) {
            if (typeof f.finish === "function") {
                f.finish();
            }
        })

        // Add other features
        const others = features.filter(f => !consumedFeatures.has(f))
        for (let f of others) {
            combinedFeatures.push(f);
        }

        return combinedFeatures;

        function getParents(f) {
            if (f.parent && f.parent.trim() !== "") {
                return f.parent.trim().split(",");
            } else {
                return null;
            }
        }
    }
}

var GFFTranscript = function (feature) {
    Object.assign(this, feature);
    this.exons = [];
}

GFFTranscript.prototype.addExon = function (feature) {

    this.exons.push(feature)

    // Expand feature --  for transcripts not explicitly represented in the file
    this.start = Math.min(this.start, feature.start);
    this.end = Math.max(this.end, feature.end);
}

GFFTranscript.prototype.addCDS = function (cds) {

    let exon
    const exons = this.exons;

    // Find exon containing CDS
    for (let i = 0; i < exons.length; i++) {
        if (exons[i].start <= cds.start && exons[i].end >= cds.end) {
            exon = exons[i];
            break;
        }
    }

    if (exon) {
        exon.cdStart = exon.cdStart ? Math.min(cds.start, exon.cdStart) : cds.start;
        exon.cdEnd = exon.cdEnd ? Math.max(cds.end, exon.cdEnd) : cds.end;
        if (!exon.children) {
            exon.children = []
        }
        exon.children.push(cds)
    } else {
        cds.cdStart = cds.start
        cds.cdEnd = cds.end
        exons.push(cds)
    }

    // Expand feature --  for transcripts not explicitly represented in the file (gtf files)
    this.start = Math.min(this.start, cds.start);
    this.end = Math.max(this.end, cds.end);

    this.cdStart = this.cdStart ? Math.min(cds.start, this.cdStart) : cds.start;
    this.cdEnd = this.cdEnd ? Math.max(cds.end, this.cdEnd) : cds.end;
}

GFFTranscript.prototype.addUTR = function (utr) {

    let exon
    const exons = this.exons;

    // Find exon containing CDS
    for (let i = 0; i < exons.length; i++) {
        if (exons[i].start <= utr.start && exons[i].end >= utr.end) {
            exon = exons[i];
            break;
        }
    }

    if (exon) {
        if (utr.start === exon.start && utr.end === exon.end) {
            exon.utr = true;
        } else {
            if (utr.end < exon.end) {
                exon.cdStart = utr.end
            }
            if (utr.start > exon.start) {
                exon.cdEnd = utr.start
            }
        }
        if (!exon.children) {
            exon.children = []
        }
        exon.children.push(utr)

    } else {
        utr.utr = true
        exons.push(utr)
    }

    // Expand feature --  for transcripts not explicitly represented in the file
    this.start = Math.min(this.start, utr.start);
    this.end = Math.max(this.end, utr.end);

}

GFFTranscript.prototype.finish = function () {

    var cdStart = this.cdStart;
    var cdEnd = this.cdEnd;

    this.exons.sort(function (a, b) {
        return a.start - b.start;
    })

    // Search for UTR exons that were not explicitly tagged
    if (cdStart) {
        this.exons.forEach(function (exon) {
            if (exon.end < cdStart || exon.start > cdEnd) exon.utr = true;
        });
    }
}

GFFTranscript.prototype.popupData = function (genomicLocation) {

    const kvs = this.attributeString.split(';')
    const pd = []

    // If feature has an associated gene list its attributes first
    if (this.gene && typeof this.gene.popupData === 'function') {
        const gd = this.gene.popupData(genomicLocation);
        for (let e of gd) {
            pd.push(e);
        }
        pd.push("
");
    }
    if (this.name) {
        pd.push({name: 'name', value: this.name})
    }
    pd.push({name: 'type', value: this.type})
    for (let kv of kvs) {
        var t = kv.trim().split(this.delim, 2);
        if (t.length === 2 && t[1] !== undefined) {
            const key = t[0].trim();
            if ('name' === key.toLowerCase()) continue;
            let value = t[1].trim();
            //Strip off quotes, if any
            if (value.startsWith('"') && value.endsWith('"')) {
                value = value.substr(1, value.length - 2);
            }
            pd.push({name: key, value: value});
        }
    }
    pd.push({name: 'position', value: `${this.chr}:${numberFormatter(this.start + 1)}-${numberFormatter(this.end)}`})

    // If clicked over an exon add its attributes
    for (let exon of this.exons) {
        if (genomicLocation >= exon.start && genomicLocation < exon.end && typeof exon.popupData === 'function') {
            pd.push("
")
            const exonData = exon.popupData(genomicLocation)
            for (let att of exonData) {
                pd.push(att)
            }

            if (exon.children) {
                for (let c of exon.children) {
                    pd.push("
")
                    const exonData = c.popupData(genomicLocation)
                    for (let att of exonData) {
                        pd.push(att)
                    }
                }
            }
        }
    }

    return pd;
}

export default GFFHelper;
<|endoftext|>


<commit_before>var createcommonjs = require('./gulp-tools/create-common');
var createtestjs = require('./gulp-tools/create-test');
var filecount = require('./gulp-tools/filecount');
var run = require('gulp-run');
var gulp = require('gulp');
var mainstyle = require('./gulp-tools/mainstyle');
var checkdependencies = require('./gulp-tools/check-dependencies');
var manifest = require('gulp-manifest');
var template = require('./gulp-tools/template');
var libs = require('./gulp-tools/libs');
var buildstyle = require('./gulp-tools/buildstyle');
var multiprocess = require('gulp-multi-process');

var sources = {
  styles: ['lib/*.css', 'style/**/*.css', '!style/mainstyle.css'],
  scripts_and_tests: ['scripts/*/*.js', '!scripts/core/{common,config,main}.js'],
  scripts: ['scripts/*/*.js', '!scripts/core/{common,config,main}.js', '!**/test/*.js'],
  dependant_scripts: [
    'scripts/*/*.js',
    '{basic,boule,tac,test}/scripts/{presets,options,strings}.js',
    'scripts/**/test/*.js',
    '!scripts/core/{common,config,main}.js',
    '!**/lib/*.js'
  ],
  tests: ['scripts/**/test/*.js'],
  templates: 'templates/**/*.html',
  template_path: 'templates'
};

gulp.task('default', ['lib', 'update', 'build', 'test']);
gulp.task('update', ['update-mainstyle', 'update-common-js', 'update-test-js', 'template']);
gulp.task('template', ['template-basic', 'template-boule', 'template-tac']);
gulp.task('build', ['build-static', 'build-boule', 'build-basic', 'build-tac']);
gulp.task('test', ['libs'], function () {
  return run('npm test').exec();
})

gulp.task('lib', libs());

gulp.task('build-static', ['build-static-images', 'build-static-html', 'build-static-manifest']);

gulp.task('build-static-html', function () {
  return gulp.src('index.html')
    .pipe(filecount())
    .pipe(gulp.dest('build/'));
});

gulp.task('build-static-images', function () {
  return gulp.src('images/*.png')
    .pipe(filecount())
    .pipe(gulp.dest('build/images/'));
});

gulp.task('build-static-manifest', function () {
  return gulp.src(['index.html', 'images/*.png'], { base: './' })
    .pipe(filecount())
    .pipe(manifest({ filename: 'manifest.appcache', timestamp: false, hash: true }))
    .pipe(filecount())
    .pipe(gulp.dest('build/'));
});

gulp.task('build-basic', ['template', 'build-basic-style']);
gulp.task('build-boule', ['template', 'build-boule-style']);
gulp.task('build-tac', ['template', 'build-tac-style']);

gulp.task('build-basic-style-internal', buildstyle('basic'));
gulp.task('build-boule-style-internal', buildstyle('boule'));
gulp.task('build-tac-style-internal', buildstyle('tac'));

gulp.task('build-basic-style', ['update-mainstyle'], function (cb) {
  return multiprocess(['build-basic-style-internal'], cb);
});
gulp.task('build-boule-style', ['update-mainstyle'], function (cb) {
  return multiprocess(['build-boule-style-internal'], cb);
});
gulp.task('build-tac-style', ['update-mainstyle'], function (cb) {
  return multiprocess(['build-tac-style-internal'], cb);
});

gulp.task('check-dependencies', function () {
  return gulp.src(sources.dependant_scripts, { base: 'scripts' })
    .pipe(filecount())
    .pipe(checkdependencies());
});

/**
 * update
 **/
gulp.task('update-mainstyle', ['lib-normalize'], function () {
  return gulp.src(sources.styles, { base: 'style/' })
    .pipe(filecount())
    .pipe(mainstyle())
    .pipe(filecount())
    .pipe(gulp.dest('style'));
});

gulp.task('update-common-js', [], function () {
  return gulp.src(sources.scripts, { base: 'scripts/' })
    .pipe(filecount())
    .pipe(createcommonjs())
    .pipe(gulp.dest('scripts/core'));
});

gulp.task('update-test-js', [], function () {
  return gulp.src(sources.tests, { base: 'scripts/' })
    .pipe(filecount())
    .pipe(createtestjs())
    .pipe(gulp.dest('test/scripts'));
});

gulp.task('template-basic', template('basic', sources.template_path));
gulp.task('template-boule', template('boule', sources.template_path));
gulp.task('template-tac', template('tac', sources.template_path));

gulp.task('watch', function () {
  gulp.watch(sources.scripts, ['update-common-js']);
  gulp.watch(sources.scripts_and_tests, ['test']);
  gulp.watch(sources.dependant_scripts, ['check-dependencies']);
  gulp.watch(sources.styles, ['update-mainstyle']);
  gulp.watch(sources.templates, ['template']);
  gulp.watch(sources.tests, ['update-test-js']);
});
<commit_msg>Gulp libs-lib typo fixed<commit_after>var createcommonjs = require('./gulp-tools/create-common');
var createtestjs = require('./gulp-tools/create-test');
var filecount = require('./gulp-tools/filecount');
var run = require('gulp-run');
var gulp = require('gulp');
var mainstyle = require('./gulp-tools/mainstyle');
var checkdependencies = require('./gulp-tools/check-dependencies');
var manifest = require('gulp-manifest');
var template = require('./gulp-tools/template');
var libs = require('./gulp-tools/libs');
var buildstyle = require('./gulp-tools/buildstyle');
var multiprocess = require('gulp-multi-process');

var sources = {
  styles: ['lib/*.css', 'style/**/*.css', '!style/mainstyle.css'],
  scripts_and_tests: ['scripts/*/*.js', '!scripts/core/{common,config,main}.js'],
  scripts: ['scripts/*/*.js', '!scripts/core/{common,config,main}.js', '!**/test/*.js'],
  dependant_scripts: [
    'scripts/*/*.js',
    '{basic,boule,tac,test}/scripts/{presets,options,strings}.js',
    'scripts/**/test/*.js',
    '!scripts/core/{common,config,main}.js',
    '!**/lib/*.js'
  ],
  tests: ['scripts/**/test/*.js'],
  templates: 'templates/**/*.html',
  template_path: 'templates'
};

gulp.task('default', ['lib', 'update', 'build', 'test']);
gulp.task('update', ['update-mainstyle', 'update-common-js', 'update-test-js', 'template']);
gulp.task('template', ['template-basic', 'template-boule', 'template-tac']);
gulp.task('build', ['build-static', 'build-boule', 'build-basic', 'build-tac']);
gulp.task('test', ['lib'], function () {
  return run('node cli/test.js').exec();
})

gulp.task('lib', libs());

gulp.task('build-static', ['build-static-images', 'build-static-html', 'build-static-manifest']);

gulp.task('build-static-html', function () {
  return gulp.src('index.html')
    .pipe(filecount())
    .pipe(gulp.dest('build/'));
});

gulp.task('build-static-images', function () {
  return gulp.src('images/*.png')
    .pipe(filecount())
    .pipe(gulp.dest('build/images/'));
});

gulp.task('build-static-manifest', function () {
  return gulp.src(['index.html', 'images/*.png'], { base: './' })
    .pipe(filecount())
    .pipe(manifest({ filename: 'manifest.appcache', timestamp: false, hash: true }))
    .pipe(filecount())
    .pipe(gulp.dest('build/'));
});

gulp.task('build-basic', ['template', 'build-basic-style']);
gulp.task('build-boule', ['template', 'build-boule-style']);
gulp.task('build-tac', ['template', 'build-tac-style']);

gulp.task('build-basic-style-internal', buildstyle('basic'));
gulp.task('build-boule-style-internal', buildstyle('boule'));
gulp.task('build-tac-style-internal', buildstyle('tac'));

gulp.task('build-basic-style', ['update-mainstyle'], function (cb) {
  return multiprocess(['build-basic-style-internal'], cb);
});
gulp.task('build-boule-style', ['update-mainstyle'], function (cb) {
  return multiprocess(['build-boule-style-internal'], cb);
});
gulp.task('build-tac-style', ['update-mainstyle'], function (cb) {
  return multiprocess(['build-tac-style-internal'], cb);
});

gulp.task('check-dependencies', function () {
  return gulp.src(sources.dependant_scripts, { base: 'scripts' })
    .pipe(filecount())
    .pipe(checkdependencies());
});

/**
 * update
 **/
gulp.task('update-mainstyle', ['lib-normalize'], function () {
  return gulp.src(sources.styles, { base: 'style/' })
    .pipe(filecount())
    .pipe(mainstyle())
    .pipe(filecount())
    .pipe(gulp.dest('style'));
});

gulp.task('update-common-js', [], function () {
  return gulp.src(sources.scripts, { base: 'scripts/' })
    .pipe(filecount())
    .pipe(createcommonjs())
    .pipe(gulp.dest('scripts/core'));
});

gulp.task('update-test-js', [], function () {
  return gulp.src(sources.tests, { base: 'scripts/' })
    .pipe(filecount())
    .pipe(createtestjs())
    .pipe(gulp.dest('test/scripts'));
});

gulp.task('template-basic', template('basic', sources.template_path));
gulp.task('template-boule', template('boule', sources.template_path));
gulp.task('template-tac', template('tac', sources.template_path));

gulp.task('watch', function () {
  gulp.watch(sources.scripts, ['update-common-js']);
  gulp.watch(sources.scripts_and_tests, ['test']);
  gulp.watch(sources.dependant_scripts, ['check-dependencies']);
  gulp.watch(sources.styles, ['update-mainstyle']);
  gulp.watch(sources.templates, ['template']);
  gulp.watch(sources.tests, ['update-test-js']);
});
<|endoftext|>