<commit_before>/*******************************************
* js-cgi.js
* Copyright (c) 2015, Darrel Kathan
* Licensed under the MIT license.
*
* A current version and some documentation is available at
*    https://github.com/kathan/js-cgi
*
* @summary     Javascript CGI process manager
* @description js-cgi is a javascript CGI process manager, similar to php-fpm, for executing node.js compatible scripts behind NGINX or Apache.
* @file        js-cgi.js
* @version     1.0.0
* @author      Darrel Kathan
* @license     MIT
* 2/16/16 - Added cluster node cache
* 7/6/16 - Added script timeout override
* 2/16/17 - Added middleware option
* 4/13/17 - Major timeout bug fix
* 11/3/17 - Added cgi function
*******************************************/
"use strict";

var cluster = require("cluster"),
  _ = require("lodash"),
  url = require("url"),
  fs = require("fs"),
  vm = require("vm"),
  os = require("os"),
  util = require("util"),
  path = require("path"),
  express = require("express"),
  app = express(),
  config_name = "js-cgi.config",
  use_name = "use.js",
  config = {};
/******************************************
* Capture console.log and console.error
* input to log file.
*******************************************/
var console_log = console.log,
  console_error = console.error;

console.log = function() {
  var d = new Date(),
    log_msg = d.toString() + " - (" + process.pid + "): ";
  if (config.output_log) {
    fs.appendFile(
      config.output_log,
      log_msg + util.format.apply(this, arguments) + "\n",
      function() {
        return;
      }
    );
  }
  return console_log.apply(this, arguments);
};

console.error = function(err) {
  var d = new Date(),
    log_msg = d.toString() + " - (" + process.pid + "): ";

  if (config.error_log) {
    fs.appendFile(
      config.error_log,
      log_msg + util.format.apply(this, arguments) + "\n",
      function() {
        return;
      }
    );
    if (err && err.stack) {
      fs.appendFile(
        config.error_log,
        err.stack + util.format.apply(this, arguments) + "\n",
        function() {
          return;
        }
      );
    }
  }
  return console_error.apply(this, arguments);
};

/*******************************************
* Prepare web server to handle cookies and
* format JSON.
*******************************************/

app.set("json spaces", 2);

//console.log(config.output_log);
if (fs.existsSync(path.join(__dirname, config_name))) {
  //Load the congfig file
  console.log("Loading " + config_name + "...");
  config = require("./" + config_name);
}

if (fs.existsSync(path.join(__dirname, use_name))) {
  //Load the congfig file
  console.log("Loading " + use_name + "...");
  var mid_ware = require("./" + use_name);
  if (typeof mid_ware === "function") {
    mid_ware(app);
  } else {
    console.error("Use file is malformed.");
  }
}

//Set default config items
!config.output_log
  ? (config.output_log = path.dirname(process.argv[1]) + "/js-cgi.log")
  : "";
!config.error_log
  ? (config.error_log = path.dirname(process.argv[1]) + "/err.log")
  : "";
!config.port ? (config.port = 3000) : "";
!config.localhostOnly ? (config.localhostOnly = true) : "";
!config.timeout ? (config.timeout = 30000) : "";
!config.workers ? (config.workers = os.cpus().length - 1) : ""; //Subtract one for the master
!config.watch_required ? (config.watch_required = false) : "";

/*******************************************
* Override the "require" function to watch
* if required files have change and expire
* them from cache when they do.
*******************************************/
var assert = require("assert").ok,
  Module = require("module");
if (typeof Module._watching !== "object") {
  Module._watching = {};
}
function watchRequired(fn) {
  /*var fs = require('fs')
    console = console;*/
  //console.log(fn);
  if (Module._watching && !Module._watching.hasOwnProperty(fn)) {
    if (fs.existsSync(fn) && !Module._watching.hasOwnProperty(fn)) {
      console.log("Watching " + fn);
      Module._watching[fn] = fs.watch(fn, (event, f) => {
        //Module._watching[fn] = fs.watchFile(fn, function(curr, prev){
        console.log(fn, event);

        if (Module._cache.hasOwnProperty(fn)) {
          console.log("Expiring " + fn);
          //fs.unwatch(fn, function(){return;});
          return delete Module._cache[fn];
        }
        return;
      });
    }
  }
}

Module.prototype.require = function(path) {
  assert(path, "missing path");
  assert(typeof path === "string", "path must be a string");
  if (config.watch_required) {
    watchRequired(Module._resolveFilename(path, this));
  }
  return Module._load(path, this);
};

/*******************************************
* Start up the server node.
*******************************************/
if (cluster.isMaster) {
  cluster.globals = {};
  cluster.fork().on("error", console.error); //At least one worker is required.
  console.log(process.versions);
  for (var w = 2; w <= config.workers; w++) {
    cluster.fork().on("error", console.error);
  }

  cluster.on("disconnect", worker => {
    cluster.fork().on("error", console.error);
  });

  cluster.on("listening", (worker, address) => {
    console.log("A worker is now connected to " + JSON.stringify(address));
  });
} else {
  // the worker
  var domain = require("domain"),
    server,
    d = domain.create();

  d.on("error", err => {
    console.error("Domain Error:", err, err.stack);
    //console.trace();
    try {
      // make sure we close down if it times out
      //var killtimer = setTimeout(() => {
      //var err = new Error('Killing process.');

      //console.error('Domain Error:', err);
      //console.trace();
      console.log("Killing process.");
      process.exit(1);
      //}, config.timeout);

      // But don't keep the process open just for that!
      //killtimer.unref();

      // stop taking new requests.
      server.close();

      // Let the master know we're dead.  This will trigger a
      // 'disconnect' in the cluster master, and then it will fork
      // a new worker.
      cluster.worker.disconnect();
    } catch (er2) {
      // oh well, not much we can do at this point.
      console.error(er2);
    }
  });

  /*******************************************
    * Now run the handler function in the domain.
    *******************************************/
  d.run(() => {
    console.log("Listening on " + config.port);

    server = app.listen(config.port);

    app.all("*", (req, res) => {
      //console.log('req');
      return handleRequest(req, res);
    });
  });
}

/*******************************************
* This is where all of the web requests are
* handled.
*******************************************/
function handleRequest(req, res) {
  //console.log('request:', req);
  var url_obj = url.parse(req.url, true),
    file_path;

  /*var cache = [],
    j = JSON.stringify(req, function(key, value) {

      if (typeof value === 'object' && value !== null) {
        var idx = _.findIndex(cache, value);
        if (idx > -1) {return '[Circular '+idx+']';}
        cache.push(value);
      }
    return value;
  });

  res.send(j);*/
  //console.log('req.connection.remoteFamily:', '"'+req.connection.remoteFamily+'"');
  //console.log('req.connection.remoteAddress:', '"'+req.connection.remoteAddress+'"');
  if (config.localhostOnly) {
    if (
      (req.connection.remoteFamily === "IPv4" &&
        req.connection.remoteAddress !== "127.0.0.1") ||
      (req.connection.remoteFamily === "IPv6" &&
        (!_.endsWith(req.connection.remoteAddress, "::1") &&
          !_.endsWith(req.connection.remoteAddress, ":127.0.0.1")))
    ) {
      return res.sendStatus(401);
    }
  }

  if (!req.headers.path_translated) {
    req.headers.path_translated = __dirname + "/www";
    //console.log(req.headers.path_translated);
    if (!fs.existsSync(req.headers.path_translated)) {
      fs.mkdirSync(req.headers.path_translated);
    }
  }

  if (req.headers.path_translated && url_obj.pathname) {
    file_path = req.headers.path_translated + url_obj.pathname;
  } else {
    file_path = url_obj.pathname;
  }
  console.log(req.method + ": " + file_path);
  function resolveModule(module) {
    if (module.charAt(0) !== ".") {
      return module;
    }
    return path.resolve(path.dirname(file_path), module);
  }

  //If the requested file exists...
  fs.exists(file_path, exists => {
    if (exists) {
      fs.readFile(file_path, (err, source) => {
        if (err) {
          //Error reading file
          console.error(err);
          return res
            .status(500)
            .send({ error: err.toString(), stack: err.stack });
        }
        try {
          //console.log(require.cache);
          //var timer = 'not set';
          req.timeout = config.timeout;
          var timer,
              sandbox = {
                console: console,
                setImmediate: setImmediate,
                setInterval: setInterval,
                setTimeout: setTimeout,
                clearTimeout: clearTimeout,
                Buffer: Buffer,
                JSON: JSON,
                require: function(name) {
                  var mod_path = resolveModule(name);
                  //watchRequired(mod_path);
                  return require(mod_path);
                },
                req: req,
                res: res,
                process: process,
                __dirname: path.dirname(file_path)
              },
              setKilltimer = function() {
                //!req.timeout ? (req.timeout = config.timeout) : "";
                var to_start = Date.now();
                var timeout = req.timeout;
                if (timeout > 0) {
                  return setTimeout(() => {
                    var to_end = Date.now(),
                        msg =
                          "Timeout expired (" +
                          (to_end - to_start) +
                          " ms) for " +
                          file_path,
                        err;

                    //if(!res.headerSent){
                    res.status(408).send(msg);
                    //}
                    //err = new Error(msg);
                    console.error(msg);
                    return;
                  }, req.timeout);
                }
              };
          /****************************
          * Capture "res.send" and
          * "res.sendFile" calls to
          * be able to unset timeout
          * when the script ends. */
          var send = res.send;
          res.send = function(){
            if(timer){
              console.log('timeout cleared');
              clearTimeout(timer);
            }
            return send.apply(this, arguments);
          };
          var sendFile = res.sendFile;
          res.sendFile = function(){
            if(timer){
              console.log('timeout cleared');
              clearTimeout(timer);
            }
            return sendFile.apply(this, arguments);
          }
          /***************************/

          /*****************
           * Start VM Code *
           *****************/
          var c = vm.createContext(sandbox),
              code = `function runInContext() {try{${source}                          //0
                          if(typeof cgi === 'function'){                              //1
                            cgi(req, res);                                            //2
                          }                                                           //3
                        }catch(e){                                                    //4
                          console.error(e);                                           //5
                          res.status(500).send({error: e.toString(), stack: e.stack});//6
                        }                                                             //7
                      }                                                               //8
                                                                                //9
                      runInContext();`;
          /***************
          * End VM Code *
          ***************/

          /***************************************************
           * Set the kill timer after executing the script so
           * the script can set the timeout duration.
           ***************************************************/
          var result = vm.runInContext(code, c, file_path);
          timer = setKilltimer();
          return result;
        } catch (err) {
          console.error(err);
          return res
            .status(500)
            .send({ error: err.toString(), stack: err.stack });
        }
      });
    } else {
      //File does not exist
      return res.status(404).send("File not found. " + file_path);
    }
  });
}
<commit_msg>Added path_info<commit_after>/*******************************************
* js-cgi.js
* Copyright (c) 2015, Darrel Kathan
* Licensed under the MIT license.
*
* A current version and some documentation is available at
*    https://github.com/kathan/js-cgi
*
* @summary     Javascript CGI process manager
* @description js-cgi is a javascript CGI process manager, similar to php-fpm, for executing node.js compatible scripts behind NGINX or Apache.
* @file        js-cgi.js
* @version     1.1.1
* @author      Darrel Kathan
* @license     MIT
* 2/16/16 - Added cluster node cache
* 7/6/16 - Added script timeout override
* 2/16/17 - Added middleware option
* 4/13/17 - Major timeout bug fix
* 11/3/17 - Added cgi function
* 11/29/17 - Added path_info
*******************************************/
"use strict";

var cluster = require("cluster"),
  _ = require("lodash"),
  url = require("url"),
  fs = require("fs"),
  vm = require("vm"),
  os = require("os"),
  util = require("util"),
  path = require("path"),
  express = require("express"),
  app = express(),
  config_name = "js-cgi.config",
  use_name = "use.js",
  config = {};
/******************************************
* Capture console.log and console.error
* input to log file.
*******************************************/
var console_log = console.log,
  console_error = console.error;

console.log = function() {
  var d = new Date(),
    log_msg = d.toString() + " - (" + process.pid + "): ";
  if (config.output_log) {
    fs.appendFile(
      config.output_log,
      log_msg + util.format.apply(this, arguments) + "\n",
      function() {
        return;
      }
    );
  }
  return console_log.apply(this, arguments);
};

console.error = function(err) {
  var d = new Date(),
    log_msg = d.toString() + " - (" + process.pid + "): ";

  if (config.error_log) {
    fs.appendFile(
      config.error_log,
      log_msg + util.format.apply(this, arguments) + "\n",
      function() {
        return;
      }
    );
    if (err && err.stack) {
      fs.appendFile(
        config.error_log,
        err.stack + util.format.apply(this, arguments) + "\n",
        function() {
          return;
        }
      );
    }
  }
  return console_error.apply(this, arguments);
};

/*******************************************
* Prepare web server to handle cookies and
* format JSON.
*******************************************/

app.set("json spaces", 2);

//console.log(config.output_log);
if (fs.existsSync(path.join(__dirname, config_name))) {
  //Load the congfig file
  console.log("Loading " + config_name + "...");
  config = require("./" + config_name);
}

if (fs.existsSync(path.join(__dirname, use_name))) {
  //Load the congfig file
  console.log("Loading " + use_name + "...");
  var mid_ware = require("./" + use_name);
  if (typeof mid_ware === "function") {
    mid_ware(app);
  } else {
    console.error("Use file is malformed.");
  }
}

//Set default config items
!config.output_log
  ? (config.output_log = path.dirname(process.argv[1]) + "/js-cgi.log")
  : "";
!config.error_log
  ? (config.error_log = path.dirname(process.argv[1]) + "/err.log")
  : "";
!config.port ? (config.port = 3000) : "";
!config.localhostOnly ? (config.localhostOnly = true) : "";
!config.timeout ? (config.timeout = 30000) : "";
!config.workers ? (config.workers = os.cpus().length - 1) : ""; //Subtract one for the master
!config.watch_required ? (config.watch_required = false) : "";

/*******************************************
* Override the "require" function to watch
* if required files have change and expire
* them from cache when they do.
*******************************************/
var assert = require("assert").ok,
  Module = require("module");
if (typeof Module._watching !== "object") {
  Module._watching = {};
}
function watchRequired(fn) {
  /*var fs = require('fs')
    console = console;*/
  //console.log(fn);
  if (Module._watching && !Module._watching.hasOwnProperty(fn)) {
    if (fs.existsSync(fn) && !Module._watching.hasOwnProperty(fn)) {
      console.log("Watching " + fn);
      Module._watching[fn] = fs.watch(fn, (event, f) => {
        //Module._watching[fn] = fs.watchFile(fn, function(curr, prev){
        console.log(fn, event);

        if (Module._cache.hasOwnProperty(fn)) {
          console.log("Expiring " + fn);
          //fs.unwatch(fn, function(){return;});
          return delete Module._cache[fn];
        }
        return;
      });
    }
  }
}

Module.prototype.require = function(path) {
  assert(path, "missing path");
  assert(typeof path === "string", "path must be a string");
  if (config.watch_required) {
    watchRequired(Module._resolveFilename(path, this));
  }
  return Module._load(path, this);
};

/*******************************************
* Start up the server node.
*******************************************/
if (cluster.isMaster) {
  cluster.globals = {};
  cluster.fork().on("error", console.error); //At least one worker is required.
  console.log(process.versions);
  for (var w = 2; w <= config.workers; w++) {
    cluster.fork().on("error", console.error);
  }

  cluster.on("disconnect", worker => {
    cluster.fork().on("error", console.error);
  });

  cluster.on("listening", (worker, address) => {
    console.log("A worker is now connected to " + JSON.stringify(address));
  });
} else {
  // the worker
  var domain = require("domain"),
    server,
    d = domain.create();

  d.on("error", err => {
    console.error("Domain Error:", err, err.stack);
    //console.trace();
    try {
      // make sure we close down if it times out
      //var killtimer = setTimeout(() => {
      //var err = new Error('Killing process.');

      //console.error('Domain Error:', err);
      //console.trace();
      console.log("Killing process.");
      process.exit(1);
      //}, config.timeout);

      // But don't keep the process open just for that!
      //killtimer.unref();

      // stop taking new requests.
      server.close();

      // Let the master know we're dead.  This will trigger a
      // 'disconnect' in the cluster master, and then it will fork
      // a new worker.
      cluster.worker.disconnect();
    } catch (er2) {
      // oh well, not much we can do at this point.
      console.error(er2);
    }
  });

  /*******************************************
    * Now run the handler function in the domain.
    *******************************************/
  d.run(() => {
    console.log("Listening on " + config.port);

    server = app.listen(config.port);

    app.all("*", (req, res) => {
      //console.log('req');
      return handleRequest(req, res);
    });
  });
}

/*******************************************
* This is where all of the web requests are
* handled.
*******************************************/
function handleRequest(req, res) {
  //console.log('request:', req);
  var url_obj = url.parse(req.url, true),
      file_path;
  console.log(req.headers);
  /*var cache = [],
    j = JSON.stringify(req, function(key, value) {

      if (typeof value === 'object' && value !== null) {
        var idx = _.findIndex(cache, value);
        if (idx > -1) {return '[Circular '+idx+']';}
        cache.push(value);
      }
    return value;
  });

  res.send(j);*/
  //console.log('req.connection.remoteFamily:', '"'+req.connection.remoteFamily+'"');
  //console.log('req.connection.remoteAddress:', '"'+req.connection.remoteAddress+'"');
  if (config.localhostOnly) {
    if (
      (req.connection.remoteFamily === "IPv4" &&
        req.connection.remoteAddress !== "127.0.0.1") ||
      (req.connection.remoteFamily === "IPv6" &&
        (!_.endsWith(req.connection.remoteAddress, "::1") &&
          !_.endsWith(req.connection.remoteAddress, ":127.0.0.1")))
    ) {
      return res.sendStatus(401);
    }
  }

  //Set to the directory path
  if (!req.headers.path_translated) {
    req.headers.path_translated = __dirname + "/www";
    //console.log(req.headers.path_translated);
    if (!fs.existsSync(req.headers.path_translated)) {
      fs.mkdirSync(req.headers.path_translated);
    }
  }

  //
  if(req.headers.path_translated && req.headers.script_name)
    file_path = req.headers.path_translated + req.headers.script_name;
  else if (req.headers.path_translated && url_obj.pathname) {
    file_path = req.headers.path_translated + url_obj.pathname;
  } else {
    file_path = url_obj.pathname;
  }
  console.log(req.method + ": " + file_path);
  function resolveModule(module) {
    if (module.charAt(0) !== ".") {
      return module;
    }
    return path.resolve(path.dirname(file_path), module);
  }

  //If the requested file exists...
  fs.exists(file_path, exists => {
    if (exists) {
      fs.readFile(file_path, (err, source) => {
        if (err) {
          //Error reading file
          console.error(err);
          return res
            .status(500)
            .send({ error: err.toString(), stack: err.stack });
        }
        try {
          //console.log(require.cache);
          //var timer = 'not set';
          req.timeout = config.timeout;
          var timer,
              sandbox = {
                console: console,
                setImmediate: setImmediate,
                setInterval: setInterval,
                setTimeout: setTimeout,
                clearTimeout: clearTimeout,
                Buffer: Buffer,
                JSON: JSON,
                require: function(name) {
                  var mod_path = resolveModule(name);
                  //watchRequired(mod_path);
                  return require(mod_path);
                },
                req: req,
                res: res,
                process: process,
                __dirname: path.dirname(file_path)
              },
              setKilltimer = function() {
                //!req.timeout ? (req.timeout = config.timeout) : "";
                var to_start = Date.now();
                var timeout = req.timeout;
                if (timeout > 0) {
                  return setTimeout(() => {
                    var to_end = Date.now(),
                        msg =
                          "Timeout expired (" +
                          (to_end - to_start) +
                          " ms) for " +
                          file_path,
                        err;

                    //if(!res.headerSent){
                    res.status(408).send(msg);
                    //}
                    //err = new Error(msg);
                    console.error(msg);
                    return;
                  }, req.timeout);
                }
              };
          /****************************
          * Capture "res.send" and
          * "res.sendFile" calls to
          * be able to unset timeout
          * when the script ends. */
          var send = res.send;
          res.send = function(){
            if(timer){
              console.log('timeout cleared');
              clearTimeout(timer);
            }
            return send.apply(this, arguments);
          };
          var sendFile = res.sendFile;
          res.sendFile = function(){
            if(timer){
              console.log('timeout cleared');
              clearTimeout(timer);
            }
            return sendFile.apply(this, arguments);
          }
          /***************************/

          /*****************
           * Start VM Code *
           *****************/
          var c = vm.createContext(sandbox),
              code = `function runInContext() {try{${source}                          //0
                          if(typeof cgi === 'function'){                              //1
                            cgi(req, res);                                            //2
                          }                                                           //3
                        }catch(e){                                                    //4
                          console.error(e);                                           //5
                          res.status(500).send({error: e.toString(), stack: e.stack});//6
                        }                                                             //7
                      }                                                               //8
                                                                                //9
                      runInContext();`;
          /***************
          * End VM Code *
          ***************/

          /***************************************************
           * Set the kill timer after executing the script so
           * the script can set the timeout duration.
           ***************************************************/
          var result = vm.runInContext(code, c, file_path);
          timer = setKilltimer();
          return result;
        } catch (err) {
          console.error(err);
          return res
            .status(500)
            .send({ error: err.toString(), stack: err.stack });
        }
      });
    } else {
      //File does not exist
      return res.status(404).send("File not found. " + file_path);
    }
  });
}
<|endoftext|>


<commit_before>import React, { Component } from "react"
import { Link, withRouter } from "react-router-dom"
import { connect } from "react-redux"
import Skeleton from "react-loading-skeleton"
import AppBar from "@material-ui/core/AppBar"
import Tabs from "@material-ui/core/Tabs"
import Tab from "@material-ui/core/Tab"
import Typography from "@material-ui/core/Typography"

import OntologyTabContainer from "./OntologyTabContainer"
import { tabLabels } from "common/constants/tabLabels"
import { fetchGeneralData } from "features/Summary/summaryActions"
import { fetchGoa } from "features/Ontology/goaActions"

const TabContainer = props => {
  return (
    <Typography component="div" style={{ padding: 8 * 2 }}>
      {props.children}
    </Typography>
  )
}

export class OntologyContainer extends Component {
  state = {
    value: "goa",
  }

  componentDidMount() {
    const { fetchGeneralData, fetchGoa, match } = this.props
    const mainUrl = `${process.env.REACT_APP_API_SERVER}/${match.params.id}`
    const goaUrl = `${process.env.REACT_APP_API_SERVER}/${match.params.id}/goas`
    fetchGeneralData(mainUrl)
    fetchGoa(goaUrl)
  }

  handleChange = (event, value) => {
    this.setState({ value })
  }

  // generates tabs dynamically based on json data structure
  generateTabs = json => {
    const { match } = this.props
    const tabs = json.data.attributes.group.map((item, index) => {
      if (!tabLabels[item]) {
        return
Error: data not mapped to tab

      }
      return (
        <Tab
          value={item}
          label={tabLabels[item]}
          key={index}
          component={Link}
          to={`/${match.params.id}/${item}`}
        />
      )
    })
    return tabs
  }

  render() {
    const { value } = this.state
    const { match, general, goa } = this.props

    if (goa.error) {
      return (

          Sorry! There was an error loading the items

      )
    }

    if (general.isFetching || goa.isFetching) {
      return (

          <Skeleton count={10} />

      )
    }

    return (

        <AppBar position="static">
          <Tabs value={false} onChange={this.handleChange}>
            <Tab
              value="summary"
              label="Gene Summary"
              component={Link}
              to={`/${match.params.id}`}
            />
            {general.data && this.generateTabs(general.data)}
          </Tabs>
        </AppBar>
        {value === "goa" && (
          <TabContainer>
            <OntologyTabContainer />
          </TabContainer>
        )}

    )
  }
}

const mapStateToProps = ({ general, goa }) => ({ general, goa })

export default withRouter(
  connect(
    mapStateToProps,
    { fetchGeneralData, fetchGoa },
  )(OntologyContainer),
)
<commit_msg>remove unnecessary state from OntologyContainer<commit_after>import React, { Component } from "react"
import { Link, withRouter } from "react-router-dom"
import { connect } from "react-redux"
import Skeleton from "react-loading-skeleton"
import AppBar from "@material-ui/core/AppBar"
import Tabs from "@material-ui/core/Tabs"
import Tab from "@material-ui/core/Tab"
import Typography from "@material-ui/core/Typography"

import OntologyTabContainer from "./OntologyTabContainer"
import { tabLabels } from "common/constants/tabLabels"
import { fetchGeneralData } from "features/Summary/summaryActions"
import { fetchGoa } from "features/Ontology/goaActions"

const TabContainer = props => {
  return (
    <Typography component="div" style={{ padding: 8 * 2 }}>
      {props.children}
    </Typography>
  )
}

export class OntologyContainer extends Component {
  componentDidMount() {
    const { fetchGeneralData, fetchGoa, match } = this.props
    const mainUrl = `${process.env.REACT_APP_API_SERVER}/${match.params.id}`
    const goaUrl = `${process.env.REACT_APP_API_SERVER}/${match.params.id}/goas`
    fetchGeneralData(mainUrl)
    fetchGoa(goaUrl)
  }

  handleChange = (event, value) => {
    this.setState({ value })
  }

  // generates tabs dynamically based on json data structure
  generateTabs = json => {
    const { match } = this.props
    const tabs = json.data.attributes.group.map((item, index) => {
      if (!tabLabels[item]) {
        return
Error: data not mapped to tab

      }
      return (
        <Tab
          value={item}
          label={tabLabels[item]}
          key={index}
          component={Link}
          to={`/${match.params.id}/${item}`}
        />
      )
    })
    return tabs
  }

  render() {
    const { match, general, goa } = this.props

    if (goa.error) {
      return (

          Sorry! There was an error loading the items

      )
    }

    if (general.isFetching || goa.isFetching) {
      return (

          <Skeleton count={10} />

      )
    }

    return (

        <AppBar position="static">
          <Tabs value="goa" onChange={this.handleChange}>
            <Tab
              value="summary"
              label="Gene Summary"
              component={Link}
              to={`/${match.params.id}`}
            />
            {general.data && this.generateTabs(general.data)}
          </Tabs>
        </AppBar>
        <TabContainer>
          <OntologyTabContainer />
        </TabContainer>

    )
  }
}

const mapStateToProps = ({ general, goa }) => ({ general, goa })

export default withRouter(
  connect(
    mapStateToProps,
    { fetchGeneralData, fetchGoa },
  )(OntologyContainer),
)
<|endoftext|>


<commit_before>Ext.define('BurnChartApp', {
    extend:'Rally.app.App',
    mixins: {
        messageable: 'Rally.Messageable'
    },
    layout: {
        type: 'hbox',
        align: 'stretch'
    },
    appName:'Burn Chart',
    cls:'burnchart',

    launch: function () {
        this.chartConfigBuilder = Ext.create('Rally.app.analytics.BurnChartBuilder');

		var reportControls = this._buildReportControls();
		var chartFilteringControls = this._buildChartFilteringControls();

		// Button
		var runQueryButton = Ext.create('Ext.Container', {
			items: [{
				xtype: 'rallybutton',
				text: 'Build Chart',
				handler: Ext.bind(this._refreshChart, this)
			}]
		});

		var leftNavigation = Ext.create('Ext.Container', {
			items: [reportControls, chartFilteringControls, runQueryButton],
			flex: 1,
			defaults: {
				padding: '5 0 0 0'
			}
		});

		this.add(leftNavigation);
		this.add({
			id: 'chartCmp',
			flex: 2,
			border: 0
		});
    },

	_buildReportControls: function () {
		var reportContainer = Ext.create('Ext.panel.Panel', {
			title: 'Standard Reports',
			layout: {
				type: 'fit'
			},
			defaults: {
				padding: '2 0 2 0'
			}
		});

		this.reportStore = Ext.create('Ext.data.Store', {
			fields: ['display'],
			data: [
				{'display': 'Released - Critical/High'},
				{'display': 'Blocked'}
			],
			filterInfo: {
				'Released - Critical/High': {
					State: ['Submitted', 'Open', 'Fixed/Resolved'],
					ReleasedDefect: [true],
					Priority: ['Critical', 'High']
				},
				"Blocked": {
					State: ['Submitted', 'Open', 'Fixed/Resolved'],
					Blocked: [true]
				}
			}
		});

		this.reportComboBox = Ext.create('Ext.form.ComboBox', {
			fieldLabel: "Report",
			store: this.reportStore,
			queryMode: 'local',
			displayField: 'display',
			valueField: 'display',
			listeners: {
				select: Ext.bind(this._reportSelected, this)
			}
		});

		reportContainer.add(this.reportComboBox);

		return reportContainer;
	},

	_reportSelected: function(comboBox, records){
		var selectedReport = records[0].data.display;
		var filterInfo = this.reportStore.filterInfo[selectedReport];

		var fields = _.keys(filterInfo);
		fields = _.without(fields, 'State');
		this.defectFieldPicker.setValue(fields);

		for(var key in filterInfo)
		{
			var cntrl = Ext.getCmp(key);
			if(_.isUndefined(cntrl)) {
				alert('Missing control: ' + key);
			}
			else {
				cntrl.setValue(filterInfo[key]);
			}
		}
	},

	_buildChartFilteringControls: function() {
		var filterContainer = Ext.create('Ext.panel.Panel', {
			title: 'Chart Filtering',
			layout: {
				type: 'fit'
			},
			defaults: {
				padding: '2 2 0 2'
			}
		});

		// State Picker
		this.defectStatePicker = Ext.create('Rally.ui.AttributeComboBox', {
				id: 'State',
				model: 'Defect',
				field: 'State',
				fieldLabel: 'State',
				multiSelect: true
			});

		this.defectStatePickerContainer = Ext.create('Ext.Container', {
			items: [this.defectStatePicker]
		});
		filterContainer.add( this.defectStatePickerContainer );

		this.startTimePicker = Ext.create('Rally.ui.DateField', {
			fieldLabel: 'Start Date',
			value: new Date().add(-1).month()
		});
		this.startTimePickerContainer = Ext.create('Ext.Container', {
			items: [this.startTimePicker]
		});
		filterContainer.add( this.startTimePickerContainer );

		this.endTimePicker = Ext.create('Rally.ui.DateField', {
			fieldLabel: 'End Date',
			value: new Date().add(1).days()
		});
		this.endTimePickerContainer = Ext.create('Ext.Container', {
			items: [this.endTimePicker]
		});
		filterContainer.add( this.endTimePickerContainer );

		// Customer Filter Picker
		this.defectFieldPicker = Ext.create('DefectFieldComboBox', {
			model: 'Defect',
			fieldLabel: 'Custom Filters',
			multiSelect: true,
			listeners:{
				change: Ext.bind(this._defectFieldSelectionChanged, this)
			}
		});

		this.defectFieldPickerContainer = Ext.create('Ext.Container', {
			items: [this.defectFieldPicker ]
		});
		filterContainer.add( this.defectFieldPickerContainer );

		// Custom Filter Container
		this.customFilterContainer = Ext.create('Ext.panel.Panel', {
			title: 'Custom Filters',
			hidden: true,
			padding: '5 5 5 5',
			items: [],
			layout: 'fit',
			defaults: {
				padding: '2 0 0 0'
			}
		});
		filterContainer.add( this.customFilterContainer );

		return filterContainer;
	},

	_defectFieldSelectionChanged: function(comboBox, newFields, oldFields){
		newFields = _.isUndefined(newFields) ? [] : newFields;
		oldFields = _.isUndefined(oldFields) ? [] : oldFields;

		var added = _.difference(newFields, oldFields);
		var removed = _.difference(oldFields, newFields);

		if(newFields.length === 0)
			this.customFilterContainer.hide();
		else
			this.customFilterContainer.show();

		var labelWidth = 120;
		for (var i in added) {
			if(this.defectFieldPicker.fieldTypes[added[i]] === 'bool') {
				var filterStore = Ext.create('Ext.data.Store', {
					fields: ['display', 'value'],
					data: [
						{"display":'True', value: true},
						{"display":'False', value: false}
					]
				});

				var newFilter = Ext.create('Ext.form.ComboBox', {
					id: added[i],
					fieldLabel: added[i],
					labelWidth: labelWidth,
					multiSelect: true,
					store: filterStore,
					queryMode: 'local',
					displayField: 'display',
					valueField: 'value'
				});
			}
			else {
				var newFilter = Ext.create('Rally.ui.AttributeComboBox', {
					id: added[i],
					model: 'Defect',
					field: added[i],
					fieldLabel: added[i],
					labelWidth: labelWidth,
					multiSelect: true
				});
			}
			this.customFilterContainer.add(newFilter);
		}
		for (var i in removed) {
			this.customFilterContainer.remove(Ext.getCmp(removed[i]));
		}

		this.customFilterContainer.doLayout();
	},

	_afterChartConfigBuilt: function (success, chartConfig) {
		this.getEl().unmask('Loading...');
        this._removeChartComponent();
        if (success){
            this.add({
                id: 'chartCmp',
                xtype: 'highchart',
                flex: 2,
                chartConfig: chartConfig
            });
        } else {
            this.add({
                id: 'chartCmp',
				flex: 2,
                xtype: 'component',
                html: '
No user story data found. :(
'
            });
        }
    },

    _removeChartComponent: function() {
        var chartCmp = this.down('#chartCmp');
        if (chartCmp) {
            this.remove(chartCmp);
        }
    },

    _refreshChart: function() {
		this.chartQuery = this._buildChartQuery();
		this.getEl().mask('Loading...');
		this.chartConfigBuilder.build(this.chartQuery, this.startTimePicker.getValue().toISOString(), this.endTimePicker.getValue().toISOString(),
			"Defect Count", Ext.bind(this._afterChartConfigBuilt, this));
    },

	_buildChartQuery: function(){
        var chartQuery = {
            find:{
                _Type:'Defect'
            }
        };

		chartQuery.find._ProjectHierarchy = Rally.environment.getContext().getScope().project.ObjectID;

		var defectStates = this.defectStatePicker.getValue();
		chartQuery.find.State = {$in:defectStates};

		var filterItems = this.customFilterContainer.query('pickerfield');
		for (var i in filterItems)
		{
			var filterItem = filterItems[i];
			chartQuery.find[filterItem.id] = {$in:filterItem.getValue()};
		}

		return chartQuery;
	}
});
<commit_msg>Default states on load<commit_after>Ext.define('BurnChartApp', {
    extend:'Rally.app.App',
    mixins: {
        messageable: 'Rally.Messageable'
    },
    layout: {
        type: 'hbox',
        align: 'stretch'
    },
    appName:'Burn Chart',
    cls:'burnchart',

    launch: function () {
        this.chartConfigBuilder = Ext.create('Rally.app.analytics.BurnChartBuilder');

		var reportControls = this._buildReportControls();
		var chartFilteringControls = this._buildChartFilteringControls();

		// Button
		var runQueryButton = Ext.create('Ext.Container', {
			items: [{
				xtype: 'rallybutton',
				text: 'Build Chart',
				handler: Ext.bind(this._refreshChart, this)
			}]
		});

		var leftNavigation = Ext.create('Ext.Container', {
			items: [reportControls, chartFilteringControls, runQueryButton],
			flex: 1,
			defaults: {
				padding: '5 0 0 0'
			}
		});

		this.add(leftNavigation);
		this.add({
			id: 'chartCmp',
			flex: 2,
			border: 0
		});
    },

	_buildReportControls: function () {
		var reportContainer = Ext.create('Ext.panel.Panel', {
			title: 'Standard Reports',
			layout: {
				type: 'fit'
			},
			defaults: {
				padding: '2 0 2 0'
			}
		});

		this.reportStore = Ext.create('Ext.data.Store', {
			fields: ['display'],
			data: [
				{'display': 'Released - Critical/High'},
				{'display': 'Blocked'}
			],
			filterInfo: {
				'Released - Critical/High': {
					State: ['Submitted', 'Open', 'Fixed/Resolved'],
					ReleasedDefect: [true],
					Priority: ['Critical', 'High']
				},
				"Blocked": {
					State: ['Submitted', 'Open', 'Fixed/Resolved'],
					Blocked: [true]
				}
			}
		});

		this.reportComboBox = Ext.create('Ext.form.ComboBox', {
			fieldLabel: "Report",
			store: this.reportStore,
			queryMode: 'local',
			displayField: 'display',
			valueField: 'display',
			listeners: {
				select: Ext.bind(this._reportSelected, this)
			}
		});

		reportContainer.add(this.reportComboBox);

		return reportContainer;
	},

	_reportSelected: function(comboBox, records){
		var selectedReport = records[0].data.display;
		var filterInfo = this.reportStore.filterInfo[selectedReport];

		var fields = _.keys(filterInfo);
		fields = _.without(fields, 'State');
		this.defectFieldPicker.setValue(fields);

		for(var key in filterInfo)
		{
			var cntrl = Ext.getCmp(key);
			if(_.isUndefined(cntrl)) {
				alert('Missing control: ' + key);
			}
			else {
				cntrl.setValue(filterInfo[key]);
			}
		}
	},

	_buildChartFilteringControls: function() {
		var filterContainer = Ext.create('Ext.panel.Panel', {
			title: 'Chart Filtering',
			layout: {
				type: 'fit'
			},
			defaults: {
				padding: '2 2 0 2'
			}
		});

		// State Picker
		this.defectStatePicker = Ext.create('Rally.ui.AttributeComboBox', {
				id: 'State',
				model: 'Defect',
				field: 'State',
				fieldLabel: 'State',
				multiSelect: true,
				listeners:{
					ready: function(comboBox){
						comboBox.setValue(['Submitted', 'Open']);
					}
				}
			});

		this.defectStatePickerContainer = Ext.create('Ext.Container', {
			items: [this.defectStatePicker]
		});
		filterContainer.add( this.defectStatePickerContainer );

		this.startTimePicker = Ext.create('Rally.ui.DateField', {
			fieldLabel: 'Start Date',
			value: new Date().add(-1).month()
		});
		this.startTimePickerContainer = Ext.create('Ext.Container', {
			items: [this.startTimePicker]
		});
		filterContainer.add( this.startTimePickerContainer );

		this.endTimePicker = Ext.create('Rally.ui.DateField', {
			fieldLabel: 'End Date',
			value: new Date().add(1).days()
		});
		this.endTimePickerContainer = Ext.create('Ext.Container', {
			items: [this.endTimePicker]
		});
		filterContainer.add( this.endTimePickerContainer );

		// Customer Filter Picker
		this.defectFieldPicker = Ext.create('DefectFieldComboBox', {
			model: 'Defect',
			fieldLabel: 'Custom Filters',
			multiSelect: true,
			listeners:{
				change: Ext.bind(this._defectFieldSelectionChanged, this)
			}
		});

		this.defectFieldPickerContainer = Ext.create('Ext.Container', {
			items: [this.defectFieldPicker ]
		});
		filterContainer.add( this.defectFieldPickerContainer );

		// Custom Filter Container
		this.customFilterContainer = Ext.create('Ext.panel.Panel', {
			title: 'Custom Filters',
			hidden: true,
			padding: '5 5 5 5',
			items: [],
			layout: 'fit',
			defaults: {
				padding: '2 0 0 0'
			}
		});
		filterContainer.add( this.customFilterContainer );

		return filterContainer;
	},

	_defectFieldSelectionChanged: function(comboBox, newFields, oldFields){
		newFields = _.isUndefined(newFields) ? [] : newFields;
		oldFields = _.isUndefined(oldFields) ? [] : oldFields;

		var added = _.difference(newFields, oldFields);
		var removed = _.difference(oldFields, newFields);

		if(newFields.length === 0)
			this.customFilterContainer.hide();
		else
			this.customFilterContainer.show();

		var labelWidth = 120;
		for (var i in added) {
			if(this.defectFieldPicker.fieldTypes[added[i]] === 'bool') {
				var filterStore = Ext.create('Ext.data.Store', {
					fields: ['display', 'value'],
					data: [
						{"display":'True', value: true},
						{"display":'False', value: false}
					]
				});

				var newFilter = Ext.create('Ext.form.ComboBox', {
					id: added[i],
					fieldLabel: added[i],
					labelWidth: labelWidth,
					multiSelect: true,
					store: filterStore,
					queryMode: 'local',
					displayField: 'display',
					valueField: 'value'
				});
			}
			else {
				var newFilter = Ext.create('Rally.ui.AttributeComboBox', {
					id: added[i],
					model: 'Defect',
					field: added[i],
					fieldLabel: added[i],
					labelWidth: labelWidth,
					multiSelect: true
				});
			}
			this.customFilterContainer.add(newFilter);
		}
		for (var i in removed) {
			this.customFilterContainer.remove(Ext.getCmp(removed[i]));
		}

		this.customFilterContainer.doLayout();
	},

	_afterChartConfigBuilt: function (success, chartConfig) {
		this.getEl().unmask('Loading...');
        this._removeChartComponent();
        if (success){
            this.add({
                id: 'chartCmp',
                xtype: 'highchart',
                flex: 2,
                chartConfig: chartConfig
            });
        } else {
            this.add({
                id: 'chartCmp',
				flex: 2,
                xtype: 'component',
                html: '
No user story data found. :(
'
            });
        }
    },

    _removeChartComponent: function() {
        var chartCmp = this.down('#chartCmp');
        if (chartCmp) {
            this.remove(chartCmp);
        }
    },

    _refreshChart: function() {
		this.chartQuery = this._buildChartQuery();
		this.getEl().mask('Loading...');
		this.chartConfigBuilder.build(this.chartQuery, this.startTimePicker.getValue().toISOString(), this.endTimePicker.getValue().toISOString(),
			"Defect Count", Ext.bind(this._afterChartConfigBuilt, this));
    },

	_buildChartQuery: function(){
        var chartQuery = {
            find:{
                _Type:'Defect'
            }
        };

		chartQuery.find._ProjectHierarchy = Rally.environment.getContext().getScope().project.ObjectID;

		var defectStates = this.defectStatePicker.getValue();
		chartQuery.find.State = {$in:defectStates};

		var filterItems = this.customFilterContainer.query('pickerfield');
		for (var i in filterItems)
		{
			var filterItem = filterItems[i];
			chartQuery.find[filterItem.id] = {$in:filterItem.getValue()};
		}

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


<commit_before>function GOL() {
	this.numRows = 0;
	this.numCols = 0;
	this.currentGeneration = [];
	this.nextGeneration = [];
	this.population = 0;
}

GOL.prototype.init = function () {
	this.numRows = Math.floor((canvas.height - 1) / Life.UI.cellSize);
	this.numCols = Math.floor((canvas.width - 1) / Life.UI.cellSize);

	for(var i = 0; i < this.numRows; ++i) {
		this.currentGeneration[i] = [];
		this.nextGeneration[i] = [];

		for(var j = 0; j < this.numCols; ++j) {
			this.currentGeneration[i][j] = false;
			this.nextGeneration[i][j] = false;
		}
	}
}

GOL.prototype.getNumberOfNeighbors = function (row, col) {
	var neighbors = [
                this.currentGeneration[row][(col - 1 + this.numCols) % this.numCols],
                this.currentGeneration[(row + 1 + this.numRows) % this.numRows][(col - 1 + this.numCols) % this.numCols],
                this.currentGeneration[(row + 1 + this.numRows) % this.numRows][col],
                this.currentGeneration[(row + 1 + this.numRows) % this.numRows][(col + 1 + this.numCols) % this.numCols],
                this.currentGeneration[row][(col + 1 + this.numCols) % this.numCols],
                this.currentGeneration[(row - 1 + this.numRows) % this.numRows][(col + 1 + this.numCols) % this.numCols],
                this.currentGeneration[(row - 1 + this.numRows) % this.numRows][col],
                this.currentGeneration[(row - 1 + this.numRows) % this.numRows][(col - 1 + this.numCols) % this.numCols]
            ];
	var numNeighbors = 0;

	for (var i = 0; i < neighbors.length; ++i) {
		if (neighbors[i]) {
			++numNeighbors;
		}
	}

	return numNeighbors;
}

GOL.prototype.getNextGeneration = function () {
	var i, j;

	this.nextGeneration = this.currentGeneration;
	for (i = 0; i < this.numRows; ++i) {
		for (j = 0; j < this.numCols; ++j) {
			var count = this.getNumberOfNeighbors(i, j);

			if (this.currentGeneration[i][j]) {
				if (count < 2 || count > 3) {
					this.nextGeneration[i][j] = false;
				}
			} else if (count == 3) {
				this.nextGeneration[i][j] = true;
			}
		}
	}
	this.currentGeneration = this.nextGeneration;
}

GOL.prototype.getPopulation = function () {
	var population = 0;
	for (var i = 0; i < this.numRows; ++i) {
		for (var j = 0; j < this.numCols; ++j) {
			if (this.currentGeneration[i][j]) {
				++population;
			}
		}
	}

	this.population = population;
}
<commit_msg>Solver initialization function prototype completed.<commit_after>function Solver() {
	this.numRows = 0;
	this.numCols = 0;
	this.maze = [];
	this.distances = [];
	this.visited = [];
	this.path = [];
	this.numNodes = 0;
}

GOL.prototype.init = function () {
	this.numRows = Math.floor((canvas.height - 1) / Life.UI.cellSize);
	this.numCols = Math.floor((canvas.width - 1) / Life.UI.cellSize);
	this.numNodes = numRows * numCols;

	for (var i = 0; i < numNodes; ++i) {
	    this.distances[i] = null;
	    this.visited[i] = false;
	    this.path[i] = null;
	}

	for (var i = 0; i < this.numNodes; ++i) {
	    maze[i] = [];
	    for (var j = 0; j < this.numNodes; ++j) {
	        maze[i][j] = false;
	    }
	}

	for (var i = 0; i < this.numRows; ++i) {
	    for (var j = 0; j < this.numCols; ++j) {
	        currentNode = i * this.numCols + j
	        if (i != this.numRows - 1 && j != this.numCols -1) {
	            if (i == this.numRows - 1) {
	                maze[currentNode][currentNode + 1] = true;
	            } else if (j = this.numCols - 1) {
	                maze[currentNode + 1][currentNode] = true;
	            } else {
	                maze[currentNode][currentNode + 1] = true;
	                maze[currentNode + 1][currentNode] = true;
	            }
	        }
	    }
	}
}

<|endoftext|>


<commit_before>/**
 * @author aymanhab based on mr. doob
 */

Sidebar.SceneSettings = function (editor) {

    var config = editor.config;
    var signals = editor.signals;

    var backgrounds = {
        'nobackground': 'No Background',
        'sky': 'Sky',
        'desert': 'Desert'
    };

    var floorpatterns = {
        'nofloor': 'No Floor',
        'redbricks': 'Red Bricks',
        'graybricks': 'Gray Bricks',
        'wood-floor': 'Wood',
        'tile': 'Tiles'
    };

    var container = new UI.CollapsiblePanel();
    container.setCollapsed(config.getKey('ui/sidebar/scenesettings/collapsed'));
    container.onCollapsedChange(function (boolean) {

        config.setKey('ui/sidebar/scenesettings/collapsed', boolean);

    });

    container.addStatic(new UI.Text('SCENE SETTINGS'));
    container.add(new UI.Break());

    // Background

    var backgroundTypeRow = new UI.Panel();
    var backgroundType = new UI.Select().setOptions(backgrounds).setWidth('150px').onChange(function () {

        var value = this.getValue();

        config.setKey('background', value);

        // change  editor.config
        editor.updateBackground(value);
    });

    backgroundTypeRow.add(new UI.Text('Background').setWidth('90px'));
    backgroundTypeRow.add(backgroundType);

    container.add(backgroundTypeRow);

    // Floor
    var floorTypeRow = new UI.Panel();
    var floorType = new UI.Select().setOptions(floorpatterns).setWidth('150px').onChange(function () {

        var value = this.getValue();

        config.setKey('floor', value);
        // change  editor.config
        editor.updateGroundPlane(value);
    });

    floorTypeRow.add(new UI.Text('Ground').setWidth('90px'));
    floorTypeRow.add(floorType);

    container.add(floorTypeRow);

    // shadow
    /*
        var rendererShadowsSpan = new UI.Span();
        var rendererShadows = new UI.Checkbox( config.getKey( 'project/renderer/shadows' ) ).setLeft( '100px' ).onChange( function () {

            config.setKey( 'project/renderer/shadows', this.getValue() );
            updateRenderer();

        } );

        rendererShadowsSpan.add( rendererShadows );
        rendererShadowsSpan.add( new UI.Text( 'shadows' ).setMarginLeft( '3px' ) );

        rendererPropertiesRow.add( rendererShadowsSpan );

        container.add( rendererPropertiesRow );
    */
    return container;

};
<commit_msg>set default options in dropdown to match initialization code for ground and skybox.<commit_after>/**
 * @author aymanhab based on mr. doob
 */

Sidebar.SceneSettings = function (editor) {

    var config = editor.config;
    var signals = editor.signals;

    var backgrounds = {
        'nobackground': 'No Background',
        'sky': 'Sky',
        'desert': 'Desert'
    };

    var floorpatterns = {
        'nofloor': 'No Floor',
        'redbricks': 'Red Bricks',
        'graybricks': 'Gray Bricks',
        'wood-floor': 'Wood',
        'tile': 'Tiles'
    };

    var container = new UI.CollapsiblePanel();
    container.setCollapsed(config.getKey('ui/sidebar/scenesettings/collapsed'));
    container.onCollapsedChange(function (boolean) {

        config.setKey('ui/sidebar/scenesettings/collapsed', boolean);

    });

    container.addStatic(new UI.Text('SCENE SETTINGS'));
    container.add(new UI.Break());

    // Background

    var backgroundTypeRow = new UI.Panel();
    var backgroundType = new UI.Select().setOptions(backgrounds).setWidth('150px').onChange(function () {

        var value = this.getValue();

        config.setKey('background', value);

        // change  editor.config
        editor.updateBackground(value);
    });
    backgroundType.setValue('sky');
    backgroundTypeRow.add(new UI.Text('Background').setWidth('90px'));
    backgroundTypeRow.add(backgroundType);

    container.add(backgroundTypeRow);

    // Floor
    var floorTypeRow = new UI.Panel();
    var floorType = new UI.Select().setOptions(floorpatterns).setWidth('150px').onChange(function () {

        var value = this.getValue();

        config.setKey('floor', value);
        // change  editor.config
        editor.updateGroundPlane(value);
    });
    floorType.setValue('redbricks');
    floorTypeRow.add(new UI.Text('Ground').setWidth('90px'));
    floorTypeRow.add(floorType);

    container.add(floorTypeRow);

    // shadow
    /*
        var rendererShadowsSpan = new UI.Span();
        var rendererShadows = new UI.Checkbox( config.getKey( 'project/renderer/shadows' ) ).setLeft( '100px' ).onChange( function () {

            config.setKey( 'project/renderer/shadows', this.getValue() );
            updateRenderer();

        } );

        rendererShadowsSpan.add( rendererShadows );
        rendererShadowsSpan.add( new UI.Text( 'shadows' ).setMarginLeft( '3px' ) );

        rendererPropertiesRow.add( rendererShadowsSpan );

        container.add( rendererPropertiesRow );
    */
    return container;

};
<|endoftext|>


<commit_before>const path              = require('path');
const Promise           = require('bluebird');
const retry             = require('bluebird-retry');
const fs                = Promise.promisifyAll(require('fs-extra'));
const StateMachine      = require('javascript-state-machine');

const BuildMCUFirmware  = require( "./lib/BuildMCUFirmware.js" );
const FlashMCUFirmware  = require( "./lib/FlashMCUFirmware.js" );
const FlashESCFirmware  = require( "./lib/FlashESCFirmware.js" );
const ResetMCU          = require( "./lib/ResetMCU.js" );

const escConfPath       = "/opt/openrov/system/config/esc.conf";
const mcuLastBuildPath  = "/opt/openrov/system/config/lastBuildHash";
const mcuBinPath        = "/opt/openrov/firmware/bin/2x/OpenROV2x.hex";
const logger            = require("AppFramework.js").logger.child({module:"stateMachine"});

module.exports = function( board )
{
    const Progress = Object.freeze( { "InProgress":1, "Complete":2, "Failed":3 } );

    function notify(message){
        board.global.emit("notification",message);
    }

    function status( message, progress )
    {
        board.global.emit( "plugin.updateManager.status", { message: message.toString(), progress: progress } );
        logger.debug( "FIRMWARE UPDATE: " + message.toString().trim() );
    }

    function log( data )
    {
        board.global.emit( "plugin.updateManager.log", data.toString() );
        logger.debug( "FIRMWARE UPDATE: " + data.toString().trim() );
    }

    function err( data )
    {
        board.global.emit( "plugin.updateManager.error", data.toString() );
        logger.error(data);
    }

    function escCheckHandler(event, from, to)
    {
        var self = this;

        status( "Checking ESCs...", "Examining" );

        // Check to see if ESCs have been flashed before by testing the existence of esc.conf
        fs.statAsync( escConfPath )
        .then( function()
        {
            // Existence of file suggests ESCs have been flashed already
            log( "ESCs already up to date." );
            self._e_esc_flash_complete();
        })
        .catch( function(error)
        {
            // ESCs have never been flashed before. Do so now
            log( "ESCs haven't been flashed. Triggering flash." );
            self._e_trigger_esc_flash();
        });
    }

    function flashESCHandler(event, from, to)
    {
        var self = this;

        status( "Flashing ESCs...", "InProgress" );
        this.data.flashingAttemped = true;

        // First, disconnect the bridge
        self.board.bridge.close();

        // Execute the flash firmware script
        FlashESCFirmware( log, err )
        .then( function()
        {
            // Successm, write to a file to indicate this
            return fs.writeFileAsync( escConfPath, "flashed" );
        })
        .then( function()
        {
            // Re-enable the bridge
            self.board.bridge.connect();

            // Success
            log( "ESCs flashed successfully." );
            self._e_esc_flash_complete();
        })
        .catch( function( error )
        {
            // Re-enable the bridge
            self.board.bridge.connect();

            // Move to failed state
            err( "ESC flash failed." );
            self._e_fail( error );
        });
    }

    function checkBinHandler(event, from, to)
    {
        var self = this;

        status( "Checking if firmware already built...", "Examining" );

        // Check to see if ESCs have been flashed before by testing the existence of esc.conf
        fs.statAsync( mcuBinPath )
        .then( function()
        {
            // Existence of file suggests firmware has already been built
            log( "Binary already exists" );
            self._e_firmware_build_complete();
        })
        .catch( function(error)
        {
            // Firmware has never been built. Trigger a build
            log( "No binary found. Triggering build." );
            self._e_trigger_firmware_build();
        });
    }

    function buildFirmwareHandler(event, from, to)
    {
        status( "Building firmware...", "InProgress" );
        this.data.flashingAttemped = true;
        var self = this;

        // Execute the build firmware script
        BuildMCUFirmware( log, err )
        .then( function()
        {
            // Success
            log( "Build succeeded" );
            self._e_firmware_build_complete();
        })
        .catch( function( error )
        {
            // Move to failed state
            err( "Build failed" );
            self._e_fail( error );
        });
    }

    function getHashHandler(event, from, to)
    {
        status( "Fetching firmware hash...", "Examining" );

        var self = this;

        // TODO: make this read from a file from somewhere else. Hex doesn't work for clever parsing :(
        fs.readFileAsync( mcuLastBuildPath, 'utf8' )
        .then( function( hash )
        {
            log( "Hash in last build file: " + hash.trim() );

            self.board.hashInfo.fromBin = hash;
        })
        .then( function()
        {
            if( self.board.hashInfo.fromBin != "" )
            {
                // Success
                self._e_hash_obtained();
            }
            else
            {
                err( "Hash was empty!" );

                // Move to failed state
                self._e_fail( error );
            }
        })
        .catch( function( error )
        {
            err( "Failed to find hash file" );

            // Move to failed state
            self._e_fail( error );
        });
    }

    function flashMCUHandler(event, from, to)
    {
        status( "Flashing MCU firmware...", "InProgress" );
        this.data.flashingAttemped = true;
        var self = this;

        // Execute the build firmware script
        retry( function(){ return FlashMCUFirmware( log, err ); }, {interval: 10000})
        .then( function()
        {
            // Success
            log( "Flash succeeded" );
            self._e_mcu_flash_complete();
        })
        .catch( function( error )
        {
            // Move to failed state
            log( "Flash failed" );
            self._e_fail( error );
        });
    }

    function verifyVersionHandler(event, from, to)
    {
        status( "Checking current firmware against latest...", "Examining" );

        var self = this;

        // First, clear out the existing fromMCU hash info
        self.board.hashInfo.fromMCU = "";

        // Now register a timeout that attempts to fetch the updated hash
        var counter = 0;

        var RequestHashInfo = function()
        {
            // Make sure the serial port is open
            if (!self.board.bridge.isConnected())
            {
                logger.debug("Serial Port not connected.. opening and retrying in 300ms");
                self.board.bridge.connect();
                setTimeout(RequestHashInfo.bind(this),300);
                return;
            }
            // Send the version request command to the MCU
            self.board.bridge.write( "version();" );

            log( "MCU reported hash: " + self.board.hashInfo.fromMCU );
            log( "Hash from last build: " + self.board.hashInfo.fromBin );

            // Check for new hash info received from MCU
            if( self.board.hashInfo.fromMCU !== "" )
            {
                // Check it against the binary hash
                if( self.board.hashInfo.fromMCU == self.board.hashInfo.fromBin )
                {
                    // Success
                    log( "MCU Firmware is up to date" );
                    self._e_firmware_validated();
                }
                else
                {
                    // Version mismatch. Flash the latest firmware to the MCU
                    log( "MCU Firmware is out of date. Triggering flash." );
                    self._e_trigger_mcu_flash();
                }
            }
            else if( counter < 6 )
            {
                // Call 5 times, once per 3 secs
                counter++;
                log( "Verification attempt #" + counter );
                setTimeout( RequestHashInfo, 3000 );
            }
            else
            {
                // Never received hash info from MCU. Flash the latest firmware to the MCU
                log( "No firmware detected. Triggering flash." );
                self._e_trigger_mcu_flash();
            }
        };

        RequestHashInfo();
    }

    function resetMCUHandler(event, from, to)
    {
        status( "Resetting MCU...", "InProgress" );

        var self = this;

        ResetMCU()
        .then( function()
        {
            self._e_mcu_reset_complete();
        } )
        .catch( function( error )
        {
            // Move to failed state
            log( "Reset failed" );
            self._e_fail( error );
        });
    }

    function completeHandler(event, from, to)
    {
        status( "Firmware up to date!", "Complete" );
        if (this.data.flashingAttemped){
            notify( "Firmware update applied");
        }
        this.data.flashingAttemped = false;
    }

    function failHandler(event, from, to)
    {
        status( "Firmware update failed!", "Failed" );
        notify( "Firmware update failed");
        this.data.flashingAttemped = false;
    }

    function eFailHandler(event, from, to, msg)
    {
        if( msg == undefined )
        {
            msg = 'No message in failure: ' + event;
        }

        err( "StateMachine error: " + msg );
        this.data.error = JSON.stringify( msg );
    };

    var fsm = StateMachine.create(
    {
        events:
        [
            // Internal events - Should always be called as the final step of a promise chain
            { name: '_e_init',                          from: 'none',                               to: 'checking_escs' },
            { name: '_e_trigger_esc_flash',             from: 'checking_escs',                      to: 'flashing_escs' },
            { name: '_e_esc_flash_complete',            from: ['checking_escs','flashing_escs'] ,   to: 'checking_bin'},
            { name: '_e_trigger_firmware_build',        from: ['checking_bin','complete'],          to: 'building_firmware' },
            { name: '_e_firmware_build_complete',       from: ['checking_bin','building_firmware'], to: 'get_hash' },
            { name: '_e_hash_obtained',                 from: 'get_hash',                           to: 'verify_version' },
            { name: '_e_trigger_mcu_flash',             from: 'verify_version',                     to: 'flashing_mcu' },
            { name: '_e_mcu_flash_complete',            from: 'flashing_mcu',                       to: 'verify_version' },
            { name: '_e_firmware_validated',            from: 'verify_version',                     to: 'complete' },
            { name: '_e_mcu_reset_complete',            from: 'resetting_mcu',                      to: 'complete' },

            // User events (can only be used from the complete state)
            { name: '_e_trigger_esc_flash_user',        from: 'complete',                           to: 'flashing_escs' },
            { name: '_e_trigger_firmware_build_user',   from: 'complete',                           to: 'building_firmware' },
            { name: '_e_trigger_mcu_flash_user',        from: 'complete',                           to: 'flashing_mcu' },
            { name: '_e_trigger_mcu_reset_user',        from: 'complete',                           to: 'resetting_mcu' },
            { name: '_e_reset',                         from: ['complete', 'failed'],               to: 'checking_escs' },

            { name: '_e_fail',                          from: '*',                                  to: 'failed' }
        ],

        callbacks:
        {
            // State handlers - We allow states to handle their own transitions to ensure consistency
            onchecking_escs: escCheckHandler,
            onflashing_escs: flashESCHandler,
            onchecking_bin: checkBinHandler,
            onbuilding_firmware: buildFirmwareHandler,
            onflashing_mcu: flashMCUHandler,
            onget_hash: getHashHandler,
            onverify_version: verifyVersionHandler,
            onresetting_mcu: resetMCUHandler,
            oncomplete: completeHandler,
            onfailed: failHandler,

            // Event handlers
            onbefore_e_fail: eFailHandler
        },

        error: function(eventName, from, to, args, errorCode, errorMessage)
        {
            // The error handler for the statemachine is backed with the above parameters, but since
            // some flows just raise an exception, need to move things around in that case.
            if (eventName instanceof Error)
            {
                e = eventName;
                eventName = "unspecified";
            }

            errorReport =
            {
                eventName: eventName,
                from: from,
                to: to,
                args: args,
                errorCode: errorCode,
                errorMessage: errorMessage,
            }

            err( 'MCU State Machine: Error in event <' + eventName + '>: ' + JSON.stringify(errorReport));
        }
    });

    // Other state information
    fsm.data = {};
    fsm.board = board;

    return fsm;
};
<commit_msg>fix logging of raw data<commit_after>const path              = require('path');
const Promise           = require('bluebird');
const retry             = require('bluebird-retry');
const fs                = Promise.promisifyAll(require('fs-extra'));
const StateMachine      = require('javascript-state-machine');

const BuildMCUFirmware  = require( "./lib/BuildMCUFirmware.js" );
const FlashMCUFirmware  = require( "./lib/FlashMCUFirmware.js" );
const FlashESCFirmware  = require( "./lib/FlashESCFirmware.js" );
const ResetMCU          = require( "./lib/ResetMCU.js" );

const escConfPath       = "/opt/openrov/system/config/esc.conf";
const mcuLastBuildPath  = "/opt/openrov/system/config/lastBuildHash";
const mcuBinPath        = "/opt/openrov/firmware/bin/2x/OpenROV2x.hex";
const logger            = require("AppFramework.js").logger.child({module:"stateMachine"});

module.exports = function( board )
{
    const Progress = Object.freeze( { "InProgress":1, "Complete":2, "Failed":3 } );

    function notify(message){
        board.global.emit("notification",message);
    }

    function status( message, progress )
    {
        board.global.emit( "plugin.updateManager.status", { message: message.toString(), progress: progress } );
        logger.debug( "FIRMWARE UPDATE: " + message.toString().trim() );
    }

    function log( data )
    {
        board.global.emit( "plugin.updateManager.log", data.toString() );
        logger.debug( "FIRMWARE UPDATE: " + data.toString().trim() );
    }

    function err( data )
    {
        board.global.emit( "plugin.updateManager.error", data.toString() );
        logger.error(data.toString());
    }

    function escCheckHandler(event, from, to)
    {
        var self = this;

        status( "Checking ESCs...", "Examining" );

        // Check to see if ESCs have been flashed before by testing the existence of esc.conf
        fs.statAsync( escConfPath )
        .then( function()
        {
            // Existence of file suggests ESCs have been flashed already
            log( "ESCs already up to date." );
            self._e_esc_flash_complete();
        })
        .catch( function(error)
        {
            // ESCs have never been flashed before. Do so now
            log( "ESCs haven't been flashed. Triggering flash." );
            self._e_trigger_esc_flash();
        });
    }

    function flashESCHandler(event, from, to)
    {
        var self = this;

        status( "Flashing ESCs...", "InProgress" );
        this.data.flashingAttemped = true;

        // First, disconnect the bridge
        self.board.bridge.close();

        // Execute the flash firmware script
        FlashESCFirmware( log, err )
        .then( function()
        {
            // Successm, write to a file to indicate this
            return fs.writeFileAsync( escConfPath, "flashed" );
        })
        .then( function()
        {
            // Re-enable the bridge
            self.board.bridge.connect();

            // Success
            log( "ESCs flashed successfully." );
            self._e_esc_flash_complete();
        })
        .catch( function( error )
        {
            // Re-enable the bridge
            self.board.bridge.connect();

            // Move to failed state
            err( "ESC flash failed." );
            self._e_fail( error );
        });
    }

    function checkBinHandler(event, from, to)
    {
        var self = this;

        status( "Checking if firmware already built...", "Examining" );

        // Check to see if ESCs have been flashed before by testing the existence of esc.conf
        fs.statAsync( mcuBinPath )
        .then( function()
        {
            // Existence of file suggests firmware has already been built
            log( "Binary already exists" );
            self._e_firmware_build_complete();
        })
        .catch( function(error)
        {
            // Firmware has never been built. Trigger a build
            log( "No binary found. Triggering build." );
            self._e_trigger_firmware_build();
        });
    }

    function buildFirmwareHandler(event, from, to)
    {
        status( "Building firmware...", "InProgress" );
        this.data.flashingAttemped = true;
        var self = this;

        // Execute the build firmware script
        BuildMCUFirmware( log, err )
        .then( function()
        {
            // Success
            log( "Build succeeded" );
            self._e_firmware_build_complete();
        })
        .catch( function( error )
        {
            // Move to failed state
            err( "Build failed" );
            self._e_fail( error );
        });
    }

    function getHashHandler(event, from, to)
    {
        status( "Fetching firmware hash...", "Examining" );

        var self = this;

        // TODO: make this read from a file from somewhere else. Hex doesn't work for clever parsing :(
        fs.readFileAsync( mcuLastBuildPath, 'utf8' )
        .then( function( hash )
        {
            log( "Hash in last build file: " + hash.trim() );

            self.board.hashInfo.fromBin = hash;
        })
        .then( function()
        {
            if( self.board.hashInfo.fromBin != "" )
            {
                // Success
                self._e_hash_obtained();
            }
            else
            {
                err( "Hash was empty!" );

                // Move to failed state
                self._e_fail( error );
            }
        })
        .catch( function( error )
        {
            err( "Failed to find hash file" );

            // Move to failed state
            self._e_fail( error );
        });
    }

    function flashMCUHandler(event, from, to)
    {
        status( "Flashing MCU firmware...", "InProgress" );
        this.data.flashingAttemped = true;
        var self = this;

        // Execute the build firmware script
        retry( function(){ return FlashMCUFirmware( log, err ); }, {interval: 10000})
        .then( function()
        {
            // Success
            log( "Flash succeeded" );
            self._e_mcu_flash_complete();
        })
        .catch( function( error )
        {
            // Move to failed state
            log( "Flash failed" );
            self._e_fail( error );
        });
    }

    function verifyVersionHandler(event, from, to)
    {
        status( "Checking current firmware against latest...", "Examining" );

        var self = this;

        // First, clear out the existing fromMCU hash info
        self.board.hashInfo.fromMCU = "";

        // Now register a timeout that attempts to fetch the updated hash
        var counter = 0;

        var RequestHashInfo = function()
        {
            // Make sure the serial port is open
            if (!self.board.bridge.isConnected())
            {
                logger.debug("Serial Port not connected.. opening and retrying in 300ms");
                self.board.bridge.connect();
                setTimeout(RequestHashInfo.bind(this),300);
                return;
            }
            // Send the version request command to the MCU
            self.board.bridge.write( "version();" );

            log( "MCU reported hash: " + self.board.hashInfo.fromMCU );
            log( "Hash from last build: " + self.board.hashInfo.fromBin );

            // Check for new hash info received from MCU
            if( self.board.hashInfo.fromMCU !== "" )
            {
                // Check it against the binary hash
                if( self.board.hashInfo.fromMCU == self.board.hashInfo.fromBin )
                {
                    // Success
                    log( "MCU Firmware is up to date" );
                    self._e_firmware_validated();
                }
                else
                {
                    // Version mismatch. Flash the latest firmware to the MCU
                    log( "MCU Firmware is out of date. Triggering flash." );
                    self._e_trigger_mcu_flash();
                }
            }
            else if( counter < 6 )
            {
                // Call 5 times, once per 3 secs
                counter++;
                log( "Verification attempt #" + counter );
                setTimeout( RequestHashInfo, 3000 );
            }
            else
            {
                // Never received hash info from MCU. Flash the latest firmware to the MCU
                log( "No firmware detected. Triggering flash." );
                self._e_trigger_mcu_flash();
            }
        };

        RequestHashInfo();
    }

    function resetMCUHandler(event, from, to)
    {
        status( "Resetting MCU...", "InProgress" );

        var self = this;

        ResetMCU()
        .then( function()
        {
            self._e_mcu_reset_complete();
        } )
        .catch( function( error )
        {
            // Move to failed state
            log( "Reset failed" );
            self._e_fail( error );
        });
    }

    function completeHandler(event, from, to)
    {
        status( "Firmware up to date!", "Complete" );
        if (this.data.flashingAttemped){
            notify( "Firmware update applied");
        }
        this.data.flashingAttemped = false;
    }

    function failHandler(event, from, to)
    {
        status( "Firmware update failed!", "Failed" );
        notify( "Firmware update failed");
        this.data.flashingAttemped = false;
    }

    function eFailHandler(event, from, to, msg)
    {
        if( msg == undefined )
        {
            msg = 'No message in failure: ' + event;
        }

        err( "StateMachine error: " + msg );
        this.data.error = JSON.stringify( msg );
    };

    var fsm = StateMachine.create(
    {
        events:
        [
            // Internal events - Should always be called as the final step of a promise chain
            { name: '_e_init',                          from: 'none',                               to: 'checking_escs' },
            { name: '_e_trigger_esc_flash',             from: 'checking_escs',                      to: 'flashing_escs' },
            { name: '_e_esc_flash_complete',            from: ['checking_escs','flashing_escs'] ,   to: 'checking_bin'},
            { name: '_e_trigger_firmware_build',        from: ['checking_bin','complete'],          to: 'building_firmware' },
            { name: '_e_firmware_build_complete',       from: ['checking_bin','building_firmware'], to: 'get_hash' },
            { name: '_e_hash_obtained',                 from: 'get_hash',                           to: 'verify_version' },
            { name: '_e_trigger_mcu_flash',             from: 'verify_version',                     to: 'flashing_mcu' },
            { name: '_e_mcu_flash_complete',            from: 'flashing_mcu',                       to: 'verify_version' },
            { name: '_e_firmware_validated',            from: 'verify_version',                     to: 'complete' },
            { name: '_e_mcu_reset_complete',            from: 'resetting_mcu',                      to: 'complete' },

            // User events (can only be used from the complete state)
            { name: '_e_trigger_esc_flash_user',        from: 'complete',                           to: 'flashing_escs' },
            { name: '_e_trigger_firmware_build_user',   from: 'complete',                           to: 'building_firmware' },
            { name: '_e_trigger_mcu_flash_user',        from: 'complete',                           to: 'flashing_mcu' },
            { name: '_e_trigger_mcu_reset_user',        from: 'complete',                           to: 'resetting_mcu' },
            { name: '_e_reset',                         from: ['complete', 'failed'],               to: 'checking_escs' },

            { name: '_e_fail',                          from: '*',                                  to: 'failed' }
        ],

        callbacks:
        {
            // State handlers - We allow states to handle their own transitions to ensure consistency
            onchecking_escs: escCheckHandler,
            onflashing_escs: flashESCHandler,
            onchecking_bin: checkBinHandler,
            onbuilding_firmware: buildFirmwareHandler,
            onflashing_mcu: flashMCUHandler,
            onget_hash: getHashHandler,
            onverify_version: verifyVersionHandler,
            onresetting_mcu: resetMCUHandler,
            oncomplete: completeHandler,
            onfailed: failHandler,

            // Event handlers
            onbefore_e_fail: eFailHandler
        },

        error: function(eventName, from, to, args, errorCode, errorMessage)
        {
            // The error handler for the statemachine is backed with the above parameters, but since
            // some flows just raise an exception, need to move things around in that case.
            if (eventName instanceof Error)
            {
                e = eventName;
                eventName = "unspecified";
            }

            errorReport =
            {
                eventName: eventName,
                from: from,
                to: to,
                args: args,
                errorCode: errorCode,
                errorMessage: errorMessage,
            }

            err( 'MCU State Machine: Error in event <' + eventName + '>: ' + JSON.stringify(errorReport));
        }
    });

    // Other state information
    fsm.data = {};
    fsm.board = board;

    return fsm;
};
<|endoftext|>


<commit_before>//Main class that represents one simulation, including the tabs, home screen, play area, etc.
//Provides default initialization, such as polyfills as well.
define( function( require ) {
  'use strict';

  var Fort = require( 'FORT/Fort' );
  var Util = require( 'SCENERY/util/Util' );
  var NavigationBar = require( 'SCENERY_PHET/NavigationBar' );
  var HomeScreen = require( 'SCENERY_PHET/HomeScreen' );
  var Scene = require( 'SCENERY/Scene' );
  var Node = require( 'SCENERY/nodes/Node' );
  var LayoutConstants = require( 'SCENERY_PHET/LayoutConstants' );

  //Default size to use, which will be scaled up and down isometrically
  var HEIGHT = LayoutConstants.HEIGHT;
  var WIDTH = LayoutConstants.WIDTH;

  function Sim( name, tabs ) {
    var sim = this;
    this.tabs = tabs;

    Util.polyfillRequestAnimationFrame();

    this.appModel = new Fort.Model( {home: false, tab: 0} );

    this.scene = new Scene( $( '.scene' ), {width: WIDTH, height: HEIGHT, allowDevicePixelRatioScaling: true} );
    this.scene.initializeStandaloneEvents(); // sets up listeners on the document with preventDefault(), and forwards those events to our scene
    this.scene.resizeOnWindowResize(); // the scene gets resized to the full screen size

    var homeScreen = new HomeScreen( name, tabs, this.appModel );
    var navigationBar = new NavigationBar( tabs, this.appModel ).mutate( {bottom: HEIGHT - 2} );//TODO: this padding amount is copied in NavigationBar

    var root = new Node(); //root: homeScreen | tabNode
    var tabNode = new Node(); //tabNode: navigationBar tabContainer
    var tabContainer = new Node();//tabContainer: sceneForTab
    tabNode.addChild( navigationBar );
    tabNode.addChild( tabContainer );
    this.scene.addChild( root );

    this.appModel.link( 'home', function( home ) { root.children = [home ? homeScreen : tabNode];} );

    function resize() {

      //TODO: This will have to change when sims are embedded on a page instead of taking up an entire page
      var width = $( window ).width();
      var height = $( window ).height();

      var scale = Math.min( width / WIDTH, height / HEIGHT );
      sim.scene.resetTransform();
      sim.scene.setScaleMagnitude( scale );

      //center vertically
      if ( scale === width / WIDTH ) {
        sim.scene.translate( 0, (height - HEIGHT * scale) / 2 / scale );
      }

      //center horizontally
      else if ( scale === height / HEIGHT ) {
        sim.scene.translate( (width - WIDTH * scale) / 2 / scale, 0 );
      }

      //Redraw if necessary, in case the animation loop hasn't started yet
      sim.scene.updateScene();
    }

    //Fit to the window and render the initial scene
    $( window ).resize( resize );
    resize();

    //Instantiate the tabs
    for ( var i = 0; i < tabs.length; i++ ) {
      tabs[i].instance = tabs[i].create();
    }

    this.appModel.link( 'tab', function( tabIndex ) { tabContainer.children = [tabs[tabIndex].instance]; } );
    this.scene.updateScene();
  }

  Sim.prototype.start = function() {
    var sim = this;

    // place the rAF *before* the render() to assure as close to 60fps with the setTimeout fallback.
    //http://paulirish.com/2011/requestanimationframe-for-smart-animating/
    (function animationLoop() {
      requestAnimationFrame( animationLoop );

      //Update the tab, but not if the user is on the home screen
      if ( !sim.appModel.home ) {
        sim.tabs[sim.appModel.tab].instance.model.step();
      }
      sim.scene.updateScene();
    })();
  };

  return Sim;
} );<commit_msg>added docs to Sim<commit_after>//Main class that represents one simulation, including the tabs, home screen, play area, etc.
//Provides default initialization, such as polyfills as well.
define( function( require ) {
  'use strict';

  var Fort = require( 'FORT/Fort' );
  var Util = require( 'SCENERY/util/Util' );
  var NavigationBar = require( 'SCENERY_PHET/NavigationBar' );
  var HomeScreen = require( 'SCENERY_PHET/HomeScreen' );
  var Scene = require( 'SCENERY/Scene' );
  var Node = require( 'SCENERY/nodes/Node' );
  var LayoutConstants = require( 'SCENERY_PHET/LayoutConstants' );

  //Default size to use, which will be scaled up and down isometrically
  var HEIGHT = LayoutConstants.HEIGHT;
  var WIDTH = LayoutConstants.WIDTH;

  function Sim( name, tabs ) {
    var sim = this;
    this.tabs = tabs;

    Util.polyfillRequestAnimationFrame();

    //This model represents where the simulation is, whether it is on the home screen or a tab, and which tab it is on or is highlighted in the home screen
    this.appModel = new Fort.Model( {home: false, tab: 0} );

    this.scene = new Scene( $( '.scene' ), {width: WIDTH, height: HEIGHT, allowDevicePixelRatioScaling: true} );
    this.scene.initializeStandaloneEvents(); // sets up listeners on the document with preventDefault(), and forwards those events to our scene
    this.scene.resizeOnWindowResize(); // the scene gets resized to the full screen size

    var homeScreen = new HomeScreen( name, tabs, this.appModel );
    var navigationBar = new NavigationBar( tabs, this.appModel ).mutate( {bottom: HEIGHT - 2} );//TODO: this padding amount is copied in NavigationBar

    //The root contains the home screen or the tabNode
    var root = new Node(); //root: homeScreen | tabNode

    //The tab container contains the tab itself, which will be swapped out based on which tab icon the user selected
    var tabContainer = new Node();//tabContainer: sceneForTab

    //The tabNode contains the tabContainer and the navigation bar
    var tabNode = new Node( {children: [navigationBar, tabContainer]} );
    this.scene.addChild( root );

    //When the user presses the home icon, then show the home screen, otherwise show the tabNode
    this.appModel.link( 'home', function( home ) { root.children = [home ? homeScreen : tabNode];} );

    function resize() {

      //TODO: This will have to change when sims are embedded on a page instead of taking up an entire page
      var width = $( window ).width();
      var height = $( window ).height();

      var scale = Math.min( width / WIDTH, height / HEIGHT );
      sim.scene.resetTransform();
      sim.scene.setScaleMagnitude( scale );

      //center vertically
      if ( scale === width / WIDTH ) {
        sim.scene.translate( 0, (height - HEIGHT * scale) / 2 / scale );
      }

      //center horizontally
      else if ( scale === height / HEIGHT ) {
        sim.scene.translate( (width - WIDTH * scale) / 2 / scale, 0 );
      }

      //Redraw if necessary, in case the animation loop hasn't started yet
      sim.scene.updateScene();
    }

    //Instantiate the tabs
    for ( var i = 0; i < tabs.length; i++ ) {
      tabs[i].instance = tabs[i].create();
    }

    //When the user presses a different tab, show it on the screen
    this.appModel.link( 'tab', function( tabIndex ) { tabContainer.children = [tabs[tabIndex].instance]; } );

    //Fit to the window and render the initial scene
    $( window ).resize( resize );
    resize();
  }

  Sim.prototype.start = function() {
    var sim = this;

    // place the rAF *before* the render() to assure as close to 60fps with the setTimeout fallback.
    //http://paulirish.com/2011/requestanimationframe-for-smart-animating/
    (function animationLoop() {
      requestAnimationFrame( animationLoop );

      //Update the tab, but not if the user is on the home screen
      if ( !sim.appModel.home ) {
        sim.tabs[sim.appModel.tab].instance.model.step();
      }
      sim.scene.updateScene();
    })();
  };

  return Sim;
} );<|endoftext|>


<commit_before>const path = require('path')

const {
  removeExt,
  normalizePath,
  getPagesJson
} = require('@dcloudio/uni-cli-shared')

const {
  normalizeNodeModules
} = require('@dcloudio/webpack-uni-mp-loader/lib/shared')

const SCROLLER_COMPONENTS = [
  'list',
  'scroller',
  'scroll-view',
  'waterfall'
]

module.exports = function(content) {
  this.cacheable && this.cacheable()
  const source = content.trim()

  if (SCROLLER_COMPONENTS.find(name => source.indexOf('<' + name) === 0)) {
    return content
  }
  if (source.indexOf('<recycle-list') !== -1) {
    return content
  }

  let resourcePath = normalizeNodeModules(
    removeExt(normalizePath(path.relative(process.env.UNI_INPUT_DIR, this.resourcePath)))
  )

  if (
    !process.UNI_NVUE_ENTRY[resourcePath] &&
    this._module.issuer &&
    this._module.issuer.issuer
  ) {
    // <template src=""/>
    resourcePath = normalizeNodeModules(
      removeExt(normalizePath(path.relative(process.env.UNI_INPUT_DIR, this._module.issuer.issuer.resource)))
    )
  }

  if (!process.UNI_NVUE_ENTRY[resourcePath]) {
    return content
  }
  // 暂时实时读取配置信息,查找是否 disableScroll
  const appJson = getPagesJson()
  if (!appJson.nvue || !appJson.nvue.pages) {
    return content
  }
  const pagePath = resourcePath + '.html'
  const pageJson = appJson.nvue.pages.find(page => page.path === pagePath)
  if (!pageJson) {
    return content
  }

  if (!appJson.globalStyle) {
    appJson.globalStyle = {}
  }

  Object.assign(appJson.globalStyle, appJson.globalStyle['app-plus'] || {})
  Object.assign(pageJson.style, pageJson.style['app-plus'] || {})
  const pageJsonStyle = Object.assign(appJson.globalStyle, pageJson.style)
  if (pageJsonStyle.disableScroll === true) {
    return content
  }

  return `<scroll-view :scroll-y="true" :enableBackToTop="true" bubble="true" style="flex-direction:column">${content}</scroll-view>`
}
<commit_msg>fix(v3): compatible with native<commit_after>const path = require('path')

const {
  removeExt,
  normalizePath,
  getPagesJson
} = require('@dcloudio/uni-cli-shared')

const {
  normalizeNodeModules
} = require('@dcloudio/webpack-uni-mp-loader/lib/shared')

const SCROLLER_COMPONENTS = [
  'list',
  'scroller',
  'scroll-view',
  'waterfall'
]

module.exports = function(content) {
  this.cacheable && this.cacheable()
  const source = content.trim()

  if (SCROLLER_COMPONENTS.find(name => source.indexOf('<' + name) === 0)) {
    return content
  }
  if (source.indexOf('<recycle-list') !== -1) {
    return content
  }

  let resourcePath = normalizeNodeModules(
    removeExt(normalizePath(path.relative(process.env.UNI_INPUT_DIR, this.resourcePath)))
  )

  if (
    !process.UNI_NVUE_ENTRY[resourcePath] &&
    this._module.issuer &&
    this._module.issuer.issuer
  ) {
    // <template src=""/>
    resourcePath = normalizeNodeModules(
      removeExt(normalizePath(path.relative(process.env.UNI_INPUT_DIR, this._module.issuer.issuer.resource)))
    )
  }

  if (!process.UNI_NVUE_ENTRY[resourcePath]) {
    return content
  }
  // 暂时实时读取配置信息,查找是否 disableScroll
  const appJson = getPagesJson()

  let pageJson
  if (appJson.nvue) { //旧版本
    if (!appJson.nvue || !appJson.nvue.pages) {
      return content
    }
    const pagePath = resourcePath + '.html'
    pageJson = appJson.nvue.pages.find(page => page.path === pagePath)
  } else {
    pageJson = appJson.pages.find(page => page.path === resourcePath)
  }

  if (!pageJson) {
    return content
  }

  if (!appJson.globalStyle) {
    appJson.globalStyle = {}
  }

  Object.assign(appJson.globalStyle, appJson.globalStyle['app-plus'] || {})
  Object.assign(pageJson.style, pageJson.style['app-plus'] || {})
  const pageJsonStyle = Object.assign(appJson.globalStyle, pageJson.style)
  if (pageJsonStyle.disableScroll === true) {
    return content
  }

  return `<scroll-view :scroll-y="true" :enableBackToTop="true" bubble="true" style="flex-direction:column">${content}</scroll-view>`
}
<|endoftext|>


<commit_before>ESC.jukebox = new ESC.controllers.Jukebox();
ESC.jukebox.newPlayItem();
document.getElementById('play_button').onclick = function(){ESC.jukebox.play();};
document.getElementById('new_button').onclick = function(){ESC.jukebox.newPlayItem();};

document.getElementById('button_replace_notes').onclick = function(){ESC.jukebox.melodyWithNew('notes')};
document.getElementById('button_replace_rhythm').onclick = function(){ESC.jukebox.melodyWithNew('rhythm')};

document.getElementById('button_transform_original').onclick = function(){
																			ESC.jukebox.transformMelody('original');
																			$('.transformations li').removeClass('selected');
																			$(this).addClass('selected');
																		};

document.getElementById('button_transform_retrograde').onclick = function(){
																			ESC.jukebox.transformMelody('retrograde');
																			$('.transformations li').removeClass('selected');
																			$(this).addClass('selected');
																			};
$('#tempo_input, #tempo_slider').on('change', function(event) {
	ESC.jukebox.setTempo(this.value);
});<commit_msg>add listener to playlist items list<commit_after>ESC.jukebox = new ESC.controllers.Jukebox();
ESC.jukebox.newPlayItem();
document.getElementById('play_button').onclick = function(){ESC.jukebox.play();};
document.getElementById('new_button').onclick = function(){ESC.jukebox.newPlayItem();};

document.getElementById('button_replace_notes').onclick = function(){ESC.jukebox.melodyWithNew('notes')};
document.getElementById('button_replace_rhythm').onclick = function(){ESC.jukebox.melodyWithNew('rhythm')};

document.getElementById('button_transform_original').onclick = function(){
																			ESC.jukebox.transformMelody('original');
																			$('.transformations li').removeClass('selected');
																			$(this).addClass('selected');
																		};

document.getElementById('button_transform_retrograde').onclick = function(){
																			ESC.jukebox.transformMelody('retrograde');
																			$('.transformations li').removeClass('selected');
																			$(this).addClass('selected');
																			};
$('#tempo_input, #tempo_slider').on('change', function(event) {
	ESC.jukebox.setTempo(this.value);
});

$('#play_items_list').on('click', 'li', function(){
	var index = $('#play_items_list li').index($(this));
	ESC.jukebox.setCurrentPlayItem(index);
});

<|endoftext|>