<commit_before>// Copyright 2014 Volker Sorge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Command line interface for the speech rule engine.
 *
 * @author volker.sorge@gmail.com (Volker Sorge)
 */
goog.provide('sre.Cli');

goog.require('sre.Debugger');
goog.require('sre.Engine');
goog.require('sre.Engine.Mode');
goog.require('sre.System');
goog.require('sre.SystemExternal');

/**
 * @constructor
 */
sre.Cli = function() {};

/**
 * Method for the command line interface of the Speech Rule Engine
 */
sre.Cli.prototype.commandLine = function() {
  var commander = sre.SystemExternal.commander;
  // These are necessary to avoid closure errors.
  /** @type {!string} */
  // commander.domain is already in use by the commander module!
  commander.dom = '';
  /** @type {!boolean} */
  commander.enumerate = false;
  /** @type {!string} */
  commander.input = '';
  /** @type {!string} */
  commander.log = '';
  /** @type {!string} */
  commander.output = '';
  /** @type {!boolean} */
  commander.mathml = false;
  /** @type {!boolean} */
  commander.semantics = false;
  /** @type {!string} */
  commander.style = '';
  /** @type {!boolean} */
  commander.verbose = false;

  commander.version(sre.System.getInstance().version).
      option('-d, --dom [name]', 'Domain or subject area [name].').
      option('-e, --enumerate', 'Enumerates available domains and styles.').
      option('-i, --input [name]', 'Input file [name].').
      option('-l, --log [name]', 'Log file [name].').
      option('-m, --mathml', 'Generate MathML output.').
      option('-o, --output [name]', 'Output file [name]. Defaults to stdout.').
      option('-s, --semantics', 'Switch on semantics interpretation.').
      option('-t, --style [name]', 'Speech style [name].').
      option('-v, --verbose', 'Verbose mode.').
      parse(process.argv);
  try {
    if (commander.enumerate) {
      sre.System.getInstance().setupEngine({'mode': sre.Engine.Mode.SYNC});
      var output = 'Domain options: ' +
          sre.Engine.getInstance().allDomains.sort().join(', ') +
          '\nStyle options:  ' +
          sre.Engine.getInstance().allStyles.sort().join(', ');
      console.log(output);
      process.exit(0);
    }
    if (commander.mathml) {
      commander.semantics = true;
    }
    sre.System.getInstance().setupEngine(
        {
          'semantics': commander.semantics,
          'domain': commander.dom,
          'style': commander.style,
          'mode': sre.Engine.Mode.SYNC
        });
    if (commander.verbose) {
      sre.Debugger.getInstance().init(commander.log);
    }
    if (commander.input) {
      sre.System.getInstance().fileToSpeech(commander.input, commander.output);
    }
  } catch (err) {
    console.log(err.name + ': ' + err.message);
    sre.Debugger.getInstance().exit(function() {process.exit(1);});
  }
  sre.Debugger.getInstance().exit(function() {process.exit(0);});
};

(new sre.Cli()).commandLine();
<commit_msg>Pretty prints options.<commit_after>// Copyright 2014 Volker Sorge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Command line interface for the speech rule engine.
 *
 * @author volker.sorge@gmail.com (Volker Sorge)
 */
goog.provide('sre.Cli');

goog.require('sre.Debugger');
goog.require('sre.Engine');
goog.require('sre.Engine.Mode');
goog.require('sre.System');
goog.require('sre.SystemExternal');

/**
 * @constructor
 */
sre.Cli = function() {};

/**
 * Method for the command line interface of the Speech Rule Engine
 */
sre.Cli.prototype.commandLine = function() {
  var commander = sre.SystemExternal.commander;
  // These are necessary to avoid closure errors.
  /** @type {!string} */
  // commander.domain is already in use by the commander module!
  commander.dom = '';
  /** @type {!boolean} */
  commander.enumerate = false;
  /** @type {!string} */
  commander.input = '';
  /** @type {!string} */
  commander.log = '';
  /** @type {!string} */
  commander.output = '';
  /** @type {!boolean} */
  commander.mathml = false;
  /** @type {!boolean} */
  commander.semantics = false;
  /** @type {!string} */
  commander.style = '';
  /** @type {!boolean} */
  commander.verbose = false;

  commander.version(sre.System.getInstance().version).
      option('').
      option('-i, --input [name]', 'Input file [name].').
      option('-o, --output [name]', 'Output file [name]. Defaults to stdout.').
      option('').
      option('-d, --dom [name]', 'Domain or subject area [name].').
      option('-t, --style [name]', 'Speech style [name].').
      option('-s, --semantics', 'Switch on semantics interpretation.').
      option('-e, --enumerate', 'Enumerates available domains and styles.').
      option('').
      option('-a, --audit', 'Generate auditory descriptions (JSON format).').
      option('-j, --json', 'Generate JSON of semantic tree.').
      option('-m, --mathml', 'Generate enriched MathML.').
      option('-p, --speech', 'Generate speech output (default).').
      option('-x, --xml', 'Generate XML of semantic tree.').
      option('').
      option('-v, --verbose', 'Verbose mode.').
      option('-l, --log [name]', 'Log file [name].').
      parse(process.argv);
  try {
    if (commander.enumerate) {
      sre.System.getInstance().setupEngine({'mode': sre.Engine.Mode.SYNC});
      var output = 'Domain options: ' +
          sre.Engine.getInstance().allDomains.sort().join(', ') +
          '\nStyle options:  ' +
          sre.Engine.getInstance().allStyles.sort().join(', ');
      console.log(output);
      process.exit(0);
    }
    if (commander.mathml) {
      commander.semantics = true;
    }
    sre.System.getInstance().setupEngine(
        {
          'semantics': commander.semantics,
          'domain': commander.dom,
          'style': commander.style,
          'mode': sre.Engine.Mode.SYNC
        });
    if (commander.verbose) {
      sre.Debugger.getInstance().init(commander.log);
    }
    if (commander.input) {
      sre.System.getInstance().fileToSpeech(commander.input, commander.output);
    }
  } catch (err) {
    console.log(err.name + ': ' + err.message);
    sre.Debugger.getInstance().exit(function() {process.exit(1);});
  }
  sre.Debugger.getInstance().exit(function() {process.exit(0);});
};

(new sre.Cli()).commandLine();
<|endoftext|>


<commit_before>/*
  radio-to-button.js
    written by UTF-8
*/

//************************************************//
// vOC
//************************************************//

(function($){
	$.fn.radioToButton=function( styles ){

		var SetStyle=function(jq,_mode){
			$.each( styles, function(k,v){
				jq.removeClass( v );
			});
			jq.addClass(styles[_mode]);

		};

		return this.each(function(){
			var _radio=$(this);
			if(!_radio.is('input[type=radio]')) return;

			if(_radio.attr('label')){
/*				var btn=$(document.createElement('input')).attr({
					type: 'button',
					value: _radio.attr('label'),
					disabled: _radio.attr('disabled'),
					className: _radio.attr('className')
				});
*/			var btn=$(document.createElement('a'))
							.click(function(){return false;})
							.addClass( _radio.attr('className') )
							.text(_radio.attr('label'))
							.attr('title',_radio.attr('title'));

				btn.css({
					fontFamily: 'Arial'
				});

				btn.hover(
					function(){
						if( !_radio.attr('checked') && !_radio.attr('disabled') ) SetStyle($(this),'hover');
					},
					function(){
						if( !_radio.attr('checked') && !_radio.attr('disabled') ) SetStyle($(this),'normal');
					}
				).click(function(){
					_radio.click();
					$(':radio[name='+_radio.attr('name')+']').trigger('flush');
				})
				.insertAfter(_radio);

				_radio.bind('flush',function(){
					// disabled
					if( _radio.attr('disabled') ){
						SetStyle( btn, 'disabled' );
					}
					// checked
					else if( _radio.attr('checked') ){
						SetStyle( btn, 'checked' );
					}
					// normal
					else {
						SetStyle( btn, 'normal' );
					}
				});

				_radio.trigger('flush');
				_radio.hide();
			}

		});
	}
})(jQuery);

//************************************************//
//
//************************************************//

$(function(){
	$('.radio-to-button').radioToButton({
		normal: 'radio-to-button-normal',
		hover: 'radio-to-button-hover',
		checked: 'radio-to-button-checked',
		disabled: 'radio-to-button-disabled'
	});
	$('.radio-to-button-l').radioToButton({
		normal: 'radio-to-button-l-normal',
		hover: 'radio-to-button-l-hover',
		checked: 'radio-to-button-l-checked',
		disabled: 'radio-to-button-l-disabled'
	});
});

//************************************************//
// CSS Example
//************************************************//
/*
.radio-to-button {
	display:block;
	cursor:pointer;

	border:0px none;
	background-color:transparent;
	background-repeat:repeat;
	padding:0;
	margin:0;

	outline:0;
	overflow:hidden;

	float: left;
	margin-right: 1px;
}

.radio-to-button {
	background-image: url(./btn-radio.jpg);
}

.radio-to-button-normal {
	color: #333;
	border: 1px solid #333;
	background-position: 0 0;
}
.radio-to-button-hover {
	color: #333;
	border: 1px solid #ff6600;
	background-position: 0 -23px;
}
.radio-to-button-checked {
	color: #fff;
	border: 1px solid #8a3b2b;
	background-position: 0 -46px;
}
.radio-to-button-disabled {
	color: #ccc;
	border: 1px solid #ccc;
	background-position: 0 -69px;
}
</style>
*/

//************************************************//
// HTML Example
//************************************************//
/*
<form>

	<input type="radio" name="hoge" value="1" label="l͂P" />
	<input type="radio" name="hoge" value="2" label="l͂Q" />
	<input type="radio" name="hoge" value="3" label="l͂R" />

	<input type="radio" name="hoge" value="1" label="l͂P" />
	<input type="radio" name="hoge" value="2" label="l͂Q" disabled="disabled" />
	<input type="radio" name="hoge" value="3" label="l͂R" />

	<input type="radio" name="hoge" value="1" label="l͂PAAAAAAAA" />
	<input type="radio" name="hoge" value="2" label="l͂Q" />
	<input type="radio" name="hoge" value="3" label="l͂R" />

</form>
*/

<commit_msg>Removed multibyte comments from radio-to-button.js<commit_after>/*
 * radio-to-button.js
 *
 * Converts radio buttons which have 'radio-to-button' class
 * into  elements with the same class name.
 *  elements can be styled more easily by CSS.
 */

//************************************************//
// jQuery plugin definition
//************************************************//

(function($){
	$.fn.radioToButton=function( styles ){

		var SetStyle=function(jq,_mode){
			$.each( styles, function(k,v){
				jq.removeClass( v );
			});
			jq.addClass(styles[_mode]);

		};

		return this.each(function(){
			var _radio=$(this);
			if(!_radio.is('input[type=radio]')) return;

			if(_radio.attr('label')){
			var btn=$(document.createElement('a'))
							.click(function(){return false;})
							.addClass( _radio.attr('className') )
							.text(_radio.attr('label'))
							.attr('title',_radio.attr('title'));
				btn.hover(
					function(){
						if( !_radio.attr('checked') && !_radio.attr('disabled') )
							SetStyle($(this),'hover');
					},
					function(){
						if( !_radio.attr('checked') && !_radio.attr('disabled') )
							SetStyle($(this),'normal');
					}
				).click(function(){
					_radio.click();
					$(':radio[name='+_radio.attr('name')+']').trigger('flush');
				})
				.insertAfter(_radio);

				_radio.bind('flush',function(){
					// disabled
					if( _radio.attr('disabled') ){
						SetStyle( btn, 'disabled' );
					}
					// checked
					else if( _radio.attr('checked') ){
						SetStyle( btn, 'checked' );
					}
					// normal
					else {
						SetStyle( btn, 'normal' );
					}
				});

				_radio.trigger('flush');
				_radio.hide();
			}

		});
	}
})(jQuery);

//************************************************//
// Initialization
//************************************************//

$(function(){
	$('.radio-to-button').radioToButton({
		normal: 'radio-to-button-normal',
		hover: 'radio-to-button-hover',
		checked: 'radio-to-button-checked',
		disabled: 'radio-to-button-disabled'
	});
	$('.radio-to-button-l').radioToButton({
		normal: 'radio-to-button-l-normal',
		hover: 'radio-to-button-l-hover',
		checked: 'radio-to-button-l-checked',
		disabled: 'radio-to-button-l-disabled'
	});
});

//************************************************//
// HTML Example
//************************************************//
/*
<form>

	<input type="radio" name="foo" value="1" label="apples" />
	<input type="radio" name="foo" value="2" label="bananas" disabled="disabled" />
	<input type="radio" name="foo" value="3" label="oranges" />

</form>
*/
<|endoftext|>


<commit_before>var Maki = require('maki');
var config = require('./config');
var decentral = new Maki( config );

var mongoose = decentral.mongoose;
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;

var Torrent = require('node-torrent-stream');
var readTorrent = require('read-torrent');
var magnet = require('magnet-uri');

var crypto = require('crypto');
var stream = require('stream');

var Credit = decentral.define('Credit', {
  internal: true,
  attributes: {
    _person: { type: ObjectId , ref: 'Person', required: true },
    role: { type: String , enum: ['host', 'producer', 'guest'] }
  }
});

var Show = decentral.define('Show', {
  attributes: {
    name:    { type: String , max: 35 , required: true , slug: true },
    created: { type: Date , default: Date.now , required: true },
    description: { type: String },
    hosts:     [ Credit.Schema ],
    producers: [ Credit.Schema ],
    donations: {
      type: { type: String , enum: ['bitcoin'] },
      destination: { type: String , max: 35 }
    },
    remotes: {
      soundcloud: {

      }
    }
  },
  icon: 'unmute'
});

var Recording = decentral.define('Recording', {
  attributes: {
    _show:    { type: ObjectId , ref: 'Show', required: false , alias: 'show' },
    title:    { type: String , max: 35 , required: true , slug: true },
    media:    { type: 'File', required: true },
    torrent:  { type: ObjectId , render: { create: false } },
    magnet:   { type: String , max: 24 , render: { create: false } },
    type:     { type: String , max: 5 , render: { create: false } },
    recorded: { type: Date },
    released: { type: Date , default: Date.now , required: true },
    description: { type: String },
    hash: { type: String , max: 32 , render: { create: false } },
    credits:  [ Credit.Schema ]
  },
  icon: 'sound'
});

var Checksum = decentral.define('Checksum', {
  attributes: {
    filename: { type: String },
    _file: { type: ObjectId },
    _recording: { type: ObjectId },
    hash: { type: String , max: 35 },
    type: { type: String , enum: ['md5'] },
    created: { type: Date , default: Date.now }
  },
  icon: 'lock'
});

Recording.on('file:media', function(media) {
  console.log('received media:', media);

  var torrent = new Torrent({
    name: media.filename,
    trackers: config.torrents.trackers
  });
  var file = decentral.datastore.gfs.createReadStream({
    _id: media._id
  });
  var torrentstore = decentral.datastore.gfs.createWriteStream({
    mode: 'w',
    filename: media.filename + '.torrent',
    content_type: 'application/x-bittorrent'
  });
  torrentstore.on('error', function(data) {
    console.log('error!' , data );
  });
  torrentstore.on('close', function( torrentFile ) {
    readTorrent('http://localhost:15005/files/' + torrentFile._id , function(err, parsed) {
      if (err) console.error( err );
      var magnetURI = magnet.encode( parsed );

      Recording.patch({
        _id: media.metadata.document
      }, [
        { op: 'add', path: '/torrent' , value: torrentFile._id },
        { op: 'add', path: '/magnet' , value: magnetURI },
        { op: 'add', path: '/type' , value: media.contentType }
      ], function(err, num) {
        if (err) console.error( err );
        console.log('all done,', num , 'affected');
      });

    });
  });

  torrent.pipe( torrentstore );
  file.pipe( torrent );

});

Recording.pre('create', function(next, done) {
  var recording = this;
  if (!recording.media) return next();

  var db = decentral.datastore.mongoose.connections[0].db;
  var files = db.collection('fs.files');
  files.findOne({ _id: recording.media }, function(err, thing) {
    return Checksum.create({
      filename: thing.filename,
      _file: thing._id,
      hash: thing.md5,
      type: 'md5'
    }, function() {
      recording.hash = thing.md5;
      return next();
    });
  });
});

var Person = decentral.define('Person', {
  attributes: {
    name: {
      given: { type: String , max: 30 },
      family: { type: String , max: 70 }
    },
    profiles: {}
  },
  virtuals: {
    'name.full': function() {
      return [ this.name.given , this.name.family ].join(' ');
    }
  },
  icon: 'user'
});

decentral.use({
  extends: {
    services: {
      http: {
        middleware: function(req, res, next) {
          console.log(req.method , req.path, req.headers);
          next();
        }
      }
    }
  }
});

decentral.start(function() {
  decentral.app.get('/search', function(req, res, next) {
    Show.query({}, function(err, shows) {
      return res.send({
        results: shows.map(function(x) {
          return {
            title: x.name
          }
        })
      });
    });
  });
});
<commit_msg>add filename<commit_after>var Maki = require('maki');
var config = require('./config');
var decentral = new Maki( config );

var mongoose = decentral.mongoose;
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;

var Torrent = require('node-torrent-stream');
var readTorrent = require('read-torrent');
var magnet = require('magnet-uri');

var crypto = require('crypto');
var stream = require('stream');

var Credit = decentral.define('Credit', {
  internal: true,
  attributes: {
    _person: { type: ObjectId , ref: 'Person', required: true },
    role: { type: String , enum: ['host', 'producer', 'guest'] }
  }
});

var Show = decentral.define('Show', {
  attributes: {
    name:    { type: String , max: 35 , required: true , slug: true },
    created: { type: Date , default: Date.now , required: true },
    description: { type: String },
    hosts:     [ Credit.Schema ],
    producers: [ Credit.Schema ],
    donations: {
      type: { type: String , enum: ['bitcoin'] },
      destination: { type: String , max: 35 }
    },
    remotes: {
      soundcloud: {

      }
    }
  },
  icon: 'unmute'
});

var Recording = decentral.define('Recording', {
  attributes: {
    _show:    { type: ObjectId , ref: 'Show', required: false , alias: 'show' },
    title:    { type: String , max: 35 , required: true , slug: true },
    media:    { type: 'File', required: true },
    torrent:  { type: ObjectId , render: { create: false } },
    magnet:   { type: String , max: 24 , render: { create: false } },
    type:     { type: String , max: 5 , render: { create: false } },
    filename: { type: String , max: 255 , render: { create: false } },
    recorded: { type: Date },
    released: { type: Date , default: Date.now , required: true },
    description: { type: String },
    hash: { type: String , max: 32 , render: { create: false } },
    credits:  [ Credit.Schema ]
  },
  icon: 'sound'
});

var Checksum = decentral.define('Checksum', {
  attributes: {
    filename: { type: String },
    _file: { type: ObjectId },
    _recording: { type: ObjectId },
    hash: { type: String , max: 35 },
    type: { type: String , enum: ['md5'] },
    created: { type: Date , default: Date.now }
  },
  icon: 'lock'
});

Recording.on('file:media', function(media) {
  console.log('received media:', media);

  var torrent = new Torrent({
    name: media.filename,
    trackers: config.torrents.trackers
  });
  var file = decentral.datastore.gfs.createReadStream({
    _id: media._id
  });
  var torrentstore = decentral.datastore.gfs.createWriteStream({
    mode: 'w',
    filename: media.filename + '.torrent',
    content_type: 'application/x-bittorrent'
  });
  torrentstore.on('error', function(data) {
    console.log('error!' , data );
  });
  torrentstore.on('close', function( torrentFile ) {
    readTorrent('http://localhost:15005/files/' + torrentFile._id , function(err, parsed) {
      if (err) console.error( err );
      var magnetURI = magnet.encode( parsed );

      Recording.patch({
        _id: media.metadata.document
      }, [
        { op: 'add', path: '/torrent' , value: torrentFile._id },
        { op: 'add', path: '/magnet' , value: magnetURI },
        { op: 'add', path: '/type' , value: media.contentType },
        { op: 'add', path: '/filename' , value: media.filename }
      ], function(err, num) {
        if (err) console.error( err );
        console.log('all done,', num , 'affected');
      });

    });
  });

  torrent.pipe( torrentstore );
  file.pipe( torrent );

});

Recording.pre('create', function(next, done) {
  var recording = this;
  if (!recording.media) return next();

  var db = decentral.datastore.mongoose.connections[0].db;
  var files = db.collection('fs.files');
  files.findOne({ _id: recording.media }, function(err, thing) {
    return Checksum.create({
      filename: thing.filename,
      _file: thing._id,
      hash: thing.md5,
      type: 'md5'
    }, function() {
      recording.hash = thing.md5;
      return next();
    });
  });
});

var Person = decentral.define('Person', {
  attributes: {
    name: {
      given: { type: String , max: 30 },
      family: { type: String , max: 70 }
    },
    profiles: {}
  },
  virtuals: {
    'name.full': function() {
      return [ this.name.given , this.name.family ].join(' ');
    }
  },
  icon: 'user'
});

decentral.use({
  extends: {
    services: {
      http: {
        middleware: function(req, res, next) {
          console.log(req.method , req.path, req.headers);
          next();
        }
      }
    }
  }
});

decentral.start(function() {
  decentral.app.get('/search', function(req, res, next) {
    Show.query({}, function(err, shows) {
      return res.send({
        results: shows.map(function(x) {
          return {
            title: x.name
          }
        })
      });
    });
  });
});
<|endoftext|>


<commit_before>"use strict";

var fit = require('canvas-fit');
var mat4 = require('gl-mat4');
var normals = require('normals');
var bunny = require('bunny');
var teapot = require('teapot');
var canvasOrbitCamera = require('canvas-orbit-camera');
var glContext = require('gl-context');
var pack = require('array-pack-2d');

function make_buffer(gl, data, type, mode) {
  // Initialize a buffer.
  var buf = gl.createBuffer();

  // Flatten the data to a packed array.
  var arr = pack(data, type);

  // Insert the data into the buffer.
  gl.bindBuffer(mode, buf);
  gl.bufferData(mode, arr, gl.STATIC_DRAW);

  return buf;
}

// Given a mesh, with the fields `positions` and `cells`, create three buffers
// for drawing the thing. Return an object with the fields:
// - `cells`, a 3-dimensional uint16 element array buffer
// - `positions`, a 3-dimensional float32 array buffer
// - `normals`, ditto
function mesh_buffers(gl, obj) {
  var norm = normals.vertexNormals(obj.cells, obj.positions);

  return {
    cells: make_buffer(gl, obj.cells, 'uint16', gl.ELEMENT_ARRAY_BUFFER),
    positions: make_buffer(gl, obj.positions, 'float32', gl.ARRAY_BUFFER),
    normals: make_buffer(gl, norm, 'float32', gl.ARRAY_BUFFER),
  }
}

// Set a buffer as the element array.
function bind_element_buffer(gl, buffer) {
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer);
}

// Compute a project matrix (placed in the `out` matrix allocation) given the
// width and height of a viewport.
function projection_matrix(out, width, height) {
  var aspectRatio = width / height;
  var fieldOfView = Math.PI / 4;
  var near = 0.01;
  var far  = 100;

  mat4.perspective(out, fieldOfView, aspectRatio, near, far)
}

function start_gl(container, func) {
  // Create a <canvas> element to do our drawing in. Then set it up to fill
  // the container and resize when the window resizes.
  var canvas = container.appendChild(document.createElement('canvas'));
  window.addEventListener('resize', fit(canvas), false);

  // Attach a `canvas-orbit-camera` thing, which handles user input for
  // manipulating the view.
  var camera = canvasOrbitCamera(canvas);

  // Initialize the OpenGL context with our rendering function.
  var gl = glContext(canvas, render);

  // Load the shape data into buffers.
  var bunny_buffers = mesh_buffers(gl, bunny);
  var teapot_buffers = mesh_buffers(gl, teapot);

  // Create the base matrices to be used
  // when rendering the bunny. Alternatively, can
  // be created using `new Float32Array(16)`
  var projection = mat4.create();
  var model = mat4.create();
  var view = mat4.create();

  // Invoke the setup stage to get a function for the render stage.
  // TODO It would sure be nice to get rid of this communication through
  // globals!
  window.dingus = {
    projection: projection,
    model: model,
    view: view,
  };
  window.bunny = bunny_buffers;
  window.teapot = teapot_buffers;
  var shfl_func = func(gl);

  // TODO Move as much of the following as possible to SHFL land.
  function render() {
    // Get the current size of the canvas.
    var width = gl.drawingBufferWidth;
    var height = gl.drawingBufferHeight;

    // Handle user input and update the resulting camera view matrix.
    camera.view(view);
    camera.tick();

    // Update the projection matrix for translating to 2D screen space.
    projection_matrix(projection, width, height);

    // Draw on the whole canvas.
    gl.viewport(0, 0, width, height);

    // Rendering flags.
    gl.enable(gl.DEPTH_TEST);  // Prevent triangle overlap.
    gl.enable(gl.CULL_FACE);  // Triangles not visible from behind.

    // Invoke the compiled SHFL code.
    shfl_func();

    // And the element array.
    bind_element_buffer(gl, bunny_buffers.cells);

    // Draw it!
    var count = bunny.cells.length * bunny.cells[0].length;
    gl.drawElements(gl.TRIANGLES, count, gl.UNSIGNED_SHORT, 0);
  };
}

module.exports = start_gl;
<commit_msg>Start abstracting the mesh drawing<commit_after>"use strict";

var fit = require('canvas-fit');
var mat4 = require('gl-mat4');
var normals = require('normals');
var bunny = require('bunny');
var teapot = require('teapot');
var canvasOrbitCamera = require('canvas-orbit-camera');
var glContext = require('gl-context');
var pack = require('array-pack-2d');

function make_buffer(gl, data, type, mode) {
  // Initialize a buffer.
  var buf = gl.createBuffer();

  // Flatten the data to a packed array.
  var arr = pack(data, type);

  // Insert the data into the buffer.
  gl.bindBuffer(mode, buf);
  gl.bufferData(mode, arr, gl.STATIC_DRAW);

  return buf;
}

// Given a mesh, with the fields `positions` and `cells`, create three buffers
// for drawing the thing. Return an object with the fields:
// - `cells`, a 3-dimensional uint16 element array buffer
// - `positions`, a 3-dimensional float32 array buffer
// - `normals`, ditto
function mesh_buffers(gl, obj) {
  var norm = normals.vertexNormals(obj.cells, obj.positions);

  return {
    cells: make_buffer(gl, obj.cells, 'uint16', gl.ELEMENT_ARRAY_BUFFER),
    positions: make_buffer(gl, obj.positions, 'float32', gl.ARRAY_BUFFER),
    normals: make_buffer(gl, norm, 'float32', gl.ARRAY_BUFFER),
  }
}

// Set a buffer as the element array.
function bind_element_buffer(gl, buffer) {
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer);
}

// Compute a project matrix (placed in the `out` matrix allocation) given the
// width and height of a viewport.
function projection_matrix(out, width, height) {
  var aspectRatio = width / height;
  var fieldOfView = Math.PI / 4;
  var near = 0.01;
  var far  = 100;

  mat4.perspective(out, fieldOfView, aspectRatio, near, far)
}

// A convenience wrapper for binding elements and drawing them. Takes a cells
// buffer as its argument.
function draw_mesh(gl, obj, cells) {
  bind_element_buffer(gl, cells);

  var count = obj.cells.length * obj.cells[0].length;
  gl.drawElements(gl.TRIANGLES, count, gl.UNSIGNED_SHORT, 0);
}

function start_gl(container, func) {
  // Create a <canvas> element to do our drawing in. Then set it up to fill
  // the container and resize when the window resizes.
  var canvas = container.appendChild(document.createElement('canvas'));
  window.addEventListener('resize', fit(canvas), false);

  // Attach a `canvas-orbit-camera` thing, which handles user input for
  // manipulating the view.
  var camera = canvasOrbitCamera(canvas);

  // Initialize the OpenGL context with our rendering function.
  var gl = glContext(canvas, render);

  // Load the shape data into buffers.
  var bunny_buffers = mesh_buffers(gl, bunny);
  var teapot_buffers = mesh_buffers(gl, teapot);

  // Create the base matrices to be used
  // when rendering the bunny. Alternatively, can
  // be created using `new Float32Array(16)`
  var projection = mat4.create();
  var model = mat4.create();
  var view = mat4.create();

  // Invoke the setup stage to get a function for the render stage.
  // TODO It would sure be nice to get rid of this communication through
  // globals!
  window.dingus = {
    projection: projection,
    model: model,
    view: view,
  };
  window.bunny = bunny_buffers;
  window.teapot = teapot_buffers;
  var shfl_func = func(gl);

  // TODO Move as much of the following as possible to SHFL land.
  function render() {
    // Get the current size of the canvas.
    var width = gl.drawingBufferWidth;
    var height = gl.drawingBufferHeight;

    // Handle user input and update the resulting camera view matrix.
    camera.view(view);
    camera.tick();

    // Update the projection matrix for translating to 2D screen space.
    projection_matrix(projection, width, height);

    // Draw on the whole canvas.
    gl.viewport(0, 0, width, height);

    // Rendering flags.
    gl.enable(gl.DEPTH_TEST);  // Prevent triangle overlap.
    gl.enable(gl.CULL_FACE);  // Triangles not visible from behind.

    // Invoke the compiled SHFL code.
    shfl_func();

    // Draw the model!
    draw_mesh(gl, bunny, bunny_buffers.cells);
  };
}

module.exports = start_gl;
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Wed Feb 05 2014 13:15:20 GMT+0100 (CET)

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

    // base path, that will be used to resolve files and exclude
    basePath: '',

    // frameworks to use
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'http://code.angularjs.org/1.2.11/angular.min.js',
      'http://code.angularjs.org/1.2.11/angular-mocks.js',
      'http://underscorejs.org/underscore-min.js',
      'coffee/atTable.coffee',
      'coffee/*.coffee',
      'test/test_helper.coffee',
      'test/*.coffee',
      'test/templates/**/*.html'
    ],

    // list of files to exclude
    exclude: [

    ],

    preprocessors: {
      'coffee/*.coffee': ['coffee'],
      'test/*.coffee': ['coffee'],
      'test/templates/**/*.html': ['ng-html2js']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
    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, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: ['Chrome'],

    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false
  });
};
<commit_msg>table_setup needs to be loaded before other classes<commit_after>// Karma configuration
// Generated on Wed Feb 05 2014 13:15:20 GMT+0100 (CET)

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

    // base path, that will be used to resolve files and exclude
    basePath: '',

    // frameworks to use
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'http://code.angularjs.org/1.2.11/angular.min.js',
      'http://code.angularjs.org/1.2.11/angular-mocks.js',
      'http://underscorejs.org/underscore-min.js',
      'coffee/atTable.coffee',
      'coffee/table.coffee',
      'coffee/table_setup.coffee',
      'coffee/*.coffee',
      'test/test_helper.coffee',
      'test/*.coffee',
      'test/templates/**/*.html'
    ],

    // list of files to exclude
    exclude: [

    ],

    preprocessors: {
      'coffee/*.coffee': ['coffee'],
      'test/*.coffee': ['coffee'],
      'test/templates/**/*.html': ['ng-html2js']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
    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, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: ['Chrome'],

    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false
  });
};
<|endoftext|>


<commit_before>
/*************************
     Default Settings
 *************************/

// Settings
var settings = {

  // Save data
  data : null,

  // Feature Group representation of data
  layers : [],

  // Target API URL
  API_url : (window.location.href.indexOf("herokuapp.com") > -1) ? "http://g-player.herokuapp.com/api/" : "http://localhost:5000/api/",

  // enable heatmap
  heatmap : true,

  // enable player paths
  paths : true,

  // Default Game
  game : "Fallout New Vegas",

  // Current Map
  map : null,

  // Current overlay
  overlay : null,

};

/******************************
        config.js
 ******************************/

// Available options
var options = {};

options.actions = [];

options.players = [];

options.games = [
	"Fallout New Vegas",
	"League of Legends",
	"Quake 3",
	"Game Gaze",
];

options.maps = [{

    // Save map configuration
    name: "Position_Introhouse",
    game: "Fallout New Vegas",
    url: "http://i.imgur.com/zWbog8y.jpg",

    // Map player locations to their points
    // on the map. Define the corners.
    bottom : -836,
    left : -823,

    top : 2463,
    right : 2977,

}, {

    // Save map configuration
    name: "Position_Outside",
    game: "Fallout New Vegas",
    url: "http://i.imgur.com/sSYRyve.jpg",

    // Map player locations to their points
    // on the map. Manually offset for accuracy.
    // Multiplied to base

    bottom : -13981,
    left : -7682,

    top : 14735,
    right : 20151,

}, {

    // Save map configuration
    name: "Position_Bar",
    game: "Fallout New Vegas",
    url: "http://i.imgur.com/9lo12qd.jpg",

    // Map player locations to their points
    // on the map. Manually offset for accuracy.
    // Multiplied to base

    bottom : 70,
    left : 1020,

    top : 1248,
    right : 2620,

}, {

    // Save map configuration
    name: "Position_AbandonedHouse",
    game: "Fallout New Vegas",
    url: "http://i.imgur.com/kMyybLB.jpg",

    // Map player locations to their points
    // on the map. Manually offset for accuracy.
    // Multiplied to base

    bottom : -2104,
    left : -274,

    top : 84,
    right : 1914,

}, {

    // Save map configuration
    name: "Position_Cave",
    game: "Fallout New Vegas",
    url: "http://i.imgur.com/ynqOvIh.png",

    // Map player locations to their points
    // on the map. Manually offset for accuracy.
    // Multiplied to base

    bottom : 0,
    left : 0,

    top : 100,
    right : 100,

}, {

    // Save map configuration
    name: "Position_SheriffOffice",
    game: "Fallout New Vegas",
    url: "http://i.imgur.com/kMPpXSW.jpg",

    // Map player locations to their points
    // on the map. Manually offset for accuracy.
    // Multiplied to base

    bottom : 590,
    left : 1490,

    top : 1950,
    right : 2428,

}, {

    // Save map configuration
    name: "Position_Mine",
    game: "Fallout New Vegas",
    url: "http://i.imgur.com/2j0T2C0.jpg",

    // Map player locations to their points
    // on the map. Manually offset for accuracy.
    // Multiplied to base

    bottom : 0,
    left : 0,

    top : 100,
    right : 100,

}, {

    // Save map configuration
    name: "Position_Hotel",
    game: "Fallout New Vegas",
    url: "http://i.imgur.com/sKG9eRI.jpg",

    // Map player locations to their points
    // on the map. Manually offset for accuracy.
    // Multiplied to base

    bottom : 170,
    left : 60,

    top : 4200,
    right : 4310,

}, {

    // Save map configuration
    name: "Map",
    game: "League of Legends",
    url: "/leagueoflegends/map.jpg",

    // Map player locations to their points
    // on the map. Manually offset for accuracy.
    // Multiplied to base
    top : 0,
    bottom : 0,
    left : 0,
    right : 0,
}];

/******************************
        key-mappings.js
 ******************************/

/*

 Initialized by Alex Johnson
 With work from Alex Jacks

 This file stores a number of key-mapping
 settings for converting .csv files
 into their relvant JSON data files.

 Essentially, when a user imports a .csv
 file, we do not know WHICH column represents
 which data field.

 To solve this problem, we store an internal
 set of "kay-mappings". Using the first value
 of a .csv row, we can decide the "type" of
 action that row represents.

 For example, if the first row is "Position_Bar",
 We know that the data represents a player position
 and a specific point, thus we can use the
 key mapping for "position"s. This allows us
 to correlate columns 1->9 with their key.

 */

/*

This is a lookup table.
The first column of a row will always
tell us the name of the action. Using
this name, we fetch the corresponding
key mapping.

*/

// Lookup Table for Mapping action
// name to action type.

options.lookup_table = {

	"Attacked" : "action",
	"CraftingTable" : "craft",
	"Creature Giant Rat attacked first" : "ratattack",
	"Dialogue" : "dialogue",

	"InteractionContainer" : "interaction",
	"InteractionDoor" : "interactionNoTarget",
	"InteractionInterior" : "interaction",
	"InteractionNPC" : "interaction",
	"InteractionObject" : "interaction",

	"NPC Bean attacked first" : "attacked",
	"NPC Bobby D attacked first" : "attacked",
	"NPC Collin attacked first" : "attacked",
	"NPC Dough attacked first" : "attacked",
	"NPC JD attacked first" : "attacked",
	"NPC Mel attacked first" : "attacked",
	"NPC Munz attacked first" : "attacked",
	"NPC Ray attacked first" : "attacked",
	"NPC Sara attacked first" : "attacked",
	"NPC Sheriff attacked first" : "attacked",
	"NPC Slater attacked first" : "attacked",

	"ObjectOnActivate" : "object",
	"player attacked first" : "playeraction",
	"Player killed" : "playeraction",
	"Player looted dead" : "playeraction",
	"Player looted Dead" : "playeraction",
	"Player shooting a dead" : "playeraction",

	"PlayerDropItem" : "item",
	"PlayerDroppedItem" : "item",
	"PlayerEquipped" : "item",
	"PlayerLootedItem" : "item",
	"PlayerShot" : "item",
	"PlayerUnequipped" : "item",
	"PlayerJumped" : "jump",

	"PlayerSneaking" : "sneaking",

	"Position_AbandonedHouse" : "position",
	"Position_Bar" : "position",
	"Position_Hotel" : "position",
	"Position_Introhouse" : "position",
	"Position_Outside" : "position",
	"Position_SheriffOffice" : "position",

	"Quest" : "quest",
	"Stat" : "stat",
}

// Store a list of available key mappings
options.mappings = [{

	// Represent a player position in a map
	game  : "Fallout New Vegas",
	type  : "position",
	columns : ["area", "playerID", "timestamp", "posX", "posY", "cameraX", "cameraY", "???", "??", "?"]
}, {

	// Represent a user action
	game  : "Fallout New Vegas",
	type  : "action",
	columns : ["action", "playerID", "value", "target", "status"],
}, {

	// Represent a user dialogue
	game  : "Fallout New Vegas",
	type  : "dialogue",
	columns : ["action", "playerId", "timestamp", "??", "NPC", "text", "response"],
}, {

	// Represent a user interaction
	game  : "Fallout New Vegas",
	type  : "interaction",
	columns : ["action", "location", "playerID", "object", "posX", "posY", "cameraX", "cameraY"],
}, {

	// Represent item interactions
	game  : "Fallout New Vegas",
	type  : "item",
	columns : ["action", "item", "value"],
}, {

	// Represent attacks against the player
	game  : "Fallout New Vegas",
	type  : "attacked",
	columns : ["action", "playerID", "value"],
}, {

	// Represents player sneaking
	game  : "Fallout New Vegas",
	type  : "sneaking",
	columns : ["action", "area", "playerID", "value", "???"],
}, {

	// Represents player jumping
	game  : "Fallout New Vegas",
	type  : "jump",
	columns : ["action", "value"],
}, {

	// Represents player interactions
	game : "Fallout New Vegas",
	type : "interaction",
	columns : ["action", "area", "playerID", "target", "timestamp", "posX", "posY", "?"],
}, {

	// Represents player interactions without explicit targets
	game : "Fallout New Vegas",
	type : "interactionNoTarget",
	columns : ["action", "area", "playerID", "timestamp", "posX", "posY", "?"],

	// Represents player crafting
	game  : "Fallout New Vegas",
	type  : "craft",
	columns : ["action", "name", "playerID", "value"],
}, {

	// Represents player getting attacked by giant rat
	game  : "Fallout New Vegas",
	type  : "ratattack",
	columns : ["action", "playerID", "value"],
}, {

	// Represents player getting some object
	game  : "Fallout New Vegas",
	type  : "object",
	columns : ["action", "????", "value"],
}, {

	// Represents player doing some action
	game  : "Fallout New Vegas",
	type  : "playeraction",
	columns : ["action", "playerID", "value", "object"],
}, {

	// Represents player on quest
	game  : "Fallout New Vegas",
	type  : "quest",
	columns : ["action", "playerID", "value", "name", "status"],
}, {

	// Represents player stat
	game  : "Fallout New Vegas",
	type  : "stat",
	columns : ["action", "playerID", "action", "key", "value", "status"],
}];

// Return the key mapping given the
// game name, and the event name

// ex: getKeyMapping("Fallout New Vegas", "Attacked")

var getKeyMapping = function(game, eventName){

	// Get the type of event from the lookup table
	var type = options.lookup_table[eventName];

	// Find mapping
	var mapping = _.findWhere(options.mappings, {game : settings.game, type : type});

	if (!mapping || !type) {
		console.error("Unable to find key mapping for: " + eventName);
		return;
	}

	return mapping;
}

// assignKeys() returns a JSON object, where
// the values of the 'values' array are assigned
// to the column names provided in the 'mapping' array.

// For example:
// values : ["apple", "orange", "pear"]
// columns : ["fruit", "color", "shape"]

// Results in:
// { fruit : "Apple", color : "orange", shape : "pear" }

var assignKeys = function(values, columns){
	var acc = {};

	// Check data. Make sure we have enough keys for our data.
	if (columns.length != values.length){
		console.error("Warning: Mismatch in key mapping. Amount of keys and values differ." + columns.length + " Columns, " + values.length + " Values");
		console.log(columns);
		console.log(values);
		console.log("\n");
	}

	_.each(columns, function(value, key){
		// Ensure data exists. If not, make it null for DB.
		if (!values[key]) {
			values[key] = null;
		};

		// Create key/value pair
		acc[value] = values[key];
	});

	acc["game"] = settings.game;
	return acc;
	// ex: assignKeys(["apple", "orange", "pear"], ["fruit", "color", "shape"])
}

// Given a list of arrays, convert the data into JSON objects.
//   game : String of game name
//   eventName : the event name for this table
//   data : multudimensional array container player data

var assignKeysForEntireTable = function(game, eventName, data) {
	var acc = [];

	// Key the key mapping
	var mapping = getKeyMapping(game, eventName).columns;

	// Apply key mapping to each object in the data array
	_.each(data, function(d){
		var json = assigKeys(d, mapping);
		if (json) acc.push(json);
	})

	return acc;
}
<commit_msg>Rename url key on a map to imageURL<commit_after>
/*************************
     Default Settings
 *************************/

// Settings
var settings = {

  // Save data
  data : null,

  // Feature Group representation of data
  layers : [],

  // Target API url
  API_URL : (window.location.href.indexOf("herokuapp.com") > -1) ? "http://g-player.herokuapp.com/api/" : "http://localhost:5000/api/",

  // enable heatmap
  heatmap : true,

  // enable player paths
  paths : true,

  // Default Game
  game : "Fallout New Vegas",

  // Current Map
  map : null,

  // Current overlay
  overlay : null,

};

/******************************
        config.js
 ******************************/

// Available options
var options = {};

options.actions = [];

options.players = [];

options.games = [
	"Fallout New Vegas",
	"League of Legends",
	"Quake 3",
	"Game Gaze",
];

options.maps = [{

    // Save map configuration
    name: "Position_Introhouse",
    game: "Fallout New Vegas",
    imageURL: "http://i.imgur.com/zWbog8y.jpg",

    // Map player locations to their points
    // on the map. Define the corners.
    bottom : -836,
    left : -823,

    top : 2463,
    right : 2977,

}, {

    // Save map configuration
    name: "Position_Outside",
    game: "Fallout New Vegas",
    imageURL: "http://i.imgur.com/sSYRyve.jpg",

    // Map player locations to their points
    // on the map. Manually offset for accuracy.
    // Multiplied to base

    bottom : -13981,
    left : -7682,

    top : 14735,
    right : 20151,

}, {

    // Save map configuration
    name: "Position_Bar",
    game: "Fallout New Vegas",
    imageURL: "http://i.imgur.com/9lo12qd.jpg",

    // Map player locations to their points
    // on the map. Manually offset for accuracy.
    // Multiplied to base

    bottom : 70,
    left : 1020,

    top : 1248,
    right : 2620,

}, {

    // Save map configuration
    name: "Position_AbandonedHouse",
    game: "Fallout New Vegas",
    imageURL: "http://i.imgur.com/kMyybLB.jpg",

    // Map player locations to their points
    // on the map. Manually offset for accuracy.
    // Multiplied to base

    bottom : -2104,
    left : -274,

    top : 84,
    right : 1914,

}, {

    // Save map configuration
    name: "Position_Cave",
    game: "Fallout New Vegas",
    imageURL: "http://i.imgur.com/ynqOvIh.png",

    // Map player locations to their points
    // on the map. Manually offset for accuracy.
    // Multiplied to base

    bottom : 0,
    left : 0,

    top : 100,
    right : 100,

}, {

    // Save map configuration
    name: "Position_SheriffOffice",
    game: "Fallout New Vegas",
    imageURL: "http://i.imgur.com/kMPpXSW.jpg",

    // Map player locations to their points
    // on the map. Manually offset for accuracy.
    // Multiplied to base

    bottom : 590,
    left : 1490,

    top : 1950,
    right : 2428,

}, {

    // Save map configuration
    name: "Position_Mine",
    game: "Fallout New Vegas",
    imageURL: "http://i.imgur.com/2j0T2C0.jpg",

    // Map player locations to their points
    // on the map. Manually offset for accuracy.
    // Multiplied to base

    bottom : 0,
    left : 0,

    top : 100,
    right : 100,

}, {

    // Save map configuration
    name: "Position_Hotel",
    game: "Fallout New Vegas",
    imageURL: "http://i.imgur.com/sKG9eRI.jpg",

    // Map player locations to their points
    // on the map. Manually offset for accuracy.
    // Multiplied to base

    bottom : 170,
    left : 60,

    top : 4200,
    right : 4310,

}, {

    // Save map configuration
    name: "Map",
    game: "League of Legends",
    imageURL: "/leagueoflegends/map.jpg",

    // Map player locations to their points
    // on the map. Manually offset for accuracy.
    // Multiplied to base
    top : 0,
    bottom : 0,
    left : 0,
    right : 0,
}];

/******************************
        key-mappings.js
 ******************************/

/*

 Initialized by Alex Johnson
 With work from Alex Jacks

 This file stores a number of key-mapping
 settings for converting .csv files
 into their relvant JSON data files.

 Essentially, when a user imports a .csv
 file, we do not know WHICH column represents
 which data field.

 To solve this problem, we store an internal
 set of "kay-mappings". Using the first value
 of a .csv row, we can decide the "type" of
 action that row represents.

 For example, if the first row is "Position_Bar",
 We know that the data represents a player position
 and a specific point, thus we can use the
 key mapping for "position"s. This allows us
 to correlate columns 1->9 with their key.

 */

/*

This is a lookup table.
The first column of a row will always
tell us the name of the action. Using
this name, we fetch the corresponding
key mapping.

*/

// Lookup Table for Mapping action
// name to action type.

options.lookup_table = {

	"Attacked" : "action",
	"CraftingTable" : "craft",
	"Creature Giant Rat attacked first" : "ratattack",
	"Dialogue" : "dialogue",

	"InteractionContainer" : "interaction",
	"InteractionDoor" : "interactionNoTarget",
	"InteractionInterior" : "interaction",
	"InteractionNPC" : "interaction",
	"InteractionObject" : "interaction",

	"NPC Bean attacked first" : "attacked",
	"NPC Bobby D attacked first" : "attacked",
	"NPC Collin attacked first" : "attacked",
	"NPC Dough attacked first" : "attacked",
	"NPC JD attacked first" : "attacked",
	"NPC Mel attacked first" : "attacked",
	"NPC Munz attacked first" : "attacked",
	"NPC Ray attacked first" : "attacked",
	"NPC Sara attacked first" : "attacked",
	"NPC Sheriff attacked first" : "attacked",
	"NPC Slater attacked first" : "attacked",

	"ObjectOnActivate" : "object",
	"player attacked first" : "playeraction",
	"Player killed" : "playeraction",
	"Player looted dead" : "playeraction",
	"Player looted Dead" : "playeraction",
	"Player shooting a dead" : "playeraction",

	"PlayerDropItem" : "item",
	"PlayerDroppedItem" : "item",
	"PlayerEquipped" : "item",
	"PlayerLootedItem" : "item",
	"PlayerShot" : "item",
	"PlayerUnequipped" : "item",
	"PlayerJumped" : "jump",

	"PlayerSneaking" : "sneaking",

	"Position_AbandonedHouse" : "position",
	"Position_Bar" : "position",
	"Position_Hotel" : "position",
	"Position_Introhouse" : "position",
	"Position_Outside" : "position",
	"Position_SheriffOffice" : "position",

	"Quest" : "quest",
	"Stat" : "stat",
}

// Store a list of available key mappings
options.mappings = [{

	// Represent a player position in a map
	game  : "Fallout New Vegas",
	type  : "position",
	columns : ["area", "playerID", "timestamp", "posX", "posY", "cameraX", "cameraY", "???", "??", "?"]
}, {

	// Represent a user action
	game  : "Fallout New Vegas",
	type  : "action",
	columns : ["action", "playerID", "value", "target", "status"],
}, {

	// Represent a user dialogue
	game  : "Fallout New Vegas",
	type  : "dialogue",
	columns : ["action", "playerId", "timestamp", "??", "NPC", "text", "response"],
}, {

	// Represent a user interaction
	game  : "Fallout New Vegas",
	type  : "interaction",
	columns : ["action", "location", "playerID", "object", "posX", "posY", "cameraX", "cameraY"],
}, {

	// Represent item interactions
	game  : "Fallout New Vegas",
	type  : "item",
	columns : ["action", "item", "value"],
}, {

	// Represent attacks against the player
	game  : "Fallout New Vegas",
	type  : "attacked",
	columns : ["action", "playerID", "value"],
}, {

	// Represents player sneaking
	game  : "Fallout New Vegas",
	type  : "sneaking",
	columns : ["action", "area", "playerID", "value", "???"],
}, {

	// Represents player jumping
	game  : "Fallout New Vegas",
	type  : "jump",
	columns : ["action", "value"],
}, {

	// Represents player interactions
	game : "Fallout New Vegas",
	type : "interaction",
	columns : ["action", "area", "playerID", "target", "timestamp", "posX", "posY", "?"],
}, {

	// Represents player interactions without explicit targets
	game : "Fallout New Vegas",
	type : "interactionNoTarget",
	columns : ["action", "area", "playerID", "timestamp", "posX", "posY", "?"],

	// Represents player crafting
	game  : "Fallout New Vegas",
	type  : "craft",
	columns : ["action", "name", "playerID", "value"],
}, {

	// Represents player getting attacked by giant rat
	game  : "Fallout New Vegas",
	type  : "ratattack",
	columns : ["action", "playerID", "value"],
}, {

	// Represents player getting some object
	game  : "Fallout New Vegas",
	type  : "object",
	columns : ["action", "????", "value"],
}, {

	// Represents player doing some action
	game  : "Fallout New Vegas",
	type  : "playeraction",
	columns : ["action", "playerID", "value", "object"],
}, {

	// Represents player on quest
	game  : "Fallout New Vegas",
	type  : "quest",
	columns : ["action", "playerID", "value", "name", "status"],
}, {

	// Represents player stat
	game  : "Fallout New Vegas",
	type  : "stat",
	columns : ["action", "playerID", "action", "key", "value", "status"],
}];

// Return the key mapping given the
// game name, and the event name

// ex: getKeyMapping("Fallout New Vegas", "Attacked")

var getKeyMapping = function(game, eventName){

	// Get the type of event from the lookup table
	var type = options.lookup_table[eventName];

	// Find mapping
	var mapping = _.findWhere(options.mappings, {game : settings.game, type : type});

	if (!mapping || !type) {
		console.error("Unable to find key mapping for: " + eventName);
		return;
	}

	return mapping;
}

// assignKeys() returns a JSON object, where
// the values of the 'values' array are assigned
// to the column names provided in the 'mapping' array.

// For example:
// values : ["apple", "orange", "pear"]
// columns : ["fruit", "color", "shape"]

// Results in:
// { fruit : "Apple", color : "orange", shape : "pear" }

var assignKeys = function(values, columns){
	var acc = {};

	// Check data. Make sure we have enough keys for our data.
	if (columns.length != values.length){
		console.error("Warning: Mismatch in key mapping. Amount of keys and values differ." + columns.length + " Columns, " + values.length + " Values");
		console.log(columns);
		console.log(values);
		console.log("\n");
	}

	_.each(columns, function(value, key){
		// Ensure data exists. If not, make it null for DB.
		if (!values[key]) {
			values[key] = null;
		};

		// Create key/value pair
		acc[value] = values[key];
	});

	acc["game"] = settings.game;
	return acc;
	// ex: assignKeys(["apple", "orange", "pear"], ["fruit", "color", "shape"])
}

// Given a list of arrays, convert the data into JSON objects.
//   game : String of game name
//   eventName : the event name for this table
//   data : multudimensional array container player data

var assignKeysForEntireTable = function(game, eventName, data) {
	var acc = [];

	// Key the key mapping
	var mapping = getKeyMapping(game, eventName).columns;

	// Apply key mapping to each object in the data array
	_.each(data, function(d){
		var json = assigKeys(d, mapping);
		if (json) acc.push(json);
	})

	return acc;
}
<|endoftext|>


<commit_before>module.exports = (config) => {
  const configuration = {
    frameworks: [
      'browserify',
      'jasmine',
    ],
    files: [
      'test/**/*.js',
      'src/**/*.spec.js',
    ],
    browsers: [
      'ChromeHeadless',
    ],
    transports: ['polling'],
    customLaunchers: {
      ChromeTravisCi: {
        base: 'ChromeHeadless',
        flags: ['--headless --disable-gpu'],
      },
    },
    reporters: [
      'progress',
      'coverage',
    ],
    coverageReporter: {
      check: {
        each: {
          statements: 0,
          branches: 0,
          functions: 0,
          lines: 0,
        },
        global: {
          statements: 50,
          branches: 50,
          functions: 50,
          lines: 50,
        },
      },
      reporters: [
        {
          type: 'html',
          dir: 'coverage/',
          subdir: 'report-html',
        },
        {
          type: 'text',
        },
        {
          type: 'json',
        },
      ],
      instrumenterOptions: {
        istanbul: {
          noCompact: true,
        },
      },
    },
    preprocessors: {
      'test/**/*.js': ['browserify'],
      'src/**/*.spec.js': ['browserify'],
    },
    browserify: {
      entries: 'src/index.js',
      debug: true,
      transform: [
        'babelify',
      ],
    },
  };

  if (process.env.TRAVIS) {
    configuration.browsers = [
      'ChromeTravisCi',
    ];
  }

  config.set(configuration);
};
<commit_msg>chore(karma.conf.js): add package folder<commit_after>module.exports = (config) => {
  const configuration = {
    frameworks: [
      'browserify',
      'jasmine',
    ],
    files: [
      'packages/**/*.spec.js',
      'test/**/*.js',
      'src/**/*.spec.js',
    ],
    browsers: [
      'ChromeHeadless',
    ],
    transports: ['polling'],
    customLaunchers: {
      ChromeTravisCi: {
        base: 'ChromeHeadless',
        flags: ['--headless --disable-gpu'],
      },
    },
    reporters: [
      'progress',
      'coverage',
    ],
    coverageReporter: {
      check: {
        each: {
          statements: 0,
          branches: 0,
          functions: 0,
          lines: 0,
        },
        global: {
          statements: 50,
          branches: 50,
          functions: 50,
          lines: 50,
        },
      },
      reporters: [
        {
          type: 'html',
          dir: 'coverage/',
          subdir: 'report-html',
        },
        {
          type: 'text',
        },
        {
          type: 'json',
        },
      ],
      instrumenterOptions: {
        istanbul: {
          noCompact: true,
        },
      },
    },
    preprocessors: {
      'packages/**/*.spec.js': ['browserify'],
      'test/**/*.js': ['browserify'],
      'src/**/*.spec.js': ['browserify'],
    },
    browserify: {
      entries: 'src/index.js',
      debug: true,
      transform: [
        'babelify',
      ],
    },
  };

  if (process.env.TRAVIS) {
    configuration.browsers = [
      'ChromeTravisCi',
    ];
  }

  config.set(configuration);
};
<|endoftext|>


<commit_before>// Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html

module.exports = function(config) {
  config.set({
    // base path, that will be used to resolve files and exclude
    basePath: '',

    // testing framework to use (jasmine/mocha/qunit/...)
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'app/bower_components/angular/angular.js',
      'app/bower_components/angular-mocks/angular-mocks.js',
      'app/bower_components/angular-resource/angular-resource.js',
      'app/bower_components/angular-cookies/angular-cookies.js',
      'app/bower_components/angular-sanitize/angular-sanitize.js',
      'app/bower_components/angular-route/angular-route.js',
      'app/scripts/*.js',
      'app/scripts/**/*.js',
      'test/mock/**/*.js',
      'test/spec/**/*.js'
    ],

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

    // web server port
    port: 8080,

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

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

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: ['Chrome'],

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    reporters: ['progress', 'coverage'],

    preprocessors : {
      'app/scripts/pagination/*.js': 'coverage'
    },

    //coverageReporter : { type : 'html', dir : 'tmp/coverage/'}
    coverageReporter : { type : 'text' }

  });
};
<commit_msg>Replaced Chrome with PhantonJS to work on travis-ci.<commit_after>// Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html

module.exports = function(config) {
  config.set({
    // base path, that will be used to resolve files and exclude
    basePath: '',

    // testing framework to use (jasmine/mocha/qunit/...)
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'app/bower_components/angular/angular.js',
      'app/bower_components/angular-mocks/angular-mocks.js',
      'app/bower_components/angular-resource/angular-resource.js',
      'app/bower_components/angular-cookies/angular-cookies.js',
      'app/bower_components/angular-sanitize/angular-sanitize.js',
      'app/bower_components/angular-route/angular-route.js',
      'app/scripts/*.js',
      'app/scripts/**/*.js',
      'test/mock/**/*.js',
      'test/spec/**/*.js'
    ],

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

    // web server port
    port: 8080,

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

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

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: ['PhantomJS'],

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    reporters: ['progress', 'coverage'],

    preprocessors : {
      'app/scripts/pagination/*.js': 'coverage'
    },

    //coverageReporter : { type : 'html', dir : 'tmp/coverage/'}
    coverageReporter : { type : 'text' }

  });
};
<|endoftext|>


<commit_before>'use strict';
var game = require('../game'),
  Phaser = require('phaser').Phaser;

function create() {

}

function update() {

}

function paused() {

}

function render() {

}

function shutdown() {

}

var exampleStateState = {
  create: create,
  update: update,
  paused: paused,
  render: render,
  shutdown: shutdown
};

module.exports = exampleStateState;
<commit_msg>removed bogus state<commit_after><|endoftext|>


<commit_before>/* global THREE, createNumericInput, remove updateGeometry, translateBoxVertices */
(function() {
  'use strict';

  var container;

  var scene, camera, renderer;

  var geometry, material, mesh;
  var wireframe;

  function setGeometry( _geometry ) {
    geometry = _geometry;
    mesh.geometry = geometry;
    mesh.needsUpdate = true;
  }

  function createBoxGeometry( dimensions, transformFn, vectors ) {
    var geometry = new THREE.BoxGeometry( dimensions[0], dimensions[1], dimensions[2] );

    if ( typeof vectors === 'object' ) {
      translateBoxVertices( geometry, vectors );
    }

    if ( typeof transformFn === 'function' ) {
      transformFn( geometry );
    } else if ( Array.isArray( transformFn ) ) {
      transformFn.forEach(function( transformFn ) {
        transformFn( geometry );
      });
    }

    return geometry;
  }

  function createWireframe() {
    remove( wireframe );
    wireframe = new THREE.WireframeHelper( mesh );
    scene.add( wireframe );
  }

  function mergeGeometries( geometries ) {
    return geometries.reduce(function( a, b ) {
      a.merge( b );
      return a;
    })
  }

  function getQueryParam( key ) {
    var params = window.location.search
      .slice( 1 )
      .split( '&' )
      .reduce(function( object, pair ) {
        pair = pair.split( '=' ).map( decodeURIComponent );
        object[ pair[0] ] = pair[1];
        return object;
      }, {} );

      return params[ key ];
  }

  function setQueryString( key, value ) {
    var hash = (
      window.location.origin +
      window.location.pathname +
      '?' + [ key, value ].map( encodeURIComponent ).join( '=' )
    );

    window.history.replaceState( '', '', hash );
  }

  function reargMethod( key ) {
    return function() {
      var args = arguments;

      return function( geometry ) {
        geometry[ key ].apply( geometry, args );
      }
    };
  }

  var geometryMethods = [
    'rotateX',
    'rotateY',
    'rotateZ',
    'translate',
    'scale'
  ];

  var shorthandGeometryMethods = [ 'rx', 'ry', 'rz', 't', 's' ];

  var reargGeometryMethods = geometryMethods.reduce(function( fns, key ) {
    fns.push( reargMethod( key ) );
    return fns;
  }, [] );

  function onInput( event ) {
    try {
      var args = {
        keys: [ '_' ]
          .concat( geometryMethods )
          .concat( shorthandGeometryMethods ),
        values: [ createBoxGeometry ]
          .concat( reargGeometryMethods )
          .concat( reargGeometryMethods )
      };

      var fn = new Function( args.keys, event.target.value );

      var _geometries = fn.apply( undefined, args.values );
      var _geometry = mergeGeometries( _geometries );
      updateGeometry( _geometry );

      setGeometry( _geometry );
      createWireframe( mesh );
      render();

      setQueryString( 'commands', event.target.value.trim() );

      event.target.setCustomValidity( '' );
    } catch ( error ) {
      event.target.setCustomValidity( 'Invalid function' );
    }
  }

  function init() {
    container = document.createElement( 'div' );
    document.body.appendChild( container );

    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    container.appendChild( renderer.domElement );

    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight );
    camera.position.set( 0, 0, 8 );

    var controls = new THREE.OrbitControls( camera, renderer.domElement );
    controls.addEventListener( 'change', render );

    scene.add( new THREE.AmbientLight( '#333' ) );

    var light = new THREE.DirectionalLight();
    light.position.set( 0, 8, 8 );
    scene.add( light );

    var axisHelper = new THREE.AxisHelper();
    scene.add( axisHelper );

    var gridHelper = new THREE.GridHelper( 4, 0.4 );
    gridHelper.position.y = -2;
    gridHelper.material.opacity = 0.5;
    gridHelper.material.transparent = true;
    scene.add( gridHelper );

    geometry = new THREE.BoxGeometry( 1, 1, 1 );
    material = new THREE.MeshStandardMaterial({
      shading: THREE.FlatShading,
      transparent: true,
      opacity: 0.95
    });
    mesh = new THREE.Mesh( geometry, material );
    scene.add( mesh );

    var textarea = document.getElementById( 'textarea-commands' );
    createNumericInput( textarea );
    textarea.addEventListener( 'input', onInput );
    // Disable OrbitControls while textarea is focused.
    textarea.addEventListener( 'keydown', function( event ) {
      event.stopPropagation();
    });

    textarea.value = getQueryParam( 'commands' ) || '';
    textarea.dispatchEvent( new Event( 'input' ) );
  }

  function render() {
    renderer.render( scene, camera );
  }

  init();
  render();

  window.addEventListener( 'resize', function() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );
    render();
  });

})();
<commit_msg>lathe[cuboid]: Support single geometry values and add default.<commit_after>/* global THREE, createNumericInput, remove updateGeometry, translateBoxVertices */
(function() {
  'use strict';

  var container;

  var scene, camera, renderer;

  var geometry, material, mesh;
  var wireframe;

  function setGeometry( _geometry ) {
    geometry = _geometry;
    mesh.geometry = geometry;
    mesh.needsUpdate = true;
  }

  function createBoxGeometry( dimensions, transformFn, vectors ) {
    var geometry = new THREE.BoxGeometry( dimensions[0], dimensions[1], dimensions[2] );

    if ( typeof vectors === 'object' ) {
      translateBoxVertices( geometry, vectors );
    }

    if ( typeof transformFn === 'function' ) {
      transformFn( geometry );
    } else if ( Array.isArray( transformFn ) ) {
      transformFn.forEach(function( transformFn ) {
        transformFn( geometry );
      });
    }

    return geometry;
  }

  function createWireframe() {
    remove( wireframe );
    wireframe = new THREE.WireframeHelper( mesh );
    scene.add( wireframe );
  }

  function mergeGeometries( geometries ) {
    if ( !Array.isArray( geometries ) ) {
      return geometries;
    }

    return geometries.reduce(function( a, b ) {
      a.merge( b );
      return a;
    })
  }

  function getQueryParam( key ) {
    var params = window.location.search
      .slice( 1 )
      .split( '&' )
      .reduce(function( object, pair ) {
        pair = pair.split( '=' ).map( decodeURIComponent );
        object[ pair[0] ] = pair[1];
        return object;
      }, {} );

      return params[ key ];
  }

  function setQueryString( key, value ) {
    var hash = (
      window.location.origin +
      window.location.pathname +
      '?' + [ key, value ].map( encodeURIComponent ).join( '=' )
    );

    window.history.replaceState( '', '', hash );
  }

  function reargMethod( key ) {
    return function() {
      var args = arguments;

      return function( geometry ) {
        geometry[ key ].apply( geometry, args );
      }
    };
  }

  var geometryMethods = [
    'rotateX',
    'rotateY',
    'rotateZ',
    'translate',
    'scale'
  ];

  var shorthandGeometryMethods = [ 'rx', 'ry', 'rz', 't', 's' ];

  var reargGeometryMethods = geometryMethods.reduce(function( fns, key ) {
    fns.push( reargMethod( key ) );
    return fns;
  }, [] );

  function onInput( event ) {
    try {
      var args = {
        keys: [ '_' ]
          .concat( geometryMethods )
          .concat( shorthandGeometryMethods ),
        values: [ createBoxGeometry ]
          .concat( reargGeometryMethods )
          .concat( reargGeometryMethods )
      };

      var fn = new Function( args.keys, event.target.value );

      var _geometries = fn.apply( undefined, args.values );
      var _geometry = mergeGeometries( _geometries );
      updateGeometry( _geometry );

      setGeometry( _geometry );
      createWireframe( mesh );
      render();

      setQueryString( 'commands', event.target.value.trim() );

      event.target.setCustomValidity( '' );
    } catch ( error ) {
      event.target.setCustomValidity( 'Invalid function' );
    }
  }

  function init() {
    container = document.createElement( 'div' );
    document.body.appendChild( container );

    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( window.innerWidth, window.innerHeight );
    container.appendChild( renderer.domElement );

    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight );
    camera.position.set( 0, 0, 8 );

    var controls = new THREE.OrbitControls( camera, renderer.domElement );
    controls.addEventListener( 'change', render );

    scene.add( new THREE.AmbientLight( '#333' ) );

    var light = new THREE.DirectionalLight();
    light.position.set( 0, 8, 8 );
    scene.add( light );

    var axisHelper = new THREE.AxisHelper();
    scene.add( axisHelper );

    var gridHelper = new THREE.GridHelper( 4, 0.4 );
    gridHelper.position.y = -2;
    gridHelper.material.opacity = 0.5;
    gridHelper.material.transparent = true;
    scene.add( gridHelper );

    geometry = new THREE.BoxGeometry( 1, 1, 1 );
    material = new THREE.MeshStandardMaterial({
      shading: THREE.FlatShading,
      transparent: true,
      opacity: 0.95
    });
    mesh = new THREE.Mesh( geometry, material );
    scene.add( mesh );

    var textarea = document.getElementById( 'textarea-commands' );
    createNumericInput( textarea );
    textarea.addEventListener( 'input', onInput );
    // Disable OrbitControls while textarea is focused.
    textarea.addEventListener( 'keydown', function( event ) {
      event.stopPropagation();
    });

    textarea.value = getQueryParam( 'commands' ) || 'return _([1, 1, 1])';
    textarea.dispatchEvent( new Event( 'input' ) );
  }

  function render() {
    renderer.render( scene, camera );
  }

  init();
  render();

  window.addEventListener( 'resize', function() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );
    render();
  });

})();
<|endoftext|>


<commit_before>/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2014 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

(function () {

  var module = angular.module('pnc.common.events', [
    'pnc.common.websockets'
  ]);

  module.config([
    'webSocketBusProvider',
    function(webSocketBusProvider) {
      var host = window.location.host; // 'localhost:8080'
      webSocketBusProvider.newEndpoint(
        'ws://' + host + '/pnc-rest/ws/build-records/notifications',
        'eventBroadcastingWebSocketListener'
      );
    }
  ]);

  module.run([
    '$log',
    '$rootScope',
    'webSocketBus',
    'eventTypes',
    'BuildRecordDAO',
    'authService',
    'Notifications',
    function($log, $rootScope, webSocketBus, eventTypes, BuildRecordDAO,
             authService, Notifications) {
      var scope = $rootScope.$new();

      //TODO: When backend functionality is available these notifications
      // should only be fired if the userId of the payload matches the
      // current logged in user.

      scope.$on(eventTypes.BUILD_STARTED, function(event, payload) {
        $log.debug('BUILD_STARTED_EVENT: payload=%O, authService.getPncUser=%O, payload.userId=%O', payload, authService.getPncUser(), payload.userId);
        if (authService.getPncUser().id === payload.userId) {
          Notifications.info('Build #' + payload.id + ' in progress');
        }
      });

      // Notify user when builds finish.
      scope.$on(eventTypes.BUILD_FINISHED, function(event, payload) {
        if (authService.getPncUser().id === payload.userId) {
          if(payload.buildStatus === 'REJECTED') {
            Notifications.warn('Build #' + payload.id + ' rejected.');
          } else {
            BuildRecordDAO.get({recordId: payload.id}).$promise.then(
              function (result) {
                if (result.status === 'SUCCESS') {
                  Notifications.success('Build #' + payload.id + ' completed');
                } else {
                  Notifications.warn('Build #' + payload.id + ' failed');
                }
              }
            );
          }
        }
      });

    }
  ]);

})();
<commit_msg>Managed the system_error more gracefully when a triggered build fails to start on the server (no more 404 error)<commit_after>/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2014 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

(function () {

  var module = angular.module('pnc.common.events', [
    'pnc.common.websockets'
  ]);

  module.config([
    'webSocketBusProvider',
    function(webSocketBusProvider) {
      var host = window.location.host; // 'localhost:8080'
      webSocketBusProvider.newEndpoint(
        'ws://' + host + '/pnc-rest/ws/build-records/notifications',
        'eventBroadcastingWebSocketListener'
      );
    }
  ]);

  module.run([
    '$log',
    '$rootScope',
    'webSocketBus',
    'eventTypes',
    'BuildRecordDAO',
    'authService',
    'Notifications',
    function($log, $rootScope, webSocketBus, eventTypes, BuildRecordDAO,
             authService, Notifications) {
      var scope = $rootScope.$new();

      //TODO: When backend functionality is available these notifications
      // should only be fired if the userId of the payload matches the
      // current logged in user.

      scope.$on(eventTypes.BUILD_STARTED, function(event, payload) {
        $log.debug('BUILD_STARTED_EVENT: payload=%O, authService.getPncUser=%O, payload.userId=%O', payload, authService.getPncUser(), payload.userId);
        if (authService.getPncUser().id === payload.userId) {
          Notifications.info('Build #' + payload.id + ' in progress');
        }
      });

      // Notify user when builds finish
      // (see events-services.js for the conversion
      // between server and client BuildStatus)
      scope.$on(eventTypes.BUILD_FINISHED, function(event, payload) {
        if (authService.getPncUser().id === payload.userId) {
          if (payload.buildStatus === 'REJECTED') {
            Notifications.warn('Build #' + payload.id + ' rejected.');
          } else if (payload.buildStatus === 'SYSTEM_ERROR') {
            Notifications.error('A system error prevented the Build #' + payload.id + ' from starting.');
          } else {
            BuildRecordDAO.get({recordId: payload.id}).$promise.then(
              function (result) {
                if (result.status === 'SUCCESS') {
                  Notifications.success('Build #' + payload.id + ' completed');
                } else {
                  Notifications.warn('Build #' + payload.id + ' failed');
                }
              }
            );
          }
        }
      });

    }
  ]);

})();
<|endoftext|>