<commit_before>'use strict'
var _                    = require('lodash');
var webpack              = require('webpack');
var path                 = require('path');
var fs                   = require('fs');

/**
*  This module creates a new configuration for webpack,
*  Adds hot module replacement entry, source maps, react and react-dom as externals
*/
class Reconfigure {

	constructor( options ) {
    	options               = options || {};
		this.webpackConfigFile = options.configFile || "";
		this.componentsPath    = options.componentsPath || "";
		this.isProd            = options.productionMode ? options.productionMode : process.env.NODE_ENV == 'prod';
		this.webpackConfig     = require(this.webpackConfigFile);
	}

	addDefaultConfiguration () {
		//
		// ======== the default configuration =======
		//
		var defaultConfig = {
			output: {
				path: "/",
				publicPath: "/" // used to prefix json updates
			},
			devtool: 'source-map',
			plugins: [],
			externals: {},
			module: {}
		};

		if ( this.isProd )
			delete defaultConfig.devtool;

		var original = _.cloneDeep ( this.webpackConfig );
		return _.defaultsDeep( {}, original, defaultConfig );
	}

	/**
	* Prepends a new main to every entry in the config
	*/
	prependEntry( config, newEntry ) {

		var config = _.cloneDeep( config );

		var addHmr = function( entry ) {
			if ( typeof entry == 'string' ) {
				entry = [ entry ];
			}
			entry = [ newEntry ].concat ( entry );
			return entry;
		}

		if ( !config.entry  ) {
			config.entry = newEntry;
		} else if ( Array.isArray( config.entry) ) {
			config.entry = addHmr( config.entry );
		} else if ( typeof config.entry == 'object' ) {
			config.entry = _.mapValues( config.entry, addHmr );
		} else {
			config.entry = addHmr ( config.entry );
		}

		return config;
	}

	addReact( config, options ) {
		options = options || {};
		var config = _.cloneDeep ( config );
		var externals = options.externals === undefined ? false : options.externals;
		var react     = options.react     === undefined ? false : options.react;
		var reactDom  = options.reactDom  === undefined ? false : options.reactDom;
		var noparse   = options.noparse   === undefined ? false : options.noparse;

		if ( externals ) {
			config.externals['react-dom'] = 'ReactDOM';
			config.externals['react']     = 'React';
		}
		var testExpr = /.*dist.*\.js$/;
		//testExpr = /.*\.min\.js$/;

		if ( noparse ) {
			config.noParse                = testExpr;

			config.module.loaders = config.module.loaders || [];
			config.module.loaders.push({
				test  : testExpr,
				loader: "imports?define=>false,exports=>false"
			});
		}

		if ( reactDom ) {
			//var reactDomPath = require.resolve('react-dom/dist/react-dom.min.js');
			var reactDomPath = require.resolve('react-dom/dist/react-dom.js');
			config = this.prependEntry( config, reactDomPath );
		}
		if ( react ) {
			//var reactPath = require.resolve('react/dist/react.min.js');
			var reactPath = require.resolve('react/dist/react.js');
			config = this.prependEntry( config, reactPath );
		}

		return config;

	}

	addLoaders ( config ) {
		var config = _.cloneDeep ( config );

		if ( typeof config.module != "object" ) config.module = {};
		if ( !Array.isArray(config.module.loaders)) config.module.loaders = [];

		config.module.loaders = config.module.loaders || [];
		config.module.loaders.push({
			test: /\.jsx$/,
			exclude: /node_modules/,
			loader: 'babel',
			query: {
				presets: ['babel-preset-react', 'babel-preset-es2015'].map(require.resolve)
			}
		});

		return config;
	}

	addHmrMiddleware ( config ) {
		var config = _.cloneDeep ( config );

		if ( !Array.isArray(config.plugins) ) {
			config.plugins = [];
		}

		// add HMR plugin (server side)
		config.plugins.unshift(
			//new webpack.optimize.OccurenceOrderPlugin(),
			new webpack.HotModuleReplacementPlugin(),
			new webpack.NoErrorsPlugin()
		);

		// add HRM entry point (client side)
		var hmrPath = require.resolve('webpack-hot-middleware/client.js');
		config = this.prependEntry ( config, hmrPath );

		return config;
	}

	addUglify( config ) {
		var config = _.cloneDeep( config );

		if ( !Array.isArray(config.plugins) ) {
			config.plugins = [];
		}

		config.plugins.push(new webpack.optimize.UglifyJsPlugin({
			compress: {
				warnings: false
			}
		}));

		config.plugins.push(new webpack.DefinePlugin({
		    'process.env': {
		      'NODE_ENV': JSON.stringify('production')
		    }
		}));

		return config;

	}
}

Reconfigure.createEntryScript = function(options) {
    var files = fs.readdirSync(options.componentsPath);
    files = _(files)
        .filter(val => val.endsWith(".jsx")                )
        .filter(val => val.indexOf(".startup.jsx") == -1   )
        .map(   val => val.substr(0, val.indexOf(".jsx"))  )
        .value();

    var loadFiles = files.map(val => `import ${val} from './${val}.jsx';`).join("\n");
    var listFiles = files.map(val => `'${val}': ${val}`).join(",");

    var content = `
    // entry point script
    import React from 'react';
    import { render } from 'react-dom';
    \n${loadFiles}
    var compList = {${listFiles}}
    var doRender = function() {
        var INIT = window.INIT || {};
        var props         = INIT.initialProps  || null;
        var rootComponent = INIT.rootComponent || "MainComponent";
        var targetEl      = document.getElementById("main");

        console.log("rendering", rootComponent);

        if ( targetEl ) {
            render(
                React.createElement( compList[rootComponent], props),
                targetEl
            );
        }
    }

    doRender();

    if ( module.hot ) {
        module.hot.accept(function() {
            doRender();
        });
    }
    // end entry point script`;

    //console.log("entry file:", content);

    //var tempFile = temp.openSync({suffix: ".jsx"});
    //fs.writeSync( tempFile.fd, content );
    //return tempFile.path;

    var tempFile = path.join(options.componentsPath, ".startup.jsx");
    fs.writeFileSync( tempFile, content );
    return tempFile;
}

Reconfigure.generateConfig = function(options) {
	var isProd            = options.productionMode ? options.productionMode : process.env.NODE_ENV == 'production';
	if( options.generateEntry === undefined ) {
		options.generateEntry = true;
	}

	//
	// Generate the new configuration
	//

	var reconfigure = new Reconfigure( options );
	var config      = reconfigure.addDefaultConfiguration();

	if ( isProd ) {
		config      = reconfigure.addUglify( config );
	} else {
		config      = reconfigure.addHmrMiddleware( config );
	}

	// adding babel loaders
	config = reconfigure.addLoaders( config );

	// adding generated entry point
	if ( options.generateEntry ) {
		var entryFile   = Reconfigure.createEntryScript( options );
		config          = reconfigure.prependEntry(config, entryFile);
	}

	//
	// adding libraries
	//
	var defaultInternals = {
		externals: false,
		noparse: false,
		react: false,
		reactDom: false
	};
	var internalOptions = options.internals || defaultInternals;
	config              = reconfigure.addReact ( config, internalOptions);

	// debuging
	//console.log("webpack config:", config);
	//console.log("loaders:", config.module.loaders[1].query.presets);

	return config;
}

module.exports = Reconfigure;

<commit_msg>by default do full reload to fix material-ui not reloading<commit_after>'use strict'
var _                    = require('lodash');
var webpack              = require('webpack');
var path                 = require('path');
var fs                   = require('fs');

/**
*  This module creates a new configuration for webpack,
*  Adds hot module replacement entry, source maps, react and react-dom as externals
*/
class Reconfigure {

	constructor( options ) {
    	options               = options || {};
		this.webpackConfigFile = options.configFile || "";
		this.componentsPath    = options.componentsPath || "";
		this.isProd            = options.productionMode ? options.productionMode : process.env.NODE_ENV == 'prod';
		this.webpackConfig     = require(this.webpackConfigFile);
	}

	addDefaultConfiguration () {
		//
		// ======== the default configuration =======
		//
		var defaultConfig = {
			output: {
				path: "/",
				publicPath: "/" // used to prefix json updates
			},
			devtool: 'source-map',
			plugins: [],
			externals: {},
			module: {}
		};

		if ( this.isProd )
			delete defaultConfig.devtool;

		var original = _.cloneDeep ( this.webpackConfig );
		return _.defaultsDeep( {}, original, defaultConfig );
	}

	/**
	* Prepends a new main to every entry in the config
	*/
	prependEntry( config, newEntry ) {

		var config = _.cloneDeep( config );

		var addHmr = function( entry ) {
			if ( typeof entry == 'string' ) {
				entry = [ entry ];
			}
			entry = [ newEntry ].concat ( entry );
			return entry;
		}

		if ( !config.entry  ) {
			config.entry = newEntry;
		} else if ( Array.isArray( config.entry) ) {
			config.entry = addHmr( config.entry );
		} else if ( typeof config.entry == 'object' ) {
			config.entry = _.mapValues( config.entry, addHmr );
		} else {
			config.entry = addHmr ( config.entry );
		}

		return config;
	}

	addReact( config, options ) {
		options = options || {};
		var config = _.cloneDeep ( config );
		var externals = options.externals === undefined ? false : options.externals;
		var react     = options.react     === undefined ? false : options.react;
		var reactDom  = options.reactDom  === undefined ? false : options.reactDom;
		var noparse   = options.noparse   === undefined ? false : options.noparse;

		if ( externals ) {
			config.externals['react-dom'] = 'ReactDOM';
			config.externals['react']     = 'React';
		}
		var testExpr = /.*dist.*\.js$/;
		//testExpr = /.*\.min\.js$/;

		if ( noparse ) {
			config.noParse                = testExpr;

			config.module.loaders = config.module.loaders || [];
			config.module.loaders.push({
				test  : testExpr,
				loader: "imports?define=>false,exports=>false"
			});
		}

		if ( reactDom ) {
			//var reactDomPath = require.resolve('react-dom/dist/react-dom.min.js');
			var reactDomPath = require.resolve('react-dom/dist/react-dom.js');
			config = this.prependEntry( config, reactDomPath );
		}
		if ( react ) {
			//var reactPath = require.resolve('react/dist/react.min.js');
			var reactPath = require.resolve('react/dist/react.js');
			config = this.prependEntry( config, reactPath );
		}

		return config;

	}

	addLoaders ( config ) {
		var config = _.cloneDeep ( config );

		if ( typeof config.module != "object" ) config.module = {};
		if ( !Array.isArray(config.module.loaders)) config.module.loaders = [];

		config.module.loaders = config.module.loaders || [];
		config.module.loaders.push({
			test: /\.jsx$/,
			exclude: /node_modules/,
			loader: 'babel',
			query: {
				presets: ['babel-preset-react', 'babel-preset-es2015'].map(require.resolve)
			}
		});

		return config;
	}

	addHmrMiddleware ( config ) {
		var config = _.cloneDeep ( config );

		if ( !Array.isArray(config.plugins) ) {
			config.plugins = [];
		}

		// add HMR plugin (server side)
		config.plugins.unshift(
			//new webpack.optimize.OccurenceOrderPlugin(),
			new webpack.HotModuleReplacementPlugin(),
			new webpack.NoErrorsPlugin()
		);

		// add HRM entry point (client side)
		var hmrPath = require.resolve('webpack-hot-middleware/client.js');
		config = this.prependEntry ( config, hmrPath );

		return config;
	}

	addUglify( config ) {
		var config = _.cloneDeep( config );

		if ( !Array.isArray(config.plugins) ) {
			config.plugins = [];
		}

		config.plugins.push(new webpack.optimize.UglifyJsPlugin({
			compress: {
				warnings: false
			}
		}));

		config.plugins.push(new webpack.DefinePlugin({
		    'process.env': {
		      'NODE_ENV': JSON.stringify('production')
		    }
		}));

		return config;

	}
}

Reconfigure.createEntryScript = function(options) {
    var files = fs.readdirSync(options.componentsPath);
    files = _(files)
        .filter(val => val.endsWith(".jsx")                )
        .filter(val => val.indexOf(".startup.jsx") == -1   )
        .map(   val => val.substr(0, val.indexOf(".jsx"))  )
        .value();

    var loadFiles = files.map(val => `import ${val} from './${val}.jsx';`).join("\n");
    var listFiles = files.map(val => `'${val}': ${val}`).join(",");

    var content = `
    // entry point script
    import React from 'react';
    import { render } from 'react-dom';
    \n${loadFiles}
    var compList = {${listFiles}}
    var doRender = function() {
        var INIT = window.INIT || {};
        var props         = INIT.initialProps  || null;
        var rootComponent = INIT.rootComponent || "MainComponent";
        var targetEl      = document.getElementById("main");

        console.log("rendering", rootComponent);

        if ( targetEl ) {
            render(
                React.createElement( compList[rootComponent], props),
                targetEl
            );
        }
    }

    doRender();

    if ( module.hot ) {
        module.hot.accept(function() {
            //doRender();
			window.location.reload();
        });
    }
    // end entry point script`;

    //console.log("entry file:", content);

    //var tempFile = temp.openSync({suffix: ".jsx"});
    //fs.writeSync( tempFile.fd, content );
    //return tempFile.path;

    var tempFile = path.join(options.componentsPath, ".startup.jsx");
    fs.writeFileSync( tempFile, content );
    return tempFile;
}

Reconfigure.generateConfig = function(options) {
	var isProd            = options.productionMode ? options.productionMode : process.env.NODE_ENV == 'production';
	if( options.generateEntry === undefined ) {
		options.generateEntry = true;
	}

	//
	// Generate the new configuration
	//

	var reconfigure = new Reconfigure( options );
	var config      = reconfigure.addDefaultConfiguration();

	if ( isProd ) {
		config      = reconfigure.addUglify( config );
	} else {
		config      = reconfigure.addHmrMiddleware( config );
	}

	// adding babel loaders
	config = reconfigure.addLoaders( config );

	// adding generated entry point
	if ( options.generateEntry ) {
		var entryFile   = Reconfigure.createEntryScript( options );
		config          = reconfigure.prependEntry(config, entryFile);
	}

	//
	// adding libraries
	//
	var defaultInternals = {
		externals: false,
		noparse: false,
		react: false,
		reactDom: false
	};
	var internalOptions = options.internals || defaultInternals;
	config              = reconfigure.addReact ( config, internalOptions);

	// debuging
	//console.log("webpack config:", config);
	//console.log("loaders:", config.module.loaders[1].query.presets);

	return config;
}

module.exports = Reconfigure;

<|endoftext|>


<commit_before>define([
	"dojo/_base/declare",
	"dojo/request",
	"dojo/store/Memory",
	"dojo/store/util/QueryResults",
	"dojo/when", "dojo/_base/lang",
	"dojo/_base/Deferred", "dojo/Stateful",
	"../util/PathJoin"

], function(declare,
			request,
			Memory,
			QueryResults,
			when, lang,
			Deferred, Stateful,
			PathJoin){
	return declare([Memory, Stateful], {
		baseQuery: {},
		idProperty: "pathway_id",
		apiServer: window.App.dataServiceURL,
		state: null,
		genome_ids: null,
		type: "pathway",
		onSetState: function(attr, oldVal, state){
			var ov, nv;
			if(oldVal){
				ov = oldVal.search + oldVal.filter
			}
			if(state){
				nv = state.search + state.filter
			}

			console.log("MEMORY STORE onSetState: ", state, oldVal);
			// if (ov!=nv){
			console.log("clear memory store data");
			this._loaded = false;
			if(this._loadingDeferred){
				console.log("Deleting _loadingDeferred", this._loadingDeferred);
				delete this._loadingDeferred;
			}
			// }
		},
		constructor: function(opts){
			this.init(opts);
		},
		init: function(options){
			options = options || {};
			console.log("PMS Ctor Options: ", options);
			this._loaded = false;
			this.genome_ids = [];
			lang.mixin(this, options);
			this.watch("state", lang.hitch(this, "onSetState"));
			console.log("INIT COMPLETE: ", this)
		},

		query: function(query, opts){
			query = query || {};
			if(this._loaded){
				return this.inherited(arguments);
			}
			else{
				var _self = this;
				var results;
				console.log("Beofre LOAD type: ", this.type);
				console.log("Initiate NON LOADED Query: ", query);
				var qr = QueryResults(when(this.loadData(), function(){
					console.log("Do actual Query Against loadData() data. QR: ", qr);
					results = _self.query(query || {}, opts);
					qr.total = when(results, function(results){
						return results.total || results.length
					});
					return results;
				}));

				return qr;
			}
		},

		get: function(id, opts){
			if(this._loaded){
				return this.inherited(arguments);
			}
			else{
				var _self = this;
				return when(this.loadData(), function(){
					return _self.get(id, options)
				})
			}
		},

		queryTypes: {
			pathway: "&limit(25000)&group((field,pathway_id),(format,simple),(ngroups,true),(limit,1),(facet,true))" +
			"&json(facet," + encodeURIComponent(JSON.stringify({
				stat: {
					field: {
						field: "pathway_id",
						limit: -1,
						facet: {
							genome_count: "unique(genome_id)",
							gene_count: "unique(feature_id)",
							ec_count: "unique(ec_number)",
							genome_ec: "unique(genome_ec)"
						}
					}
				}
			})) + ")",

			ecnumber: "&limit(25000)&group((field,ec_number),(format,simple),(ngroups,true),(limit,1),(facet,true))" +
			"&json(facet," + encodeURIComponent(JSON.stringify({
				stat: {
					field: {
						field: "ec_number",
						limit: -1,
						facet: {
							genome_count: "unique(genome_id)",
							gene_count: "unique(feature_id)",
							ec_count: "unique(ec_number)",
							genome_ec: "unique(genome_ec)"
						}
					}
				}
			})) + ")",
			genes: "&limit(25000)&group((field,feature_id),(format,simple),(ngroups,true),(limit,1),(facet,true))" +
			"&json(facet," + encodeURIComponent(JSON.stringify({
				stat: {
					field: {
						field: "feature_id",
						limit: -1,
						facet: {
							genome_count: "unique(genome_id)",
							gene_count: "unique(feature_id)",
							ec_count: "unique(ec_number)",
							genome_ec: "unique(genome_ec)"
						}
					}
				}
			})) + ")"
		},
		buildQuery: function(){
			var q = [];
			if(this.state){
				if(this.state.search){
					console.log("buildQuery SEARCH: ", this.state.search);

					q.push((this.state.search.charAt(0) == "?") ? this.state.search.substr(1) : this.state.search);
				}else if(this.state.genome_ids){
					q.push("in(genome_id,(" + this.state.genome_ids.map(encodeURIComponent).join(",") + "))");
				}

				if(this.state.hashParams && this.state.hashParams.filter){
					if(this.state.hashParams.filter != "false"){
						q.push(this.state.hashParams.filter);
					}
				}
				if(q.length < 1){
					q = "";
				}
				else if(q.length == 1){
					q = q[0];
				}
				else{
					q = "and(" + q.join(",") + ")";
				}
			}else{
				q = ""
			}
			q = q + this.queryTypes[this.type];

			console.log("End Build Query: ", q);
			return (q.charAt(0) == "?") ? q.substr(1) : q;
		},

		loadData: function(){

			if(this._loadingDeferred){
				return this._loadingDeferred;
			}
			var state = this.state || {};

			if(!state.search || !state.genome_ids || state.genome_ids.length < 1){
				console.log("No Genome IDS, use empty data set for initial store");

				//this is done as a deferred instead of returning an empty array
				//in order to make it happen on the next tick.  Otherwise it
				//in the query() function above, the callback happens before qr exists
				var def = new Deferred();
				setTimeout(lang.hitch(this, function(){
					this.setData([]);
					this._loaded = true;
					def.resolve(true);
				}), 0);
				return def.promise;

			}

			// var lq;

			// if(state && state.genome_ids){
			// 		lq = "&in(genome_id,(" + state.genome_ids.map(encodeURIComponent).join(",") + "))";
			// }

			console.log("QUERY TYPE: ", this.type, this.queryTypes[this.type])
			var q = this.buildQuery();

			var _self = this;
			console.log("Load Data: ", q);
			this._loadingDeferred = when(request.post(PathJoin(this.apiServer, 'pathway') + '/', {
				handleAs: 'json',
				headers: {
					'Accept': "application/solr+json",
					'Content-Type': "application/rqlquery+x-www-form-urlencoded",
					'X-Requested-With': null,
					'Authorization': this.token ? this.token : (window.App.authorizationToken || "")
				},
				data: q

			}), lang.hitch(this, function(response){

				var docs = [];
				var props = {
					"pathway": "pathway_id",
					"ecnumber": "ec_number",
					"genes": 'feature_id'
				};
				console.log("Pathway Base Query Response:", response);
				// console.log("Type: ", this.type, " props[this.type]: ", props[this.type], "res prop: ",  response.grouped[props[this.type]])
				if(response && response.grouped && response.grouped[props[this.type]]){
					var ds = response.grouped[props[this.type]].doclist.docs;
					var buckets = response.facets.stat.buckets;
					var map = {};
					buckets.forEach(function(b){
						map[b["val"]] = b;
						delete b["val"];
					});

					docs = ds.map(function(doc){
						var p = props[this.type];
						var pv = doc[p];
						// console.log("p: ", p, "pv: ", pv, " mapped[pv]", map[pv]);
						lang.mixin(doc, map[pv] || {});
						if(doc.genome_ec && doc.genome_count){
							doc.ec_cons = (doc.genome_ec / doc.genome_count / doc.ec_count * 100).toFixed(2);
						}else{
							doc.ec_cons = 0;
						}
						if(doc.gene_count && doc.genome_count){
							doc.gene_cons = (doc.gene_count / doc.genome_count / doc.ec_count).toFixed(2);
						}else{
							doc.gene_cons = 0;
						}
						return doc;
					}, this);
					console.log("doc count: ", docs.length);

					_self.setData(docs);
					_self._loaded = true;
					return true;

				}else{
					console.log("Unable to Process Response: ", response);
					_self.setData([]);
					_self._loaded = true;
					return false;
				}
			}), lang.hitch(this, function(err){
				console.log("Error Loading Data: ", err);
				_self.setData([]);
				_self._loaded = true;
				return err;
			}));
			return this._loadingDeferred;
		}
	})
});
<commit_msg>remove limit from pathway requests<commit_after>define([
	"dojo/_base/declare",
	"dojo/request",
	"dojo/store/Memory",
	"dojo/store/util/QueryResults",
	"dojo/when", "dojo/_base/lang",
	"dojo/_base/Deferred", "dojo/Stateful",
	"../util/PathJoin"

], function(declare,
			request,
			Memory,
			QueryResults,
			when, lang,
			Deferred, Stateful,
			PathJoin){
	return declare([Memory, Stateful], {
		baseQuery: {},
		idProperty: "pathway_id",
		apiServer: window.App.dataServiceURL,
		state: null,
		genome_ids: null,
		type: "pathway",
		onSetState: function(attr, oldVal, state){
			var ov, nv;
			if(oldVal){
				ov = oldVal.search + oldVal.filter
			}
			if(state){
				nv = state.search + state.filter
			}

			console.log("MEMORY STORE onSetState: ", state, oldVal);
			// if (ov!=nv){
			console.log("clear memory store data");
			this._loaded = false;
			if(this._loadingDeferred){
				console.log("Deleting _loadingDeferred", this._loadingDeferred);
				delete this._loadingDeferred;
			}
			// }
		},
		constructor: function(opts){
			this.init(opts);
		},
		init: function(options){
			options = options || {};
			console.log("PMS Ctor Options: ", options);
			this._loaded = false;
			this.genome_ids = [];
			lang.mixin(this, options);
			this.watch("state", lang.hitch(this, "onSetState"));
			console.log("INIT COMPLETE: ", this)
		},

		query: function(query, opts){
			query = query || {};
			if(this._loaded){
				return this.inherited(arguments);
			}
			else{
				var _self = this;
				var results;
				console.log("Beofre LOAD type: ", this.type);
				console.log("Initiate NON LOADED Query: ", query);
				var qr = QueryResults(when(this.loadData(), function(){
					console.log("Do actual Query Against loadData() data. QR: ", qr);
					results = _self.query(query || {}, opts);
					qr.total = when(results, function(results){
						return results.total || results.length
					});
					return results;
				}));

				return qr;
			}
		},

		get: function(id, opts){
			if(this._loaded){
				return this.inherited(arguments);
			}
			else{
				var _self = this;
				return when(this.loadData(), function(){
					return _self.get(id, options)
				})
			}
		},

		queryTypes: {
			pathway: "&group((field,pathway_id),(format,simple),(ngroups,true),(limit,1),(facet,true))" +
			"&json(facet," + encodeURIComponent(JSON.stringify({
				stat: {
					field: {
						field: "pathway_id",
						limit: -1,
						facet: {
							genome_count: "unique(genome_id)",
							gene_count: "unique(feature_id)",
							ec_count: "unique(ec_number)",
							genome_ec: "unique(genome_ec)"
						}
					}
				}
			})) + ")",

			ecnumber: "&group((field,ec_number),(format,simple),(ngroups,true),(limit,1),(facet,true))" +
			"&json(facet," + encodeURIComponent(JSON.stringify({
				stat: {
					field: {
						field: "ec_number",
						limit: -1,
						facet: {
							genome_count: "unique(genome_id)",
							gene_count: "unique(feature_id)",
							ec_count: "unique(ec_number)",
							genome_ec: "unique(genome_ec)"
						}
					}
				}
			})) + ")",
			genes: "&group((field,feature_id),(format,simple),(ngroups,true),(limit,1),(facet,true))" +
			"&json(facet," + encodeURIComponent(JSON.stringify({
				stat: {
					field: {
						field: "feature_id",
						limit: -1,
						facet: {
							genome_count: "unique(genome_id)",
							gene_count: "unique(feature_id)",
							ec_count: "unique(ec_number)",
							genome_ec: "unique(genome_ec)"
						}
					}
				}
			})) + ")"
		},
		buildQuery: function(){
			var q = [];
			if(this.state){
				if(this.state.search){
					console.log("buildQuery SEARCH: ", this.state.search);

					q.push((this.state.search.charAt(0) == "?") ? this.state.search.substr(1) : this.state.search);
				}else if(this.state.genome_ids){
					q.push("in(genome_id,(" + this.state.genome_ids.map(encodeURIComponent).join(",") + "))");
				}

				if(this.state.hashParams && this.state.hashParams.filter){
					if(this.state.hashParams.filter != "false"){
						q.push(this.state.hashParams.filter);
					}
				}
				if(q.length < 1){
					q = "";
				}
				else if(q.length == 1){
					q = q[0];
				}
				else{
					q = "and(" + q.join(",") + ")";
				}
			}else{
				q = ""
			}
			q = q + this.queryTypes[this.type];

			console.log("End Build Query: ", q);
			return (q.charAt(0) == "?") ? q.substr(1) : q;
		},

		loadData: function(){

			if(this._loadingDeferred){
				return this._loadingDeferred;
			}
			var state = this.state || {};

			if(!state.search || !state.genome_ids || state.genome_ids.length < 1){
				console.log("No Genome IDS, use empty data set for initial store");

				//this is done as a deferred instead of returning an empty array
				//in order to make it happen on the next tick.  Otherwise it
				//in the query() function above, the callback happens before qr exists
				var def = new Deferred();
				setTimeout(lang.hitch(this, function(){
					this.setData([]);
					this._loaded = true;
					def.resolve(true);
				}), 0);
				return def.promise;

			}

			// var lq;

			// if(state && state.genome_ids){
			// 		lq = "&in(genome_id,(" + state.genome_ids.map(encodeURIComponent).join(",") + "))";
			// }

			console.log("QUERY TYPE: ", this.type, this.queryTypes[this.type])
			var q = this.buildQuery();

			var _self = this;
			console.log("Load Data: ", q);
			this._loadingDeferred = when(request.post(PathJoin(this.apiServer, 'pathway') + '/', {
				handleAs: 'json',
				headers: {
					'Accept': "application/solr+json",
					'Content-Type': "application/rqlquery+x-www-form-urlencoded",
					'X-Requested-With': null,
					'Authorization': this.token ? this.token : (window.App.authorizationToken || "")
				},
				data: q

			}), lang.hitch(this, function(response){

				var docs = [];
				var props = {
					"pathway": "pathway_id",
					"ecnumber": "ec_number",
					"genes": 'feature_id'
				};
				console.log("Pathway Base Query Response:", response);
				// console.log("Type: ", this.type, " props[this.type]: ", props[this.type], "res prop: ",  response.grouped[props[this.type]])
				if(response && response.grouped && response.grouped[props[this.type]]){
					var ds = response.grouped[props[this.type]].doclist.docs;
					var buckets = response.facets.stat.buckets;
					var map = {};
					buckets.forEach(function(b){
						map[b["val"]] = b;
						delete b["val"];
					});

					docs = ds.map(function(doc){
						var p = props[this.type];
						var pv = doc[p];
						// console.log("p: ", p, "pv: ", pv, " mapped[pv]", map[pv]);
						lang.mixin(doc, map[pv] || {});
						if(doc.genome_ec && doc.genome_count){
							doc.ec_cons = (doc.genome_ec / doc.genome_count / doc.ec_count * 100).toFixed(2);
						}else{
							doc.ec_cons = 0;
						}
						if(doc.gene_count && doc.genome_count){
							doc.gene_cons = (doc.gene_count / doc.genome_count / doc.ec_count).toFixed(2);
						}else{
							doc.gene_cons = 0;
						}
						return doc;
					}, this);
					console.log("doc count: ", docs.length);

					_self.setData(docs);
					_self._loaded = true;
					return true;

				}else{
					console.log("Unable to Process Response: ", response);
					_self.setData([]);
					_self._loaded = true;
					return false;
				}
			}), lang.hitch(this, function(err){
				console.log("Error Loading Data: ", err);
				_self.setData([]);
				_self._loaded = true;
				return err;
			}));
			return this._loadingDeferred;
		}
	})
});
<|endoftext|>


<commit_before>
define(['app/app', 'text!templates/letterGradeGraphics.hbs', 'text!templates/letterGradeGraphics.hbs', 'text!templates/gradeSchema.hbs', 'chart'], function(App, chartTemplate, template1, template2, chart) {
    var GradeSchema = App.Backbone.Model;//.extend({
    //defaults: {
    //    aMin: 90,
    //    bMin: 80,
    //    cMin: 70,
    //    dMin: 60
    //}
    //});
    //var GraphArray = findGraphArray();
    var LetterGradeGraphView = App.Mn.ItemView.extend({
        model : App.Course,
        template : App.Handlebars.compile(template1),
        modelEvents : {
            "change" : "onShow"
        },
        //graphTitle: "A",
        onShow : function () {
            if (!this.barCtx) {
                return
            }
            var gradeArray = this.model.findGraphArray();
            var gradeData = {
                labels : gradeArray[0],
                datasets: [
                    {
                        label : "A",
                        fillColor: this.model.get('aColor')[0],
                        strokeColor: this.model.get('aColor')[1],
                        highlightFill: this.model.get('aColor')[2],
                        highlightStroke: this.model.get('aColor')[3],
                        data: gradeArray[1]

                    }
                ]
            }
            this.barChart = new Chart(this.barCtx).Bar(gradeData, NULL);
        },
        onAttach : function (){
            this.barCtx = this.$el('.barChart')[0].getContext('2d');
        }
    });

    //var data = {
    //    labels: gradeArray[0],
    //    datasets: [
    //        {
    //            label: "My First dataset",
    //            fillColor: green[0],
    //            strokeColor: green[1],
    //            highlightFill: green[2],
    //            highlightStroke: green[3],
    //            data: gradeArray[1]
    //        }
    //    ]
    //};

    var model = new App.Backbone.Model({
        findGraphArray : function() {
            return [[50, 55, 60, 65, 68, 70, 71, 75, 78, 79, 80, 83, 88, 89, 90, 91, 94], [1, 2, 3, 1, 2, 1, 1, 2, 3, 4, 1, 2, 3, 4, 1, 3, 4]];
        },
        dColor :  ["rgba(255,0,0,0.5)", "rgba(255,0,0,0.6)", "rgba(255,0,0,0.7)", "rgba(220,220,220,0.7)"],
        fColor :  ["rgba(255,0,0,0.8)", "rgba(255,0,0,0.8)", "rgba(255,0,0,0.9)", "rgba(220,220,220,1)"],
        cColor : ["rgba(255, 165, 0, 0.5)", "rgba(255, 165, 0, 0.8)", "rgba(255, 165, 0, 0.75)", "rgba(255, 165, 0, 1)"],
        bColor :  ["rgba(255, 255, 0,0.5)", "rgba(255, 255, 0,0.8)", "rgba(255, 255, 0,0.75)", "rgba(255, 255, 0,1)"],
        aColor : ["rgba(0,255,0,0.5)", "rgba(0,255,0,0.8)", "rgba(0,255,0,0.75)", "rgba(0,255,0,1)"],
        aMin: 90,
        bMin: 80,
        cMin: 70,
        dMin: 60
    });
        //= new App.Backbone.Collecti
    //})
    var GradeSchemaView = App.Mn.ItemView.extend({
        model: GradeSchema,
        template : App.Handlebars.compile(template2),
        ui: {
            "aMin" : '.aMinInput',
            "bMin" : '.bMinInput',
            "cMin" : '.cMinInput',
            "dMin" : '.dMinInput',
            "aOut" : '.aMinOutput',
            "bOut" : '.bMinOutput',
            "cOut" : '.cMinOutput',
            "dOut" : '.dMinOutput'

        },
        modelEvents: {
            "change" : "onShow"
        },
        onShow: function() {
            this.ui.aMin.val(this.model.get('aMin'));
            this.ui.bMin.val(this.model.get('bMin'));
            this.ui.cMin.val(this.model.get('cMin'));
            this.ui.dMin.val(this.model.get('dMin'));
            //this.ui.aOut.html(this.model.get('aMin'));
            //this.ui.bOut.html(this.model.get('bMin'));
            //this.ui.cOut.html(this.model.get('cMin'));
            //this.ui.dOut.html(this.model.get('dMin'));
        },
        events: {
            "change @ui.aMin" : "updateAMin",
            "change @ui.bMin" : "updateBMin",
            "change @ui.cMin" : "updateCMin",
            "change @ui.dMin" : "updateDMin"
        },
        updateModel : function(modelString, selector, domEvent) {
            var arg = {};
            arg[modelString] = this.ui[selector];
            this.model.set(arg);
        },
        initalize: function() {
            this.updateAMin =  App._.partial(this.updateModel, "aMin");
            this.updateBMin =  App._.partial(this.updateModel, "bMin");
            this.updateCMin =  App._.partial(this.updateModel, "cMin");
            this.updateDMin =  App._.partial(this.updateModel, "dMin");

        }
    });

    var GraphView = App.Mn.LayoutView.extend({
        template : chartTemplate,
        regions : {
            graph : ".chartGraphics",
            schema : ".scheme"
        }
    });

    App.Router.route(("charts"), "histogram", function() {
        //var layout = App.show(new App.StandardLayoutView());
        var graphView = new GraphView();
        graphView.getRegion("graph").show(new GradeSchemaView({
            model : model
        }));
        graphView.getRegion("schema").show(new GradeSchemaView({
            model : model
        }));

        //App.show(new GradeSchemaView({
        //    model : model
        //}));
        //layout.getRegion('main').show(new App.Marionette.ItemView({
        //    template: template,
        //    updatePieChart: function() {
        //
        //    }
        //}))
    })
});<commit_msg>Updated chart.js<commit_after>
define(['app/app', 'text!templates/charts.hbs', 'text!templates/letterGradeGraphics.hbs', 'text!templates/gradeSchema.hbs', 'chart'], function(App, chartTemplate, template1, template2, chart) {
    var GradeSchema = App.Backbone.Model;//.extend({
    //defaults: {
    //    aMin: 90,
    //    bMin: 80,
    //    cMin: 70,
    //    dMin: 60
    //}
    //});
    //var GraphArray = findGraphArray();
    var LetterGradeGraphView = App.Mn.ItemView.extend({
        model : App.Course,
        template : App.Handlebars.compile(template1),
        modelEvents : {
            "change" : "onShow"
        },
        //graphTitle: "A",
        onShow : function () {
            if (!this.barCtx) {
                return
            }
            var gradeArray = this.model.findGraphArray();
            var gradeData = {
                labels : gradeArray[0],
                datasets: [
                    {
                        label : "A",
                        fillColor: this.model.get('aColor')[0],
                        strokeColor: this.model.get('aColor')[1],
                        highlightFill: this.model.get('aColor')[2],
                        highlightStroke: this.model.get('aColor')[3],
                        data: gradeArray[1]

                    }
                ]
            }
            this.barChart = new Chart(this.barCtx).Bar(gradeData, NULL);
        },
        onAttach : function (){
            this.barCtx = this.$el('.barChart')[0].getContext('2d');
        }
    });

    //var data = {
    //    labels: gradeArray[0],
    //    datasets: [
    //        {
    //            label: "My First dataset",
    //            fillColor: green[0],
    //            strokeColor: green[1],
    //            highlightFill: green[2],
    //            highlightStroke: green[3],
    //            data: gradeArray[1]
    //        }
    //    ]
    //};

    var model = new App.Backbone.Model({
        findGraphArray : function() {
            return [[50, 55, 60, 65, 68, 70, 71, 75, 78, 79, 80, 83, 88, 89, 90, 91, 94], [1, 2, 3, 1, 2, 1, 1, 2, 3, 4, 1, 2, 3, 4, 1, 3, 4]];
        },
        dColor :  ["rgba(255,0,0,0.5)", "rgba(255,0,0,0.6)", "rgba(255,0,0,0.7)", "rgba(220,220,220,0.7)"],
        fColor :  ["rgba(255,0,0,0.8)", "rgba(255,0,0,0.8)", "rgba(255,0,0,0.9)", "rgba(220,220,220,1)"],
        cColor : ["rgba(255, 165, 0, 0.5)", "rgba(255, 165, 0, 0.8)", "rgba(255, 165, 0, 0.75)", "rgba(255, 165, 0, 1)"],
        bColor :  ["rgba(255, 255, 0,0.5)", "rgba(255, 255, 0,0.8)", "rgba(255, 255, 0,0.75)", "rgba(255, 255, 0,1)"],
        aColor : ["rgba(0,255,0,0.5)", "rgba(0,255,0,0.8)", "rgba(0,255,0,0.75)", "rgba(0,255,0,1)"],
        aMin: 90,
        bMin: 80,
        cMin: 70,
        dMin: 60
    });
        //= new App.Backbone.Collecti
    //})
    var GradeSchemaView = App.Mn.ItemView.extend({
        model: GradeSchema,
        template : App.Handlebars.compile(template2),
        ui: {
            "aMin" : '.aMinInput',
            "bMin" : '.bMinInput',
            "cMin" : '.cMinInput',
            "dMin" : '.dMinInput',
            "aOut" : '.aMinOutput',
            "bOut" : '.bMinOutput',
            "cOut" : '.cMinOutput',
            "dOut" : '.dMinOutput'

        },
        modelEvents: {
            "change" : "onShow"
        },
        onShow: function() {
            this.ui.aMin.val(this.model.get('aMin'));
            this.ui.bMin.val(this.model.get('bMin'));
            this.ui.cMin.val(this.model.get('cMin'));
            this.ui.dMin.val(this.model.get('dMin'));
            //this.ui.aOut.html(this.model.get('aMin'));
            //this.ui.bOut.html(this.model.get('bMin'));
            //this.ui.cOut.html(this.model.get('cMin'));
            //this.ui.dOut.html(this.model.get('dMin'));
        },
        events: {
            "change @ui.aMin" : "updateAMin",
            "change @ui.bMin" : "updateBMin",
            "change @ui.cMin" : "updateCMin",
            "change @ui.dMin" : "updateDMin"
        },
        updateModel : function(modelString, selector, domEvent) {
            var arg = {};
            arg[modelString] = this.ui[selector];
            this.model.set(arg);
        },
        initalize: function() {
            this.updateAMin =  App._.partial(this.updateModel, "aMin");
            this.updateBMin =  App._.partial(this.updateModel, "bMin");
            this.updateCMin =  App._.partial(this.updateModel, "cMin");
            this.updateDMin =  App._.partial(this.updateModel, "dMin");

        }
    });

    var GraphView = App.Mn.LayoutView.extend({
        template : chartTemplate,
        regions : {
            graph : ".chartGraphics",
            schema : ".scheme"
        }
    });

    App.Router.route(("charts"), "chart", function() {
        //var layout = App.show(new App.StandardLayoutView());
        var graphView = new GraphView();
        graphView.getRegion("graph").show(new GradeSchemaView({
            model : model
        }));
        graphView.getRegion("schema").show(new GradeSchemaView({
            model : model
        }));

        //App.show(new GradeSchemaView({
        //    model : model
        //}));
        //layout.getRegion('main').show(new App.Marionette.ItemView({
        //    template: template,
        //    updatePieChart: function() {
        //
        //    }
        //}))
    })
});<|endoftext|>


<commit_before>// Global munkireport object
var mr = {
        debug: false,
        dt:{},

        statusFormat: {
            install_failed: {type: 'danger'},
            install_succeeded: {type: 'success'},
            installed: {type: 'info'},
            pending_install: {type: 'warning'},
            pending_removal: {type: 'warning'},
            removed: {type: 'info'},
            uninstall_failed: {type: 'danger'},
            uninstalled: {type: 'success'}
        },

        // Graphing defaults
        graph: {
            barColor: ['steelBlue']
        },

        // Localstorage handler
        state: function(id, data){

            if( data == undefined)
            {
              // Get data
              return JSON.parse( localStorage.getItem(id) );

            }
            else
            {
              // Set data
              localStorage.setItem( id, JSON.stringify(data) );
            }
        },

        // Set Preference handler (uses localstorage)
        setPref: function(key, val){
            var globalPrefs = mr.state('global') || {};
            globalPrefs[key] = val;
            mr.state('global', globalPrefs);
        },

        // Get Preference handler (uses localstorage)
        getPref: function(key){
            var globalPrefs = mr.state('global') || {};
            return globalPrefs[key];
        },

        // Integer or integer string OS Version to semantic OS version
        integerToVersion: function(osvers)
        {
        	osvers = "" + osvers
        	// If osvers contains a dot, don't convert
        	if( osvers.indexOf(".") == -1)
            {
        		// Remove non-numerical string
        		osvers = isNaN(osvers) ? "" : osvers;

        		// Left pad with zeroes if necessary
        		osvers = ("000000" + osvers).substr(-6)
        		osvers = osvers.match(/.{2}/g).map(function(x){return +x}).join('.')
            }
            return osvers
        },

        // Get client detail link
        getClientDetailLink: function(name, sn, hash)
        {
        	hash = (typeof hash === "undefined") ? "" : hash;
        	return '
\
            		'+name+'\
            		\

';
        },

        /*
         * Natural Sort algorithm for Javascript - Version 0.8.1 - Released under MIT license
         * Author: Jim Palmer (based on chunking idea from Dave Koelle)
         */
        naturalSort: function(a, b) {
            var re = /(^([+\-]?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?(?=\D|\s|$))|^0x[\da-fA-F]+$|\d+)/g,
                sre = /^\s+|\s+$/g,   // trim pre-post whitespace
                snre = /\s+/g,        // normalize all whitespace to single ' ' character
                dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
                hre = /^0x[0-9a-f]+$/i,
                ore = /^0/,
                insensitive = true,
                i = function(s) {
                    return (insensitive && ('' + s).toLowerCase() || '' + s).replace(sre, '');
                },
                // convert all to strings strip whitespace
                x = i(a),
                y = i(b),
                // chunk/tokenize
                xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
                yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
                // numeric, hex or date detection
                xD = parseInt(x.match(hre), 16) || (xN.length !== 1 && Date.parse(x)),
                yD = parseInt(y.match(hre), 16) || xD && y.match(dre) && Date.parse(y) || null,
                normChunk = function(s, l) {
                    // normalize spaces; find floats not starting with '0', string or 0 if not defined (Clint Priest)
                    return (!s.match(ore) || l == 1) && parseFloat(s) || s.replace(snre, ' ').replace(sre, '') || 0;
                },
                oFxNcL, oFyNcL;
            // first try and sort Hex codes or Dates
            if (yD) {
                if (xD < yD) { return -1; }
                else if (xD > yD) { return 1; }
            }
            // natural sorting through split numeric strings and default strings
            for(var cLoc = 0, xNl = xN.length, yNl = yN.length, numS = Math.max(xNl, yNl); cLoc < numS; cLoc++) {
                oFxNcL = normChunk(xN[cLoc] || '', xNl);
                oFyNcL = normChunk(yN[cLoc] || '', yNl);
                // handle numeric vs string comparison - number < string - (Kyle Adams)
                if (isNaN(oFxNcL) !== isNaN(oFyNcL)) {
                    return isNaN(oFxNcL) ? 1 : -1;
                }
                // if unicode use locale comparison
                if (/[^\x00-\x80]/.test(oFxNcL + oFyNcL) && oFxNcL.localeCompare) {
                    var comp = oFxNcL.localeCompare(oFyNcL);
                    return comp / Math.abs(comp);
                }
                if (oFxNcL < oFyNcL) { return -1; }
                else if (oFxNcL > oFyNcL) { return 1; }
            }
        }, // End naturalSort

        // Draw graph for nvd3 and update graph
        drawGraph: function(conf){
            var graphData = [{"key": " ", "values": []}];
            d3.json(conf.url, function(data) {
                graphData[0].values = data;
                height = data.length * 26 + 40;
                conf.chart.height(height);

                d3.select(conf.svg)
                    .attr('height', height)
                    .datum(graphData)
                    .transition()
                    .duration(500)
                    .call(conf.chart);

                conf.chart.update();

            });

        },

        // Get preference for graph in this order: conf, default for graph, default
        getGraphPref: function(setting, graphName, conf){
            if(conf[setting]) return conf[setting];
            if(mr.graph[graphName] && mr.graph[graphName][setting]) return mr.graph[graphName][setting];
            return mr.graph[setting];
        },

        // Add nvd3 graph
        addGraph: function(conf){
            // Sanity check
            if( ! conf.widget){
                alert('no widget provided for addGraph');
                return;
            };

            // Assemble svg identifier
            conf.svg = '#' + conf.widget + ' svg';

            nv.addGraph(function() {
              conf.chart = nv.models.multiBarHorizontalChart()
                  .x(function(d) { return conf.labelModifier ? conf.labelModifier(d.label) : d.label })
                  .y(function(d) { return d.count })
                  .margin(conf.margin ? conf.margin : {top: 20, right: 10, bottom: 20, left: 70})
                  .showValues(true)
                  .valueFormat(d3.format(''))
                  .showControls(false)
                  .showLegend(false)
                  .barColor(mr.getGraphPref('barColor', conf.widget, conf))//conf.barColor ? conf.barColor : (graphSettings.barColor ? mr.graph.barColor))
                  .height(0);

              // Hide tooltips
              conf.chart.tooltip.enabled(false);

              conf.chart.yAxis
                  .tickFormat(d3.format(''));

              d3.select(conf.svg)
                  .attr('height', 0)
                  .datum([{"key": " ","values": []}])
                  .call(conf.chart);

            // Callback for click events
              if(conf.elementClickCallback){
                  // visit page on click
                  conf.chart.multibar.dispatch.on("elementClick", function(e) {
                      conf.elementClickCallback(e)
                  });

                  d3.select(conf.svg).attr("class", "clickLabels");
              }

                // Call the munkireport drawGraph routine
                mr.drawGraph(conf);

                // update chart data on appUpdate
                $(document).on('appUpdate', function(){mr.drawGraph(conf)});

                // update chart data on Resize
                nv.utils.windowResize(conf.chart.update);

            });

        },

        loadTheme: function() {
            // Get global state
            var theme = mr.getPref('theme') || 'Default';
            var theme_dir = baseUrl + 'assets/themes/' + theme + '/';
            var theme_file = theme_dir + 'bootstrap.min.css';
            $('#bootstrap-stylesheet').attr('href', theme_dir + 'bootstrap.min.css');
            $('#nvd3-override-stylesheet').attr('href', theme_dir + 'nvd3.override.css');

            // Add active to menu item
            $('[data-switch]').parent().removeClass('active');
            $('[data-switch="'+theme+'"]').parent().addClass('active');

            // Store theme in session
            $.post( appUrl + "/settings/theme", { set: theme });
        },

        sortMenu: function(menuIdentifier) {
            var $menu = $(menuIdentifier),
            	$itemsli = $menu.children('li');

            $itemsli.sort(function(a,b){
            	var an = $(a).find('a').text(),
            		bn = $(b).find('a').text();

            	if(an > bn) {
            		return 1;
            	}
            	if(an < bn) {
            		return -1;
            	}
            	return 0;
            });

            $itemsli.detach().appendTo($menu);
        },

        // Lookup table for display vendors
        display_vendors : {
            "610": "Apple",
            "10ac": "Dell",
            "5c23": "Wacom",
            "4d10": "Sharp",
            "1e6d": "LG",
            "38a3": "NEC",
            "4c49": "SMART Technologies",
            "9d1": "BenQ",
            "4dd9": "Sony",
            "472": "Acer",
            "22f0": "HP",
            "34ac": "Mitsubishi",
            "5a63": "ViewSonic",
            "4c2d": "Samsung",
            "593a": "Vizio",
            "d82": "CompuLab",
            "3023": "LaCie",
            "3698": "Matrox",
            "4ca3": "Epson",
            "170e": "Extron",
            "e11": "Compaq",
            "24d3": "ASK Proxima",
            "410c": "Philips",
            "15c3": "Eizo",
            "26cd": "iiyama",
            "7fff": "Haier",
            "3e8d": "Optoma",
            "5262": "Toshiba",
            "34a9": "Panasonic",
            "5e3": "Flanders Scientific",
            "30ae": "Lenovo",
            "469": "Asus",
            "4249": "Insignia",
            "5c85": "Westinghouse"
        }

    };
<commit_msg>Added another display vendor (#996)<commit_after>// Global munkireport object
var mr = {
        debug: false,
        dt:{},

        statusFormat: {
            install_failed: {type: 'danger'},
            install_succeeded: {type: 'success'},
            installed: {type: 'info'},
            pending_install: {type: 'warning'},
            pending_removal: {type: 'warning'},
            removed: {type: 'info'},
            uninstall_failed: {type: 'danger'},
            uninstalled: {type: 'success'}
        },

        // Graphing defaults
        graph: {
            barColor: ['steelBlue']
        },

        // Localstorage handler
        state: function(id, data){

            if( data == undefined)
            {
              // Get data
              return JSON.parse( localStorage.getItem(id) );

            }
            else
            {
              // Set data
              localStorage.setItem( id, JSON.stringify(data) );
            }
        },

        // Set Preference handler (uses localstorage)
        setPref: function(key, val){
            var globalPrefs = mr.state('global') || {};
            globalPrefs[key] = val;
            mr.state('global', globalPrefs);
        },

        // Get Preference handler (uses localstorage)
        getPref: function(key){
            var globalPrefs = mr.state('global') || {};
            return globalPrefs[key];
        },

        // Integer or integer string OS Version to semantic OS version
        integerToVersion: function(osvers)
        {
        	osvers = "" + osvers
        	// If osvers contains a dot, don't convert
        	if( osvers.indexOf(".") == -1)
            {
        		// Remove non-numerical string
        		osvers = isNaN(osvers) ? "" : osvers;

        		// Left pad with zeroes if necessary
        		osvers = ("000000" + osvers).substr(-6)
        		osvers = osvers.match(/.{2}/g).map(function(x){return +x}).join('.')
            }
            return osvers
        },

        // Get client detail link
        getClientDetailLink: function(name, sn, hash)
        {
        	hash = (typeof hash === "undefined") ? "" : hash;
        	return '
\
            		'+name+'\
            		\

';
        },

        /*
         * Natural Sort algorithm for Javascript - Version 0.8.1 - Released under MIT license
         * Author: Jim Palmer (based on chunking idea from Dave Koelle)
         */
        naturalSort: function(a, b) {
            var re = /(^([+\-]?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?(?=\D|\s|$))|^0x[\da-fA-F]+$|\d+)/g,
                sre = /^\s+|\s+$/g,   // trim pre-post whitespace
                snre = /\s+/g,        // normalize all whitespace to single ' ' character
                dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
                hre = /^0x[0-9a-f]+$/i,
                ore = /^0/,
                insensitive = true,
                i = function(s) {
                    return (insensitive && ('' + s).toLowerCase() || '' + s).replace(sre, '');
                },
                // convert all to strings strip whitespace
                x = i(a),
                y = i(b),
                // chunk/tokenize
                xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
                yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
                // numeric, hex or date detection
                xD = parseInt(x.match(hre), 16) || (xN.length !== 1 && Date.parse(x)),
                yD = parseInt(y.match(hre), 16) || xD && y.match(dre) && Date.parse(y) || null,
                normChunk = function(s, l) {
                    // normalize spaces; find floats not starting with '0', string or 0 if not defined (Clint Priest)
                    return (!s.match(ore) || l == 1) && parseFloat(s) || s.replace(snre, ' ').replace(sre, '') || 0;
                },
                oFxNcL, oFyNcL;
            // first try and sort Hex codes or Dates
            if (yD) {
                if (xD < yD) { return -1; }
                else if (xD > yD) { return 1; }
            }
            // natural sorting through split numeric strings and default strings
            for(var cLoc = 0, xNl = xN.length, yNl = yN.length, numS = Math.max(xNl, yNl); cLoc < numS; cLoc++) {
                oFxNcL = normChunk(xN[cLoc] || '', xNl);
                oFyNcL = normChunk(yN[cLoc] || '', yNl);
                // handle numeric vs string comparison - number < string - (Kyle Adams)
                if (isNaN(oFxNcL) !== isNaN(oFyNcL)) {
                    return isNaN(oFxNcL) ? 1 : -1;
                }
                // if unicode use locale comparison
                if (/[^\x00-\x80]/.test(oFxNcL + oFyNcL) && oFxNcL.localeCompare) {
                    var comp = oFxNcL.localeCompare(oFyNcL);
                    return comp / Math.abs(comp);
                }
                if (oFxNcL < oFyNcL) { return -1; }
                else if (oFxNcL > oFyNcL) { return 1; }
            }
        }, // End naturalSort

        // Draw graph for nvd3 and update graph
        drawGraph: function(conf){
            var graphData = [{"key": " ", "values": []}];
            d3.json(conf.url, function(data) {
                graphData[0].values = data;
                height = data.length * 26 + 40;
                conf.chart.height(height);

                d3.select(conf.svg)
                    .attr('height', height)
                    .datum(graphData)
                    .transition()
                    .duration(500)
                    .call(conf.chart);

                conf.chart.update();

            });

        },

        // Get preference for graph in this order: conf, default for graph, default
        getGraphPref: function(setting, graphName, conf){
            if(conf[setting]) return conf[setting];
            if(mr.graph[graphName] && mr.graph[graphName][setting]) return mr.graph[graphName][setting];
            return mr.graph[setting];
        },

        // Add nvd3 graph
        addGraph: function(conf){
            // Sanity check
            if( ! conf.widget){
                alert('no widget provided for addGraph');
                return;
            };

            // Assemble svg identifier
            conf.svg = '#' + conf.widget + ' svg';

            nv.addGraph(function() {
              conf.chart = nv.models.multiBarHorizontalChart()
                  .x(function(d) { return conf.labelModifier ? conf.labelModifier(d.label) : d.label })
                  .y(function(d) { return d.count })
                  .margin(conf.margin ? conf.margin : {top: 20, right: 10, bottom: 20, left: 70})
                  .showValues(true)
                  .valueFormat(d3.format(''))
                  .showControls(false)
                  .showLegend(false)
                  .barColor(mr.getGraphPref('barColor', conf.widget, conf))//conf.barColor ? conf.barColor : (graphSettings.barColor ? mr.graph.barColor))
                  .height(0);

              // Hide tooltips
              conf.chart.tooltip.enabled(false);

              conf.chart.yAxis
                  .tickFormat(d3.format(''));

              d3.select(conf.svg)
                  .attr('height', 0)
                  .datum([{"key": " ","values": []}])
                  .call(conf.chart);

            // Callback for click events
              if(conf.elementClickCallback){
                  // visit page on click
                  conf.chart.multibar.dispatch.on("elementClick", function(e) {
                      conf.elementClickCallback(e)
                  });

                  d3.select(conf.svg).attr("class", "clickLabels");
              }

                // Call the munkireport drawGraph routine
                mr.drawGraph(conf);

                // update chart data on appUpdate
                $(document).on('appUpdate', function(){mr.drawGraph(conf)});

                // update chart data on Resize
                nv.utils.windowResize(conf.chart.update);

            });

        },

        loadTheme: function() {
            // Get global state
            var theme = mr.getPref('theme') || 'Default';
            var theme_dir = baseUrl + 'assets/themes/' + theme + '/';
            var theme_file = theme_dir + 'bootstrap.min.css';
            $('#bootstrap-stylesheet').attr('href', theme_dir + 'bootstrap.min.css');
            $('#nvd3-override-stylesheet').attr('href', theme_dir + 'nvd3.override.css');

            // Add active to menu item
            $('[data-switch]').parent().removeClass('active');
            $('[data-switch="'+theme+'"]').parent().addClass('active');

            // Store theme in session
            $.post( appUrl + "/settings/theme", { set: theme });
        },

        sortMenu: function(menuIdentifier) {
            var $menu = $(menuIdentifier),
            	$itemsli = $menu.children('li');

            $itemsli.sort(function(a,b){
            	var an = $(a).find('a').text(),
            		bn = $(b).find('a').text();

            	if(an > bn) {
            		return 1;
            	}
            	if(an < bn) {
            		return -1;
            	}
            	return 0;
            });

            $itemsli.detach().appendTo($menu);
        },

        // Lookup table for display vendors
        display_vendors : {
            "610": "Apple",
            "10ac": "Dell",
            "5c23": "Wacom",
            "4d10": "Sharp",
            "1e6d": "LG",
            "38a3": "NEC",
            "4c49": "SMART Technologies",
            "9d1": "BenQ",
            "4dd9": "Sony",
            "472": "Acer",
            "22f0": "HP",
            "34ac": "Mitsubishi",
            "5a63": "ViewSonic",
            "4c2d": "Samsung",
            "593a": "Vizio",
            "d82": "CompuLab",
            "3023": "LaCie",
            "3698": "Matrox",
            "4ca3": "Epson",
            "170e": "Extron",
            "e11": "Compaq",
            "24d3": "ASK Proxima",
            "410c": "Philips",
            "15c3": "Eizo",
            "26cd": "iiyama",
            "7fff": "Haier",
            "3e8d": "Optoma",
            "5262": "Toshiba",
            "34a9": "Panasonic",
            "5e3": "Flanders Scientific",
            "30ae": "Lenovo",
            "469": "Asus",
            "4249": "Insignia",
            "41d2": "Planar",
            "5c85": "Westinghouse"
        }

    };
<|endoftext|>


<commit_before>(function(ext) {

    var firstTime = true;
    var boolean = true;
    var jsonObject = null;
    var xScale = 280;
    var yScale = 210;
    var status = 1;

    alert("BEFORE CLICKING OK: Make sure you have have followed the instructions in Kinect2Scratch");
    console.log("Right after the alert");

    var wsImpl = window.WebSocket || window.MozWebSocket;

    console.log("connecting to server ..");

    // create a new websocket and connect
    window.ws = new wsImpl('ws://localhost:8181/');

    // when data is comming from the server, this metod is called
    ws.onmessage = function (evt) {
        jsonObject = JSON.parse(evt.data);
            if(jsonObject.bodies == '')
            {
                status = 1;
            } else
            {
                status = 2;
            }
    };

    // when the connection is established, this method is called
    ws.onopen = function () {
        console.log('.. connection open');
    };

    // when the connection is closed, this method is called
    ws.onclose = function () {
        console.log('.. connection closed');
        status = 0;
    };

    // Cleanup function when the extension is unloaded
    ext._shutdown = function() {};

    // Status reporting code
    // Use this to report missing hardware, plugin or unsupported browser
    ext._getStatus = function() {
        if(status == 0)
        {
            return {status: 0, msg: 'Kinect is not connected to Scratch'};
            //polling function for auto-reconnect should go here
        }
        if(status == 1)
        {
            return {status: 1, msg: 'Kinect is connected, but is not detecting any bodies'};
        }
        if(status == 2)
        {
            return {status: 2, msg: 'Kinect is sending body data'};
        }

    };

        // Block and block menu descriptions
    var descriptor = {
        blocks: [
            ['', 'My First Block', 'my_first_block'],
            ['r', '%n ^ %n', 'power', 2, 3],
            ['r', '%m.k sensor value', 'k', 'Head X'],
            ['', 'restart connection', 'restart'],
            ['', 'test block', 'test_block'],
            ['b', 'connected', 'connected'],
            ['b', 'body tracked', 'tracked'],
            ['', 'console.log %n', 'write'],
            ['r', '%m.k sensor value no m', 'kNM', 'Head X'],
            ['', 'bad only %n', 'writeB'],
            ['r', '%m.l id', 'l', 'Body 1']
        ],

        menus: {
	    k: ['Left Ankle X', 'Left Ankle Y', 'Right Ankle X', 'Right Ankle Y', 'Left Elbow X', 'Left Elbow Y', 'Right Elbow X', 'Right Elbow Y', 'Left Foot X', 'Left Foot Y', 'Right Foot X', 'Right Foot Y', 'Left Hand X', 'Left Hand Y', 'Right Hand X', 'Right Hand Y', 'Left Hand Tip X', 'Left Hand Tip Y', 'Right Hand Tip X', 'Right Hand Tip Y', 'Head X', 'Head Y', 'Left Hip X', 'Left Hip Y', 'Right Hip X', 'Right Hip Y', 'Left Knee X', 'Left Knee Y', 'Right Knee X', 'Right Knee Y', 'Neck X', 'Neck Y', 'Left Shoulder X', 'Left Shoulder Y', 'Right Shoulder X', 'Right Shoulder Y', 'Spine Base X', 'Spine Base Y', 'Spine Middle X', 'Spine Middle Y', 'Spine Shoulder X', 'Spine Shoulder Y', 'Left Thumb X', 'Left Thumb Y', 'Right Thumb X', 'Right Thumb Y', 'Left Wrist X', 'Left Wrist Y', 'Right Wrist X', 'Right Wrist Y'];
        l: ['Body 1', 'Body 2'];
    }
    };

	ext.my_first_block = function() {
        console.log("My first block");
    };

    ext.restart = function() {
        console.log("connecting to server ..");
        window.ws = new wsImpl('ws://localhost:8181/');
    };

    ext.power = function(base, exponent) {
        return Math.pow(base, exponent);
    };

    ext.test_block = function() {
        console.log(jsonObject.bodies[0].joints[3].x*xScale);
    };

        ext.connected = function()
    {
        if(status == 0){
            return false;
        }

        if(status == 1 || 2){
            return true;
        }
    };

    ext.tracked = function()
    {
        if(status == (0 || 1)){
            return false;
        }

        if(status == 2){
            return true;
        }
    };

    ext.write = function(m){
        console.log(m);
    };

    ext.writeB = function(m){
        if(m == 0)
        {
            console.log("bad");
        }
    };

    ext.l = function(m)
    {
        switch(m){
            case 'Body 1': return jsonObject.bodies[0].id;
            case 'Body 2': return jsonObject.bodies[1].id;
        }
    }

    ext.kNM = function(m) {
        switch(m){
            case 'Left Ankle X': return jsonObject.bodies[0].joints[14].x;
            case 'Left Ankle Y': return jsonObject.bodies[0].joints[14].y;
            case 'Right Ankle X': return jsonObject.bodies[0].joints[18].x;
            case 'Right Ankle Y': return jsonObject.bodies[0].joints[18].y;
            case 'Left Elbow X': return jsonObject.bodies[0].joints[5].x;
            case 'Left Elbow Y': return jsonObject.bodies[0].joints[5].y;
            case 'Right Elbow X': return jsonObject.bodies[0].joints[9].x;
            case 'Right Elbow Y': return jsonObject.bodies[0].joints[9].y;
            case 'Left Foot X': return jsonObject.bodies[0].joints[15].x;
            case 'Left Foot Y': return jsonObject.bodies[0].joints[15].y;
            case 'Right Foot X': return jsonObject.bodies[0].joints[19].x;
            case 'Right Foot Y': return jsonObject.bodies[0].joints[19].y;
            case 'Left Hand X': return jsonObject.bodies[0].joints[7].x;
            case 'Left Hand Y': return jsonObject.bodies[0].joints[7].y;
            case 'Right Hand X': return jsonObject.bodies[0].joints[11].x;
            case 'Right Hand Y': return jsonObject.bodies[0].joints[11].y;
            case 'Left Hand Tip X': return jsonObject.bodies[0].joints[21].x;
            case 'Left Hand Tip Y': return jsonObject.bodies[0].joints[21].y;
            case 'Right Hand Tip X': return jsonObject.bodies[0].joints[23].x;
            case 'Right Hand Tip Y': return jsonObject.bodies[0].joints[23].y;
            case 'Head X': return jsonObject.bodies[0].joints[3].x;
            case 'Head Y': return jsonObject.bodies[0].joints[3].y;
            case 'Left Hip X': return jsonObject.bodies[0].joints[12].x;
            case 'Left Hip Y': return jsonObject.bodies[0].joints[12].y;
            case 'Right Hip X': return jsonObject.bodies[0].joints[16].x;
            case 'Right Hip Y': return jsonObject.bodies[0].joints[16].y;
            case 'Left Knee X': return jsonObject.bodies[0].joints[13].x;
            case 'Left Knee Y': return jsonObject.bodies[0].joints[13].y;
            case 'Right Knee X': return jsonObject.bodies[0].joints[17].x;
            case 'Right Knee Y': return jsonObject.bodies[0].joints[17].y;
            case 'Neck X': return jsonObject.bodies[0].joints[2].x;
            case 'Neck Y': return jsonObject.bodies[0].joints[2].y;
            case 'Left Shoulder X': return jsonObject.bodies[0].joints[4].x;
            case 'Left Shoulder Y': return jsonObject.bodies[0].joints[4].y;
            case 'Right Shoulder X': return jsonObject.bodies[0].joints[8].x;
            case 'Right Shoulder Y': return jsonObject.bodies[0].joints[8].y;
            case 'Spine Base X': return jsonObject.bodies[0].joints[0].x;
            case 'Spine Base Y': return jsonObject.bodies[0].joints[0].y;
            case 'Spine Middle X': return jsonObject.bodies[0].joints[1].x;
            case 'Spine Middle Y': return jsonObject.bodies[0].joints[1].y;
            case 'Spine Shoulder X': return jsonObject.bodies[0].joints[20].x;
            case 'Spine Shoulder Y': return jsonObject.bodies[0].joints[20].y;
            case 'Left Thumb X': return jsonObject.bodies[0].joints[22].x;
            case 'Left Thumb Y': return jsonObject.bodies[0].joints[22].y;
            case 'Right Thumb X': return jsonObject.bodies[0].joints[24].x;
            case 'Right Thumb Y': return jsonObject.bodies[0].joints[24].y;
            case 'Left Wrist X': return jsonObject.bodies[0].joints[6].x;
            case 'Left Wrist Y': return jsonObject.bodies[0].joints[6].y;
            case 'Right Wrist X': return jsonObject.bodies[0].joints[10].x;
            case 'Right Wrist Y': return jsonObject.bodies[0].joints[10].y;
        }
    };

    ext.k = function(m) {
        switch(m){
            case 'Left Ankle X': return jsonObject.bodies[0].joints[14].x*xScale;
            case 'Left Ankle Y': return jsonObject.bodies[0].joints[14].y*yScale;
            case 'Right Ankle X': return jsonObject.bodies[0].joints[18].x*xScale;
            case 'Right Ankle Y': return jsonObject.bodies[0].joints[18].y*yScale;
            case 'Left Elbow X': return jsonObject.bodies[0].joints[5].x*xScale;
            case 'Left Elbow Y': return jsonObject.bodies[0].joints[5].y*yScale;
            case 'Right Elbow X': return jsonObject.bodies[0].joints[9].x*xScale;
            case 'Right Elbow Y': return jsonObject.bodies[0].joints[9].y*yScale;
            case 'Left Foot X': return jsonObject.bodies[0].joints[15].x*xScale;
            case 'Left Foot Y': return jsonObject.bodies[0].joints[15].y*yScale;
            case 'Right Foot X': return jsonObject.bodies[0].joints[19].x*xScale;
            case 'Right Foot Y': return jsonObject.bodies[0].joints[19].y*yScale;
            case 'Left Hand X': return jsonObject.bodies[0].joints[7].x*xScale;
            case 'Left Hand Y': return jsonObject.bodies[0].joints[7].y*yScale;
            case 'Right Hand X': return jsonObject.bodies[0].joints[11].x*xScale;
            case 'Right Hand Y': return jsonObject.bodies[0].joints[11].y*yScale;
            case 'Left Hand Tip X': return jsonObject.bodies[0].joints[21].x*xScale;
            case 'Left Hand Tip Y': return jsonObject.bodies[0].joints[21].y*yScale;
            case 'Right Hand Tip X': return jsonObject.bodies[0].joints[23].x*xScale;
            case 'Right Hand Tip Y': return jsonObject.bodies[0].joints[23].y*yScale;
            case 'Head X': return jsonObject.bodies[0].joints[3].x*xScale;
            case 'Head Y': return jsonObject.bodies[0].joints[3].y*yScale;
            case 'Left Hip X': return jsonObject.bodies[0].joints[12].x*xScale;
            case 'Left Hip Y': return jsonObject.bodies[0].joints[12].y*yScale;
            case 'Right Hip X': return jsonObject.bodies[0].joints[16].x*xScale;
            case 'Right Hip Y': return jsonObject.bodies[0].joints[16].y*yScale;
            case 'Left Knee X': return jsonObject.bodies[0].joints[13].x*xScale;
            case 'Left Knee Y': return jsonObject.bodies[0].joints[13].y*yScale;
            case 'Right Knee X': return jsonObject.bodies[0].joints[17].x*xScale;
            case 'Right Knee Y': return jsonObject.bodies[0].joints[17].y*yScale;
            case 'Neck X': return jsonObject.bodies[0].joints[2].x*xScale;
            case 'Neck Y': return jsonObject.bodies[0].joints[2].y*yScale;
            case 'Left Shoulder X': return jsonObject.bodies[0].joints[4].x*xScale;
            case 'Left Shoulder Y': return jsonObject.bodies[0].joints[4].y*yScale;
            case 'Right Shoulder X': return jsonObject.bodies[0].joints[8].x*xScale;
            case 'Right Shoulder Y': return jsonObject.bodies[0].joints[8].y*yScale;
            case 'Spine Base X': return jsonObject.bodies[0].joints[0].x*xScale;
            case 'Spine Base Y': return jsonObject.bodies[0].joints[0].y*yScale;
            case 'Spine Middle X': return jsonObject.bodies[0].joints[1].x*xScale;
            case 'Spine Middle Y': return jsonObject.bodies[0].joints[1].y*yScale;
            case 'Spine Shoulder X': return jsonObject.bodies[0].joints[20].x*xScale;
            case 'Spine Shoulder Y': return jsonObject.bodies[0].joints[20].y*yScale;
            case 'Left Thumb X': return jsonObject.bodies[0].joints[22].x*xScale;
            case 'Left Thumb Y': return jsonObject.bodies[0].joints[22].y*yScale;
            case 'Right Thumb X': return jsonObject.bodies[0].joints[24].x*xScale;
            case 'Right Thumb Y': return jsonObject.bodies[0].joints[24].y*yScale;
            case 'Left Wrist X': return jsonObject.bodies[0].joints[6].x*xScale;
            case 'Left Wrist Y': return jsonObject.bodies[0].joints[6].y*yScale;
            case 'Right Wrist X': return jsonObject.bodies[0].joints[10].x*xScale;
            case 'Right Wrist Y': return jsonObject.bodies[0].joints[10].y*yScale;
        }
    };

    // Register the extension
    ScratchExtensions.register('KinectinScratch', descriptor, ext);
})({});<commit_msg>Actually fix typo<commit_after>(function(ext) {

    var firstTime = true;
    var boolean = true;
    var jsonObject = null;
    var xScale = 280;
    var yScale = 210;
    var status = 1;

    alert("BEFORE CLICKING OK: Make sure you have have followed the instructions in Kinect2Scratch");
    console.log("Right after the alert");

    var wsImpl = window.WebSocket || window.MozWebSocket;

    console.log("connecting to server ..");

    // create a new websocket and connect
    window.ws = new wsImpl('ws://localhost:8181/');

    // when data is comming from the server, this metod is called
    ws.onmessage = function (evt) {
        jsonObject = JSON.parse(evt.data);
            if(jsonObject.bodies == '')
            {
                status = 1;
            } else
            {
                status = 2;
            }
    };

    // when the connection is established, this method is called
    ws.onopen = function () {
        console.log('.. connection open');
    };

    // when the connection is closed, this method is called
    ws.onclose = function () {
        console.log('.. connection closed');
        status = 0;
    };

    // Cleanup function when the extension is unloaded
    ext._shutdown = function() {};

    // Status reporting code
    // Use this to report missing hardware, plugin or unsupported browser
    ext._getStatus = function() {
        if(status == 0)
        {
            return {status: 0, msg: 'Kinect is not connected to Scratch'};
            //polling function for auto-reconnect should go here
        }
        if(status == 1)
        {
            return {status: 1, msg: 'Kinect is connected, but is not detecting any bodies'};
        }
        if(status == 2)
        {
            return {status: 2, msg: 'Kinect is sending body data'};
        }

    };

        // Block and block menu descriptions
    var descriptor = {
        blocks: [
            ['', 'My First Block', 'my_first_block'],
            ['r', '%n ^ %n', 'power', 2, 3],
            ['r', '%m.k sensor value', 'k', 'Head X'],
            ['', 'restart connection', 'restart'],
            ['', 'test block', 'test_block'],
            ['b', 'connected', 'connected'],
            ['b', 'body tracked', 'tracked'],
            ['', 'console.log %n', 'write'],
            ['r', '%m.k sensor value no m', 'kNM', 'Head X'],
            ['', 'bad only %n', 'writeB'],
            ['r', '%m.l id', 'l', 'Body 1']
        ],

        menus: {
	    k: ['Left Ankle X', 'Left Ankle Y', 'Right Ankle X', 'Right Ankle Y', 'Left Elbow X', 'Left Elbow Y', 'Right Elbow X', 'Right Elbow Y', 'Left Foot X', 'Left Foot Y', 'Right Foot X', 'Right Foot Y', 'Left Hand X', 'Left Hand Y', 'Right Hand X', 'Right Hand Y', 'Left Hand Tip X', 'Left Hand Tip Y', 'Right Hand Tip X', 'Right Hand Tip Y', 'Head X', 'Head Y', 'Left Hip X', 'Left Hip Y', 'Right Hip X', 'Right Hip Y', 'Left Knee X', 'Left Knee Y', 'Right Knee X', 'Right Knee Y', 'Neck X', 'Neck Y', 'Left Shoulder X', 'Left Shoulder Y', 'Right Shoulder X', 'Right Shoulder Y', 'Spine Base X', 'Spine Base Y', 'Spine Middle X', 'Spine Middle Y', 'Spine Shoulder X', 'Spine Shoulder Y', 'Left Thumb X', 'Left Thumb Y', 'Right Thumb X', 'Right Thumb Y', 'Left Wrist X', 'Left Wrist Y', 'Right Wrist X', 'Right Wrist Y'],
        l: ['Body 1', 'Body 2']
    }
    };

	ext.my_first_block = function() {
        console.log("My first block");
    };

    ext.restart = function() {
        console.log("connecting to server ..");
        window.ws = new wsImpl('ws://localhost:8181/');
    };

    ext.power = function(base, exponent) {
        return Math.pow(base, exponent);
    };

    ext.test_block = function() {
        console.log(jsonObject.bodies[0].joints[3].x*xScale);
    };

        ext.connected = function()
    {
        if(status == 0){
            return false;
        }

        if(status == 1 || 2){
            return true;
        }
    };

    ext.tracked = function()
    {
        if(status == (0 || 1)){
            return false;
        }

        if(status == 2){
            return true;
        }
    };

    ext.write = function(m){
        console.log(m);
    };

    ext.writeB = function(m){
        if(m == 0)
        {
            console.log("bad");
        }
    };

    ext.l = function(m)
    {
        switch(m){
            case 'Body 1': return jsonObject.bodies[0].id;
            case 'Body 2': return jsonObject.bodies[1].id;
        }
    }

    ext.kNM = function(m) {
        switch(m){
            case 'Left Ankle X': return jsonObject.bodies[0].joints[14].x;
            case 'Left Ankle Y': return jsonObject.bodies[0].joints[14].y;
            case 'Right Ankle X': return jsonObject.bodies[0].joints[18].x;
            case 'Right Ankle Y': return jsonObject.bodies[0].joints[18].y;
            case 'Left Elbow X': return jsonObject.bodies[0].joints[5].x;
            case 'Left Elbow Y': return jsonObject.bodies[0].joints[5].y;
            case 'Right Elbow X': return jsonObject.bodies[0].joints[9].x;
            case 'Right Elbow Y': return jsonObject.bodies[0].joints[9].y;
            case 'Left Foot X': return jsonObject.bodies[0].joints[15].x;
            case 'Left Foot Y': return jsonObject.bodies[0].joints[15].y;
            case 'Right Foot X': return jsonObject.bodies[0].joints[19].x;
            case 'Right Foot Y': return jsonObject.bodies[0].joints[19].y;
            case 'Left Hand X': return jsonObject.bodies[0].joints[7].x;
            case 'Left Hand Y': return jsonObject.bodies[0].joints[7].y;
            case 'Right Hand X': return jsonObject.bodies[0].joints[11].x;
            case 'Right Hand Y': return jsonObject.bodies[0].joints[11].y;
            case 'Left Hand Tip X': return jsonObject.bodies[0].joints[21].x;
            case 'Left Hand Tip Y': return jsonObject.bodies[0].joints[21].y;
            case 'Right Hand Tip X': return jsonObject.bodies[0].joints[23].x;
            case 'Right Hand Tip Y': return jsonObject.bodies[0].joints[23].y;
            case 'Head X': return jsonObject.bodies[0].joints[3].x;
            case 'Head Y': return jsonObject.bodies[0].joints[3].y;
            case 'Left Hip X': return jsonObject.bodies[0].joints[12].x;
            case 'Left Hip Y': return jsonObject.bodies[0].joints[12].y;
            case 'Right Hip X': return jsonObject.bodies[0].joints[16].x;
            case 'Right Hip Y': return jsonObject.bodies[0].joints[16].y;
            case 'Left Knee X': return jsonObject.bodies[0].joints[13].x;
            case 'Left Knee Y': return jsonObject.bodies[0].joints[13].y;
            case 'Right Knee X': return jsonObject.bodies[0].joints[17].x;
            case 'Right Knee Y': return jsonObject.bodies[0].joints[17].y;
            case 'Neck X': return jsonObject.bodies[0].joints[2].x;
            case 'Neck Y': return jsonObject.bodies[0].joints[2].y;
            case 'Left Shoulder X': return jsonObject.bodies[0].joints[4].x;
            case 'Left Shoulder Y': return jsonObject.bodies[0].joints[4].y;
            case 'Right Shoulder X': return jsonObject.bodies[0].joints[8].x;
            case 'Right Shoulder Y': return jsonObject.bodies[0].joints[8].y;
            case 'Spine Base X': return jsonObject.bodies[0].joints[0].x;
            case 'Spine Base Y': return jsonObject.bodies[0].joints[0].y;
            case 'Spine Middle X': return jsonObject.bodies[0].joints[1].x;
            case 'Spine Middle Y': return jsonObject.bodies[0].joints[1].y;
            case 'Spine Shoulder X': return jsonObject.bodies[0].joints[20].x;
            case 'Spine Shoulder Y': return jsonObject.bodies[0].joints[20].y;
            case 'Left Thumb X': return jsonObject.bodies[0].joints[22].x;
            case 'Left Thumb Y': return jsonObject.bodies[0].joints[22].y;
            case 'Right Thumb X': return jsonObject.bodies[0].joints[24].x;
            case 'Right Thumb Y': return jsonObject.bodies[0].joints[24].y;
            case 'Left Wrist X': return jsonObject.bodies[0].joints[6].x;
            case 'Left Wrist Y': return jsonObject.bodies[0].joints[6].y;
            case 'Right Wrist X': return jsonObject.bodies[0].joints[10].x;
            case 'Right Wrist Y': return jsonObject.bodies[0].joints[10].y;
        }
    };

    ext.k = function(m) {
        switch(m){
            case 'Left Ankle X': return jsonObject.bodies[0].joints[14].x*xScale;
            case 'Left Ankle Y': return jsonObject.bodies[0].joints[14].y*yScale;
            case 'Right Ankle X': return jsonObject.bodies[0].joints[18].x*xScale;
            case 'Right Ankle Y': return jsonObject.bodies[0].joints[18].y*yScale;
            case 'Left Elbow X': return jsonObject.bodies[0].joints[5].x*xScale;
            case 'Left Elbow Y': return jsonObject.bodies[0].joints[5].y*yScale;
            case 'Right Elbow X': return jsonObject.bodies[0].joints[9].x*xScale;
            case 'Right Elbow Y': return jsonObject.bodies[0].joints[9].y*yScale;
            case 'Left Foot X': return jsonObject.bodies[0].joints[15].x*xScale;
            case 'Left Foot Y': return jsonObject.bodies[0].joints[15].y*yScale;
            case 'Right Foot X': return jsonObject.bodies[0].joints[19].x*xScale;
            case 'Right Foot Y': return jsonObject.bodies[0].joints[19].y*yScale;
            case 'Left Hand X': return jsonObject.bodies[0].joints[7].x*xScale;
            case 'Left Hand Y': return jsonObject.bodies[0].joints[7].y*yScale;
            case 'Right Hand X': return jsonObject.bodies[0].joints[11].x*xScale;
            case 'Right Hand Y': return jsonObject.bodies[0].joints[11].y*yScale;
            case 'Left Hand Tip X': return jsonObject.bodies[0].joints[21].x*xScale;
            case 'Left Hand Tip Y': return jsonObject.bodies[0].joints[21].y*yScale;
            case 'Right Hand Tip X': return jsonObject.bodies[0].joints[23].x*xScale;
            case 'Right Hand Tip Y': return jsonObject.bodies[0].joints[23].y*yScale;
            case 'Head X': return jsonObject.bodies[0].joints[3].x*xScale;
            case 'Head Y': return jsonObject.bodies[0].joints[3].y*yScale;
            case 'Left Hip X': return jsonObject.bodies[0].joints[12].x*xScale;
            case 'Left Hip Y': return jsonObject.bodies[0].joints[12].y*yScale;
            case 'Right Hip X': return jsonObject.bodies[0].joints[16].x*xScale;
            case 'Right Hip Y': return jsonObject.bodies[0].joints[16].y*yScale;
            case 'Left Knee X': return jsonObject.bodies[0].joints[13].x*xScale;
            case 'Left Knee Y': return jsonObject.bodies[0].joints[13].y*yScale;
            case 'Right Knee X': return jsonObject.bodies[0].joints[17].x*xScale;
            case 'Right Knee Y': return jsonObject.bodies[0].joints[17].y*yScale;
            case 'Neck X': return jsonObject.bodies[0].joints[2].x*xScale;
            case 'Neck Y': return jsonObject.bodies[0].joints[2].y*yScale;
            case 'Left Shoulder X': return jsonObject.bodies[0].joints[4].x*xScale;
            case 'Left Shoulder Y': return jsonObject.bodies[0].joints[4].y*yScale;
            case 'Right Shoulder X': return jsonObject.bodies[0].joints[8].x*xScale;
            case 'Right Shoulder Y': return jsonObject.bodies[0].joints[8].y*yScale;
            case 'Spine Base X': return jsonObject.bodies[0].joints[0].x*xScale;
            case 'Spine Base Y': return jsonObject.bodies[0].joints[0].y*yScale;
            case 'Spine Middle X': return jsonObject.bodies[0].joints[1].x*xScale;
            case 'Spine Middle Y': return jsonObject.bodies[0].joints[1].y*yScale;
            case 'Spine Shoulder X': return jsonObject.bodies[0].joints[20].x*xScale;
            case 'Spine Shoulder Y': return jsonObject.bodies[0].joints[20].y*yScale;
            case 'Left Thumb X': return jsonObject.bodies[0].joints[22].x*xScale;
            case 'Left Thumb Y': return jsonObject.bodies[0].joints[22].y*yScale;
            case 'Right Thumb X': return jsonObject.bodies[0].joints[24].x*xScale;
            case 'Right Thumb Y': return jsonObject.bodies[0].joints[24].y*yScale;
            case 'Left Wrist X': return jsonObject.bodies[0].joints[6].x*xScale;
            case 'Left Wrist Y': return jsonObject.bodies[0].joints[6].y*yScale;
            case 'Right Wrist X': return jsonObject.bodies[0].joints[10].x*xScale;
            case 'Right Wrist Y': return jsonObject.bodies[0].joints[10].y*yScale;
        }
    };

    // Register the extension
    ScratchExtensions.register('KinectinScratch', descriptor, ext);
})({});<|endoftext|>


<commit_before>/* global componentHandler */
"use strict";

module.exports = function (el, init) {
    if(init) {
        return;
    }

    componentHandler.upgradeElement(el);
};
<commit_msg>Unused<commit_after><|endoftext|>


<commit_before>// External
import * as d3 from 'd3';  // eslint-disable-line import/no-unresolved

// Internal
import Bar from './bar';
import * as config from './config';
import { roundRect } from '../commons/charts';

const BARS_CLASS = 'bars';

class Bars {
  /**
   * [constructor description]
   *
   * @method  constructor
   * @author  Fritz Lekschas
   * @date    2016-09-14
   * @param   {Object}  baseEl   D3 selection where the group of bars should be
   *   appended to.
   * @param   {String}  mode     Display more. Can be either `one` or `two`.
   * @param   {Object}  visData  Object with the list graph app data.
   */
  constructor (baseEl, mode, visData) {
    const self = this;

    this.mode = mode;
    this.visData = visData;

    this.indicatorX = d3.scaleLinear()
      .domain([0, 1])
      .range([1, this.visData.global.column.contentWidth - 3]);

    this.baseEl = baseEl.append('g').attr('class', BARS_CLASS);

    this.baseEl.each(function (datum) {
      new Bar(d3.select(this), datum.data.bars, datum, self.visData, self);
    });
  }

  /**
   * Updates all bar magnitude elements.
   *
   * @method  updateAll
   * @author  Fritz Lekschas
   * @date    2016-09-14
   * @param   {Object}  update  Object with the current data.
   * @param   {String}  sortBy  Name of the poperty to be sorted by.
   */
  updateAll (update, sortBy) {
    this.baseEl.selectAll('.bar-magnitude')
      .data(update, data => data.barId)
      .transition()
      .duration(config.TRANSITION_SEMI_FAST)
      .attr('d', data => this.generatePath(data, sortBy));
  }

  /**
   * Update bars when switching the bar mode.
   *
   * @method  update
   * @author  Fritz Lekschas
   * @date    2016-09-14
   * @param   {Object}  selection  D3 selection
   * @param   {String}  sortBy     Name of the poperty to be sorted by.
   */
  update (selection, sortBy) {
    selection.each(function (data) {
      const el = d3.select(this);

      if (data.id === sortBy && !el.classed('active')) {
        el.classed('active', true);
        // Ensure that the active bars we are places before any other bar,
        // thus placing them in the background
        this.parentNode.insertBefore(
          this,
          this.parentNode.children[0]
        );
      }

      if (data.id !== sortBy) {
        el.classed('active', false);
      }
    });

    selection.selectAll('.bar-magnitude')
      .transition()
      .duration(config.TRANSITION_SEMI_FAST)
      .attr('d', data => this.generatePath(data, sortBy));
  }

  /**
   * Switch one and two-bar display mode.
   *
   * @method  switchMode
   * @author  Fritz Lekschas
   * @date    2016-09-14
   * @param   {String}  mode            Name of the display mode. Can either be
   *   `one` or `two`.
   * @param   {String}  currentSorting  Name if the property currently sorted
   *   by.
   */
  switchMode (mode, currentSorting) {
    if (this.mode !== mode) {
      if (mode === 'one') {
        if (currentSorting.global.type) {
          this.baseEl.selectAll('.bar').selectAll('.bar-magnitude')
            .transition()
            .duration(config.TRANSITION_SEMI_FAST)
            .attr('d', data => this.generateOneBarPath(
              data, currentSorting.global.type
            ));
        } else {
          // console.error(
          //   'Switching magnitude visualization after individual sorting is ' +
          //   'not supported yet.'
          // );
        }
      }

      if (mode === 'two') {
        this.baseEl.selectAll('.bar.precision').selectAll('.bar-magnitude')
          .transition()
          .duration(config.TRANSITION_SEMI_FAST)
          .attr('d', data => this.generateTwoBarsPath(data));

        this.baseEl.selectAll('.bar.recall').selectAll('.bar-magnitude')
          .transition()
          .duration(config.TRANSITION_SEMI_FAST)
          .attr('d', data => this.generateTwoBarsPath(data, true));
      }

      this.mode = mode;
    }
  }

  /**
   * Helper method to generate path used as a bar.
   *
   * @method  generatePath
   * @author  Fritz Lekschas
   * @date    2016-09-14
   * @param   {Object}   data             Data object.
   * @param   {String}   sortBy           Name of the property currently sorted
   *   by.
   */
  generatePath (data, sortBy) {
    if (this.mode === 'two') {
      return this.generateTwoBarsPath(data);
    }
    return this.generateOneBarPath(data, sortBy);
  }

  /**
   * Generates a bar when one-bar display mode is active.
   *
   * @method  generateOneBarPath
   * @author  Fritz Lekschas
   * @date    2016-09-14
   * @param   {Object}   data    Data object.
   * @param   {String}   sortBy  Name of the property currently sorted by.
   */
  generateOneBarPath (data, sortBy) {
    const height = this.visData.global.row.contentHeight;
    const normValue = Math.min(data.value, 1) || 0;

    let x = 0;
    let width = 2;

    let radius = {
      topLeft: 2,
      bottomLeft: 2
    };

    if (data.id !== sortBy) {
      x = this.indicatorX(normValue);
      radius = {};
    } else {
      width = this.visData.global.column.contentWidth * normValue;
    }

    x = Math.min(x, this.visData.global.column.contentWidth - 2);

    return roundRect(
      x,
      this.visData.global.row.padding,
      width,
      height,
      radius
    );
  }

  /**
   * Generates a bar when two-bar display mode is active.
   *
   * @method  generateTwoBarsPath
   * @author  Fritz Lekschas
   * @date    2016-09-14
   * @param   {Object}   data      Data object.
   * @param   {Boolean}  isBottom  If `true` then the bottom bar should be
   *   generated.
   */
  generateTwoBarsPath (data, isBottom) {
    const normValue = Math.min(data.value, 1);
    const height = this.visData.global.row.contentHeight / 2;
    const width = this.visData.global.column.contentWidth * normValue;

    let y = this.visData.global.row.padding;
    let radius = { topLeft: 2 };

    if (isBottom) {
      radius = { bottomLeft: 2 };
      y += height;
    }

    return roundRect(
      0,
      y,
      width,
      height,
      radius
    );
  }
}

export default Bars;
<commit_msg>Rename for clarity.<commit_after>// External
import * as d3 from 'd3';  // eslint-disable-line import/no-unresolved

// Internal
import Bar from './bar';
import * as config from './config';
import { roundRect } from '../commons/charts';

const BARS_CLASS = 'bars';

class Bars {
  /**
   * [constructor description]
   *
   * @method  constructor
   * @author  Fritz Lekschas
   * @date    2016-09-14
   * @param   {Object}  baseEl   D3 selection where the group of bars should be
   *   appended to.
   * @param   {String}  mode     Display more. Can be either `one` or `two`.
   * @param   {Object}  visData  Object with the list graph app data.
   */
  constructor (baseEl, mode, visData) {
    const self = this;

    this.mode = mode;
    this.visData = visData;

    this.xScale = d3.scaleLinear()
      .domain([0, 1])
      .range([1, this.visData.global.column.contentWidth - 3]);

    this.baseEl = baseEl.append('g').attr('class', BARS_CLASS);

    this.baseEl.each(function (datum) {
      new Bar(d3.select(this), datum.data.bars, datum, self.visData, self);
    });
  }

  /**
   * Updates all bar magnitude elements.
   *
   * @method  updateAll
   * @author  Fritz Lekschas
   * @date    2016-09-14
   * @param   {Object}  update  Object with the current data.
   * @param   {String}  sortBy  Name of the poperty to be sorted by.
   */
  updateAll (update, sortBy) {
    this.baseEl.selectAll('.bar-magnitude')
      .data(update, data => data.barId)
      .transition()
      .duration(config.TRANSITION_SEMI_FAST)
      .attr('d', data => this.generatePath(data, sortBy));
  }

  /**
   * Update bars when switching the bar mode.
   *
   * @method  update
   * @author  Fritz Lekschas
   * @date    2016-09-14
   * @param   {Object}  selection  D3 selection
   * @param   {String}  sortBy     Name of the poperty to be sorted by.
   */
  update (selection, sortBy) {
    selection.each(function (data) {
      const el = d3.select(this);

      if (data.id === sortBy && !el.classed('active')) {
        el.classed('active', true);
        // Ensure that the active bars we are places before any other bar,
        // thus placing them in the background
        this.parentNode.insertBefore(
          this,
          this.parentNode.children[0]
        );
      }

      if (data.id !== sortBy) {
        el.classed('active', false);
      }
    });

    selection.selectAll('.bar-magnitude')
      .transition()
      .duration(config.TRANSITION_SEMI_FAST)
      .attr('d', data => this.generatePath(data, sortBy));
  }

  /**
   * Switch one and two-bar display mode.
   *
   * @method  switchMode
   * @author  Fritz Lekschas
   * @date    2016-09-14
   * @param   {String}  mode            Name of the display mode. Can either be
   *   `one` or `two`.
   * @param   {String}  currentSorting  Name if the property currently sorted
   *   by.
   */
  switchMode (mode, currentSorting) {
    if (this.mode !== mode) {
      if (mode === 'one') {
        if (currentSorting.global.type) {
          this.baseEl.selectAll('.bar').selectAll('.bar-magnitude')
            .transition()
            .duration(config.TRANSITION_SEMI_FAST)
            .attr('d', data => this.generateOneBarPath(
              data, currentSorting.global.type
            ));
        } else {
          // console.error(
          //   'Switching magnitude visualization after individual sorting is ' +
          //   'not supported yet.'
          // );
        }
      }

      if (mode === 'two') {
        this.baseEl.selectAll('.bar.precision').selectAll('.bar-magnitude')
          .transition()
          .duration(config.TRANSITION_SEMI_FAST)
          .attr('d', data => this.generateTwoBarsPath(data));

        this.baseEl.selectAll('.bar.recall').selectAll('.bar-magnitude')
          .transition()
          .duration(config.TRANSITION_SEMI_FAST)
          .attr('d', data => this.generateTwoBarsPath(data, true));
      }

      this.mode = mode;
    }
  }

  /**
   * Helper method to generate path used as a bar.
   *
   * @method  generatePath
   * @author  Fritz Lekschas
   * @date    2016-09-14
   * @param   {Object}   data             Data object.
   * @param   {String}   sortBy           Name of the property currently sorted
   *   by.
   */
  generatePath (data, sortBy) {
    if (this.mode === 'two') {
      return this.generateTwoBarsPath(data);
    }
    return this.generateOneBarPath(data, sortBy);
  }

  /**
   * Generates a bar when one-bar display mode is active.
   *
   * @method  generateOneBarPath
   * @author  Fritz Lekschas
   * @date    2016-09-14
   * @param   {Object}   data    Data object.
   * @param   {String}   sortBy  Name of the property currently sorted by.
   */
  generateOneBarPath (data, sortBy) {
    const height = this.visData.global.row.contentHeight;
    const normValue = Math.min(data.value, 1) || 0;

    let x = 0;
    let width = 2;

    let radius = {
      topLeft: 2,
      bottomLeft: 2
    };

    if (data.id !== sortBy) {
      x = this.xScale(normValue);
      radius = {};
    } else {
      width = this.visData.global.column.contentWidth * normValue;
    }

    x = Math.min(x, this.visData.global.column.contentWidth - 2);

    return roundRect(
      x,
      this.visData.global.row.padding,
      width,
      height,
      radius
    );
  }

  /**
   * Generates a bar when two-bar display mode is active.
   *
   * @method  generateTwoBarsPath
   * @author  Fritz Lekschas
   * @date    2016-09-14
   * @param   {Object}   data      Data object.
   * @param   {Boolean}  isBottom  If `true` then the bottom bar should be
   *   generated.
   */
  generateTwoBarsPath (data, isBottom) {
    const normValue = Math.min(data.value, 1);
    const height = this.visData.global.row.contentHeight / 2;
    const width = this.visData.global.column.contentWidth * normValue;

    let y = this.visData.global.row.padding;
    let radius = { topLeft: 2 };

    if (isBottom) {
      radius = { bottomLeft: 2 };
      y += height;
    }

    return roundRect(
      0,
      y,
      width,
      height,
      radius
    );
  }
}

export default Bars;
<|endoftext|>