<commit_before>var runtimes = new function()
{
  var __runtimes = {};

  var self = this;

  var registerRuntime = function(id)
  {
    if( !(id in __runtimes) )
    {
      //alert('runtime: '+ id);
      __runtimes[id] = null;
      services['ecmascript-debugger'].getRuntime( tagManager.setCB(null, parseRuntime), id );
    }
  }

  var removeRuntime = function(id)
  {
    var sc = null ;
    /*
    for( sc in __scripts )
    {
      if( __scripts[sc]['runtime-id'] == id )
      {
        delete __scripts[sc];
      }
    }
    */
    delete __runtimes[id];
  }

  this.handleRuntimesReplay = function(xml)
  {
    parseRuntime(xml);
  }

  var parseRuntime = function(xml)
  {
    var r_ts = xml.getElementsByTagName('runtime'), r_t=null, i=0;
    var runtimeId = '', runtime=null, prop = '',
      children = null, child = null, j = 0;
    var cur = '';
    for ( ; r_t = r_ts[i]; i++)
    {
      runtimeId = r_t.getNodeData('runtime-id');
      //alert('parseRuntime: '+ runtimeId);
      if(runtimeId)
      {
        runtime={};
        children = r_t.childNodes;
        for(j=0 ; child = children[j]; j++)
        {
          runtime[child.nodeName] = child.textContent;
        }
        for( cur in __runtimes )
        {
          if( __runtimes[cur] && __runtimes[cur]['uri'] == runtime['uri'] )
          {
            // copy states
            //alert("__runtimes[cur]['unfolded'] "+__runtimes[cur]['unfolded'])
            if( __runtimes[cur]['unfolded'] )
            {
              runtime['unfolded'] = __runtimes[cur]['unfolded'];
            }
            delete __runtimes[cur];
          }
        }
        __runtimes[runtimeId] = runtime;

        if(__next_runtime_id_to_select == runtimeId)
        {
          self.setSelectedRuntime(runtime);
          __next_runtime_id_to_select = '';
        }

        // update view
        views.runtimes.update();
      }
    }
  }

  var __scripts = {};

/** checks if that script is already known from a previous runtime
  * checks first for the url and the for the script data.
  * Both checks are not really reliable.
  * TODO we need a better logic to handle this
  */
  var registerScript = function(script)
  {
    var sc = null, is_known = false;
    var new_script_id = script['script-id'];
    for( sc in __scripts )
    {
      if( ( __scripts[sc]['uri'] && ( __scripts[sc]['uri'] == script['uri'] ) )|| __scripts[sc]['script-data'] == script['script-data'] )
      {
        is_known = true;
        break;
      }
    }

    if( is_known )
    {
      var old_b_ps = __scripts[sc]['breakpoints'];
      var new_b_ps = script['breakpoints'];
      for( b_p in old_b_ps )
      {
        services['ecmascript-debugger'].setBreakpoint(new_script_id, b_p, old_b_ps[b_p]);
        new_b_ps[b_p] = old_b_ps[b_p];
      }
      delete __scripts[sc];
    }

    __scripts[new_script_id] = script;

    var a ='', b='';
    for( a in __scripts ) b+=a+'; ';

  }

/*
"<new-script>"
   "<runtime-id>" UNSIGNED "</runtime-id>"
   "<script-id>" UNSIGNED "</script-id>"
   "<script-type>"
      ( "inline" | "event" | "linked" | "timeout" | "java" | "unknown" )
   "</script-type>"
   "<script-data>" TEXT "</script-data>"
   "<uri>" TEXT "</uri>"             ; present if SCRIPT-TYPE is "linked"
 "</new-script>" ;
*/

  var breakpoint_count = 1;

  var getBreakpointId = function()
  {
    return ( breakpoint_count++ ).toString();
  }

  var script_count = 1;

  var getScriptId = function()
  {
    return ( script_count++ ).toString();
  }

  this.handle = function(new_script_event)
  {
    var script = {};
    var children = new_script_event.documentElement.childNodes, child=null, i=0;
    for ( ; child = children[i]; i++)
    {
      script[child.nodeName] = child.firstChild.nodeValue;
    }
    script['breakpoints'] = {};
    registerRuntime( script['runtime-id'] );
    registerScript( script );
    views.runtimes.update();
  }

  var thread_queue = []
  var threads = {}
  var current_thread = [];

  var clear_thread_id = function(id)
  {
    var cur = '', i = 0;
    /* it seems that the order of the thread-finished events can get reversed
    if( id == current_thread[ current_thread.length - 1 ] )
    {
      current_thread.pop();
    }
    */
    for(i = 0 ; cur = current_thread[i]; i++)
    {
      if( cur == id )
      {
        current_thread.splice(i, 1);
        break;
      }
    }
    for(i = 0 ; cur = thread_queue[i]; i++)
    {
      if( cur == id )
      {
        thread_queue.splice(i, 1);
        delete threads[id];
        return true;
      }
    }
    return false;
  }

/*

  <thread-started>
    <runtime-id>3</runtime-id>
    <thread-id>3</thread-id>
    <parent-thread-id>0</parent-thread-id>
    <thread-type>inline</thread-type>
  </thread-started>

  <thread-finished>
    <runtime-id>3</runtime-id>
    <thread-id>3</thread-id>
    <status>completed</status>
    <value type="null"/>
  </thread-finished>

  */

  this.handleThreadStarted = function(xml)
  {
    var id = xml.getNodeData("thread-id");
    var parent_thread_id = xml.getNodeData("parent-thread-id");
    thread_queue[thread_queue.length] = id;
    if( !current_thread.length ||
      ( parent_thread_id != '0' && parent_thread_id == current_thread[ current_thread.length - 1 ] ) )
    {
      current_thread[current_thread.length] = id;
    }
  }

  this.handleThreadStopedAt = function(xml)
  {
    var id = xml.getNodeData("thread-id");
    // the current thread id should either be set in 'thread-started' event or
    // in shifting one from the thread event queue

    if( id == current_thread[ current_thread.length - 1 ] )
    {
      stop_at.handle(xml);
    }
    else
    {
      // there should never be more then one 'thread-stopped-at' event per runtime
      // is this really true ?
      threads[id] = xml;
    }
  }

  this.handleThreadFinished = function(xml)
{
    /* TODO
    status "completed" | "unhandled-exception" | "aborted" | "cancelled-by-scheduler"
    */
    var id = xml.getNodeData("thread-id") , i = 0, parent_thread_id = '', thread = null;
    clear_thread_id(id);
    // opera.postError("thread finished id: " + id +' queue: '+thread_queue+' current: '+current_thread)
    for( ; id = thread_queue[i]; i++)
    {
      if( thread = threads[id] )
      {
        parent_thread_id = thread.getNodeData("parent-thread-id");
        if( !current_thread.length ||
            ( parent_thread_id != '0' && parent_thread_id == current_thread[ current_thread.length - 1 ] ) )
        {
          current_thread[current_thread.length] = id;
          stop_at.handle(threads[id]);
          break;
        }
      }
    }
  }

  /*
  <runtime-stopped>
  <runtime-id>1</runtime-id>
</runtime-stopped>

*/
  this.handleRuntimeStoped = function(xml)
  {

    var rt_id = xml.getNodeData('runtime-id');
    if(rt_id)
    {
      removeRuntime(rt_id);
      views.runtimes.update();
      var script_id = views.js_source.getCurrentScriptId();
      if( script_id  && ( self.getScriptsRuntimeId(script_id) == rt_id ) )
      {
        views.js_source.clearView();
      }
    }

  }

  this.getRuntimes = function()
  {
    // not very clever
    return __runtimes;
  }

  this.getRuntimeIdWithURL = function(url)
  {
    var r = '';
    for( r in __runtimes )
    {
      if( __runtimes[r]['uri'] == url )
      {
        return __runtimes[r];
      }
    }
    return null;
  }

  this.getScript = function(scriptId)
  {
    return __scripts[scriptId];
  }

  this.getScriptsRuntimeId = function(scriptId)
  {
    return __scripts[scriptId] && __scripts[scriptId]['runtime-id'] || null;
  }

  this.getScriptSource = function(scriptId)
  {
    return __scripts[scriptId] && __scripts[scriptId]['script-data'] || null;
  }

  this.getScripts = function(runtime_id)
  {
    var ret=[], script = null, cur = '';
    for( cur in __scripts )
    {
      script = __scripts[cur];
      if(script['runtime-id'] == runtime_id)
      {
        ret[ret.length] = script;
      }
    }
    return ret;
  }

  this.hasBreakpoint = function(script_id, line_nr)
  {
    return (line_nr in __scripts[script_id]['breakpoints']);
  }

  this.setBreakpoint = function(script_id, line_nr)
  {
    var b_p_id = __scripts[script_id]['breakpoints'][line_nr] = getBreakpointId();
    services['ecmascript-debugger'].setBreakpoint(script_id, line_nr, b_p_id);
  }

  this.removeBreakpoint = function(script_id, line_nr)
  {
    services['ecmascript-debugger'].removeBreakpoint( __scripts[script_id]['breakpoints'][line_nr] );
    delete __scripts[script_id]['breakpoints'][line_nr];
  }

  this.getBreakpoints = function(script_id)
  {
    return __scripts[script_id] && __scripts[script_id]['breakpoints'];
  }

  this.setUnfolded = function(runtime_id, is_unfolded)
  {

    if( __runtimes[runtime_id] )
    {
      //alert(__runtimes[runtime_id]+' '+is_unfolded);
      __runtimes[runtime_id]['unfolded'] = is_unfolded;
    }
  }

  this.setObserve = function(runtime_id, observe)
  {
    if( __runtimes[runtime_id] )
    {
      __runtimes[runtime_id]['observe'] = observe;
    }
  }

  this.getObserve = function(runtime_id)
  {
    return __runtimes[runtime_id] && __runtimes[runtime_id]['observe']  || false;
  }

  // this is a temporary solution as long as we don't have a concept for tabs

  var __selected_runtime_id = '';

  var __next_runtime_id_to_select = ''

  this.setSelectedRuntime = function(runtime)
  {
    var r = '';
    for( r in __runtimes )
    {
      if( __runtimes[r] == runtime )
      {
        __runtimes[r]['selected'] = true;
        __selected_runtime_id = __runtimes[r]['runtime-id'];
      }
      else
      {
        // the runtime could be registered but not jet parsed
        if( __runtimes[r] )
        {
          __runtimes[r]['selected'] = false;
        }
      }
    }
  }

  this.setSelectedScript = function( runtime, id )
  {
    var scripts = this.getScripts(runtime['runtime-id']), script = null, i = 0;
    for( ; script = scripts[i]; i++)
    {
      script.selected = script['script-id'] == id ? true : false;
    }
  }

  this.setSelectedRuntimeId = function(id)
  {
    if(__runtimes[id])
    {
      this.setSelectedRuntime(__runtimes[id]);
      views.runtimes.update();
    }
    else
    {
      __next_runtime_id_to_select = id;
    }
  }

  this.getSelectedRuntimeId = function()
  {
    return __selected_runtime_id;
  }

}

//<commit_msg>cleaner code in thread-finished event<commit_after>var runtimes = new function()
{
  var __runtimes = {};

  var self = this;

  var registerRuntime = function(id)
  {
    if( !(id in __runtimes) )
    {
      //alert('runtime: '+ id);
      __runtimes[id] = null;
      services['ecmascript-debugger'].getRuntime( tagManager.setCB(null, parseRuntime), id );
    }
  }

  var removeRuntime = function(id)
  {
    var sc = null ;
    /*
    for( sc in __scripts )
    {
      if( __scripts[sc]['runtime-id'] == id )
      {
        delete __scripts[sc];
      }
    }
    */
    delete __runtimes[id];
  }

  this.handleRuntimesReplay = function(xml)
  {
    parseRuntime(xml);
  }

  var parseRuntime = function(xml)
  {
    var r_ts = xml.getElementsByTagName('runtime'), r_t=null, i=0;
    var runtimeId = '', runtime=null, prop = '',
      children = null, child = null, j = 0;
    var cur = '';
    for ( ; r_t = r_ts[i]; i++)
    {
      runtimeId = r_t.getNodeData('runtime-id');
      //alert('parseRuntime: '+ runtimeId);
      if(runtimeId)
      {
        runtime={};
        children = r_t.childNodes;
        for(j=0 ; child = children[j]; j++)
        {
          runtime[child.nodeName] = child.textContent;
        }
        for( cur in __runtimes )
        {
          if( __runtimes[cur] && __runtimes[cur]['uri'] == runtime['uri'] )
          {
            // copy states
            //alert("__runtimes[cur]['unfolded'] "+__runtimes[cur]['unfolded'])
            if( __runtimes[cur]['unfolded'] )
            {
              runtime['unfolded'] = __runtimes[cur]['unfolded'];
            }
            delete __runtimes[cur];
          }
        }
        __runtimes[runtimeId] = runtime;

        if(__next_runtime_id_to_select == runtimeId)
        {
          self.setSelectedRuntime(runtime);
          __next_runtime_id_to_select = '';
        }

        // update view
        views.runtimes.update();
      }
    }
  }

  var __scripts = {};

/** checks if that script is already known from a previous runtime
  * checks first for the url and the for the script data.
  * Both checks are not really reliable.
  * TODO we need a better logic to handle this
  */
  var registerScript = function(script)
  {
    var sc = null, is_known = false;
    var new_script_id = script['script-id'];
    for( sc in __scripts )
    {
      if( ( __scripts[sc]['uri'] && ( __scripts[sc]['uri'] == script['uri'] ) )|| __scripts[sc]['script-data'] == script['script-data'] )
      {
        is_known = true;
        break;
      }
    }

    if( is_known )
    {
      var old_b_ps = __scripts[sc]['breakpoints'];
      var new_b_ps = script['breakpoints'];
      for( b_p in old_b_ps )
      {
        services['ecmascript-debugger'].setBreakpoint(new_script_id, b_p, old_b_ps[b_p]);
        new_b_ps[b_p] = old_b_ps[b_p];
      }
      delete __scripts[sc];
    }

    __scripts[new_script_id] = script;

    var a ='', b='';
    for( a in __scripts ) b+=a+'; ';

  }

/*
"<new-script>"
   "<runtime-id>" UNSIGNED "</runtime-id>"
   "<script-id>" UNSIGNED "</script-id>"
   "<script-type>"
      ( "inline" | "event" | "linked" | "timeout" | "java" | "unknown" )
   "</script-type>"
   "<script-data>" TEXT "</script-data>"
   "<uri>" TEXT "</uri>"             ; present if SCRIPT-TYPE is "linked"
 "</new-script>" ;
*/

  var breakpoint_count = 1;

  var getBreakpointId = function()
  {
    return ( breakpoint_count++ ).toString();
  }

  var script_count = 1;

  var getScriptId = function()
  {
    return ( script_count++ ).toString();
  }

  this.handle = function(new_script_event)
  {
    var script = {};
    var children = new_script_event.documentElement.childNodes, child=null, i=0;
    for ( ; child = children[i]; i++)
    {
      script[child.nodeName] = child.firstChild.nodeValue;
    }
    script['breakpoints'] = {};
    registerRuntime( script['runtime-id'] );
    registerScript( script );
    views.runtimes.update();
  }

  var thread_queue = []
  var threads = {}
  var current_thread = [];

  var clear_thread_id = function(id)
  {
    var cur = '', i = 0;
    /* it seems that the order of the thread-finished events can get reversed
    if( id == current_thread[ current_thread.length - 1 ] )
    {
      current_thread.pop();
    }
    */
    for(i = 0 ; cur = current_thread[i]; i++)
    {
      if( cur == id )
      {
        current_thread.splice(i, 1);
        break;
      }
    }
    for(i = 0 ; cur = thread_queue[i]; i++)
    {
      if( cur == id )
      {
        thread_queue.splice(i, 1);
        delete threads[id];
        return true;
      }
    }
    return false;
  }

/*

  <thread-started>
    <runtime-id>3</runtime-id>
    <thread-id>3</thread-id>
    <parent-thread-id>0</parent-thread-id>
    <thread-type>inline</thread-type>
  </thread-started>

  <thread-finished>
    <runtime-id>3</runtime-id>
    <thread-id>3</thread-id>
    <status>completed</status>
    <value type="null"/>
  </thread-finished>

  */

  this.handleThreadStarted = function(xml)
  {
    var id = xml.getNodeData("thread-id");
    var parent_thread_id = xml.getNodeData("parent-thread-id");
    thread_queue[thread_queue.length] = id;
    if( !current_thread.length ||
      ( parent_thread_id != '0' && parent_thread_id == current_thread[ current_thread.length - 1 ] ) )
    {
      current_thread[current_thread.length] = id;
    }
  }

  this.handleThreadStopedAt = function(xml)
  {
    var id = xml.getNodeData("thread-id");
    // the current thread id should either be set in 'thread-started' event or
    // in shifting one from the thread event queue

    if( id == current_thread[ current_thread.length - 1 ] )
    {
      stop_at.handle(xml);
    }
    else
    {
      // there should never be more then one 'thread-stopped-at' event per runtime
      // is this really true ?
      threads[id] = xml;
    }
  }

  this.handleThreadFinished = function(xml)
  {
      /* TODO
      status "completed" | "unhandled-exception" | "aborted" | "cancelled-by-scheduler"
      */
      var id = xml.getNodeData("thread-id") , i = 0, parent_thread_id = '', thread = null;
      clear_thread_id(id);
      // opera.postError("thread finished id: " + id +' queue: '+thread_queue+' current: '+current_thread)
      for( ; id = thread_queue[i]; i++)
      {
        if( thread = threads[id] )
        {
          parent_thread_id = thread.getNodeData("parent-thread-id");
          if( !current_thread.length ||
              ( parent_thread_id != '0' && parent_thread_id == current_thread[ current_thread.length - 1 ] ) )
          {
            current_thread[current_thread.length] = id;
            stop_at.handle(threads[id]);
            break;
          }
        }
      }
    }

  /*
  <runtime-stopped>
  <runtime-id>1</runtime-id>
</runtime-stopped>

*/
  this.handleRuntimeStoped = function(xml)
  {

    var rt_id = xml.getNodeData('runtime-id');
    if(rt_id)
    {
      removeRuntime(rt_id);
      views.runtimes.update();
      var script_id = views.js_source.getCurrentScriptId();
      if( script_id  && ( self.getScriptsRuntimeId(script_id) == rt_id ) )
      {
        views.js_source.clearView();
      }
    }

  }

  this.getRuntimes = function()
  {
    // not very clever
    return __runtimes;
  }

  this.getRuntimeIdWithURL = function(url)
  {
    var r = '';
    for( r in __runtimes )
    {
      if( __runtimes[r]['uri'] == url )
      {
        return __runtimes[r];
      }
    }
    return null;
  }

  this.getScript = function(scriptId)
  {
    return __scripts[scriptId];
  }

  this.getScriptsRuntimeId = function(scriptId)
  {
    return __scripts[scriptId] && __scripts[scriptId]['runtime-id'] || null;
  }

  this.getScriptSource = function(scriptId)
  {
    return __scripts[scriptId] && __scripts[scriptId]['script-data'] || null;
  }

  this.getScripts = function(runtime_id)
  {
    var ret=[], script = null, cur = '';
    for( cur in __scripts )
    {
      script = __scripts[cur];
      if(script['runtime-id'] == runtime_id)
      {
        ret[ret.length] = script;
      }
    }
    return ret;
  }

  this.hasBreakpoint = function(script_id, line_nr)
  {
    return (line_nr in __scripts[script_id]['breakpoints']);
  }

  this.setBreakpoint = function(script_id, line_nr)
  {
    var b_p_id = __scripts[script_id]['breakpoints'][line_nr] = getBreakpointId();
    services['ecmascript-debugger'].setBreakpoint(script_id, line_nr, b_p_id);
  }

  this.removeBreakpoint = function(script_id, line_nr)
  {
    services['ecmascript-debugger'].removeBreakpoint( __scripts[script_id]['breakpoints'][line_nr] );
    delete __scripts[script_id]['breakpoints'][line_nr];
  }

  this.getBreakpoints = function(script_id)
  {
    return __scripts[script_id] && __scripts[script_id]['breakpoints'];
  }

  this.setUnfolded = function(runtime_id, is_unfolded)
  {

    if( __runtimes[runtime_id] )
    {
      //alert(__runtimes[runtime_id]+' '+is_unfolded);
      __runtimes[runtime_id]['unfolded'] = is_unfolded;
    }
  }

  this.setObserve = function(runtime_id, observe)
  {
    if( __runtimes[runtime_id] )
    {
      __runtimes[runtime_id]['observe'] = observe;
    }
  }

  this.getObserve = function(runtime_id)
  {
    return __runtimes[runtime_id] && __runtimes[runtime_id]['observe']  || false;
  }

  // this is a temporary solution as long as we don't have a concept for tabs

  var __selected_runtime_id = '';

  var __next_runtime_id_to_select = ''

  this.setSelectedRuntime = function(runtime)
  {
    var r = '';
    for( r in __runtimes )
    {
      if( __runtimes[r] == runtime )
      {
        __runtimes[r]['selected'] = true;
        __selected_runtime_id = __runtimes[r]['runtime-id'];
      }
      else
      {
        // the runtime could be registered but not jet parsed
        if( __runtimes[r] )
        {
          __runtimes[r]['selected'] = false;
        }
      }
    }
  }

  this.setSelectedScript = function( runtime, id )
  {
    var scripts = this.getScripts(runtime['runtime-id']), script = null, i = 0;
    for( ; script = scripts[i]; i++)
    {
      script.selected = script['script-id'] == id ? true : false;
    }
  }

  this.setSelectedRuntimeId = function(id)
  {
    if(__runtimes[id])
    {
      this.setSelectedRuntime(__runtimes[id]);
      views.runtimes.update();
    }
    else
    {
      __next_runtime_id_to_select = id;
    }
  }

  this.getSelectedRuntimeId = function()
  {
    return __selected_runtime_id;
  }

}

//<|endoftext|>


<commit_before>export default {
  container: () => ({
    display: 'flex',
    flexDirection: 'column',
    flex: 1
  }),
  labelText: () => ({
    textTransform: 'capitalize'
  }),
  myGroupsContainer: () => ({
    display: 'flex',
    flexDirection: 'column',
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center'
  })
}
<commit_msg>feat(profile): styling<commit_after>export default {
  container: () => ({
    display: 'flex',
    flexDirection: 'column',
    flex: 1
  }),
  intro: () => ({
    textAlign: 'center',
    fontSize: '2rem'
  }),
  labelText: () => ({
    textTransform: 'capitalize'
  }),
  myGroupsContainer: () => ({
    display: 'flex',
    flexDirection: 'column',
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center'
  })
}
<|endoftext|>


<commit_before>(function(angular) {
'use strict';

  angular.module('app.<%= moduleName %>')
  .controller('<%= moduleNameCap %>UpdateController', <%= moduleNameCap %>UpdateController);

  <%= moduleNameCap %>UpdateController.$inject = ['$scope','<%= moduleName %>Resolve', '$mdDialog', '$timeout', '$state', '$mdToast'];

  function <%= moduleNameCap %>UpdateController($scope, <%= moduleName %>Resolve, $mdDialog, $timeout, $state, $mdToast){
    var vm = this;
    $scope.<%= moduleName %> = <%= moduleName %>Resolve;
    vm.action = ($scope.<%= moduleName %>.id)? 'Update' : 'Create';

    function makeToast(content, mdClass){
      return $mdToast.simple()
      .textContent(content)
      .toastClass(mdClass)
      .position('bottom right')
      .hideDelay(3000)
      .action('Close');
    }

    vm.update = function(event, <%= moduleName %>){
      if(vm.action == 'Create'){
        <%= moduleName %>.$save(function(){
          $mdToast.show(makeToast('<%= moduleName %> was created', 'md-toast-blue'));
        },function(){
          $mdToast.show(makeToast('<%= moduleName %> was not created', 'md-toast-red'));
        });
      }else{
        <%= moduleName %>.$update(function(){
          $mdToast.show(makeToast('<%= moduleName %> was created', 'md-toast-blue'));
        },function(){
          $mdToast.show(makeToast('<%= moduleName %> was not updated', 'md-toast-red'));
        });
      }
    };

    vm.delete = function(event, <%= moduleName %>){
      var confirmDialog = $mdDialog.confirm()
      .title('Delete <%= moduleName %>')
      .textContent('this <%= moduleName %> will be deleted and you no longer can find it')
      .ok('Delete')
      .cancel('Cancel')
      .targetEvent(event);
      $mdDialog.show(confirmDialog).then(function(doDelete){
        if(doDelete){
          $scope.<%= moduleName %>.$delete(function(){
            $mdToast.show(makeToast('<%= moduleName %> deleted', 'md-toast-blue'))
            .then(function(){
              $state.go('app.<%= moduleName %>.list');
            });
          },function(){
            $mdToast.show(makeToast('<%= moduleName %> was not deleted', 'md-toast-red'));
          });
        }
      });
    };
  }
})(angular);<commit_msg>adding link into toast when entity is created or updated<commit_after>(function(angular) {
'use strict';

  angular.module('app.<%= moduleName %>')
  .controller('<%= moduleNameCap %>UpdateController', <%= moduleNameCap %>UpdateController);

  <%= moduleNameCap %>UpdateController.$inject = ['$scope','<%= moduleName %>Resolve', '$mdDialog', '$timeout', '$state', '$mdToast'];

  function <%= moduleNameCap %>UpdateController($scope, <%= moduleName %>Resolve, $mdDialog, $timeout, $state, $mdToast){
    var vm = this;
    $scope.<%= moduleName %> = <%= moduleName %>Resolve;
    vm.action = ($scope.<%= moduleName %>.id)? 'Update' : 'Create';

    function makeToast(content, mdClass, action){
      if(!action){
        action = 'Close';
      }
      return $mdToast.simple()
      .textContent(content)
      .toastClass(mdClass)
      .position('bottom right')
      .hideDelay(3000)
      .action(action);
    }

    vm.update = function(event, <%= moduleName %>){
      if(vm.action == 'Create'){
        <%= moduleName %>.$save(function(){
          $mdToast.show(makeToast('<%= moduleName %> was created', 'md-toast-blue', 'See'))
          .then(function(answer){
            if(answer == 'ok'){
              $state.go('^.view', { id: <%= moduleName %>.id });
            }
          });
        },function(){
          $mdToast.show(makeToast('<%= moduleName %> was not created', 'md-toast-red'));
        });
      }else{
        <%= moduleName %>.$update(function(){
          $mdToast.show(makeToast('<%= moduleName %> was updated', 'md-toast-blue', 'See'))
          .then(function(answer){
            if(answer == 'ok'){
              $state.go('^.view', { id: <%= moduleName %>.id });
            }
          });
        },function(){
          $mdToast.show(makeToast('<%= moduleName %> was not updated', 'md-toast-red'));
        });
      }
    };

    vm.delete = function(event, <%= moduleName %>){
      var confirmDialog = $mdDialog.confirm()
      .title('Delete <%= moduleName %>')
      .textContent('this <%= moduleName %> will be deleted and you no longer can find it')
      .ok('Delete')
      .cancel('Cancel')
      .targetEvent(event);
      $mdDialog.show(confirmDialog).then(function(doDelete){
        if(doDelete){
          $scope.<%= moduleName %>.$delete(function(){
            $mdToast.show(makeToast('<%= moduleName %> deleted', 'md-toast-blue'))
            .then(function(){
              $state.go('app.<%= moduleName %>.list');
            });
          },function(){
            $mdToast.show(makeToast('<%= moduleName %> was not deleted', 'md-toast-red'));
          });
        }
      });
    };
  }
})(angular);<|endoftext|>


<commit_before>'use strict';

var Mapusaurus = {
    //  Leaflet map
    map: null,
    //  Leaflet layers
    layers: {tract: {minority: null}},
    //  Stores geo data, along with fields for layers
    dataStore: {tract: {}},
    //  Stores stat data when the associated geos aren't loaded
    dataWithoutGeo: {tract: {minority: {}}},
    //  Some style info
    bubbleStyle: {fillColor: '#fff', fillOpacity: 0.9, weight: 2,
                  color: '#000'},
    //  @todo: just make this a class
    hoverCSS: {position: 'absolute', bottom: '85px', left: '50px',
               zIndex: 1002, backgroundColor: '#fff', padding: '8px',
               border: '1px solid #ccc'},

    initialize: function (map) {
        map.setView([41.88, -87.63], 12);
        Mapusaurus.map = map;
        Mapusaurus.layers.tract.minority = L.geoJson(
            {type: 'FeatureCollection', features: []},
            {onEachFeature: Mapusaurus.eachMinority}
        );
        Mapusaurus.layers.tract.minority.addTo(map);
        if (Mapusaurus.urlParam('lender')) {
            Mapusaurus.layers.tract.loanVolume = L.layerGroup([]);
            Mapusaurus.layers.tract.loanVolume.addTo(map);
            Mapusaurus.dataWithoutGeo.tract.loanVolume = {};
        }
        //  @todo: really, we only care about the part of the viewport which
        //  is new
        map.on('moveend', Mapusaurus.reloadGeo);
        //  @todo: really, we only care on zoom-out + part which is new
        map.on('zoomend', Mapusaurus.reloadGeo);
        //  Kick it off
        Mapusaurus.reloadGeo();
    },

    /* Naive url parameter parser */
    urlParam: function(field) {
        var url = window.location.search.replace('?', ''),
            keyValueStrs = url.split('&'),
            pairs = _.map(keyValueStrs, function(keyValueStr) {
                return keyValueStr.split('=');
            }),
            params = _.reduce(pairs, function(soFar, pair) {
                if (pair.length === 2) {
                    soFar[pair[0]] = pair[1];
                }
                return soFar;
            }, {});
        return params[field];
    },

    /* Whenever the map is shifted/zoomed, reload geo data */
    reloadGeo: function() {
        var bounds = Mapusaurus.map.getBounds(),
            halfWidth = Math.abs(bounds.getEast() - bounds.getWest()) / 2,
            halfHeight = Math.abs(bounds.getNorth() - bounds.getSouth()) / 2,
            //  NW-hemisphere centric
            expandedN = bounds.getNorth() + halfHeight,
            expandedS = bounds.getSouth() - halfHeight,
            expandedW = bounds.getWest() - halfWidth,
            expandedE = bounds.getEast() + halfWidth;

        /* To be responsive, only load census tract data at zoom-level 10
         * or above */
        if (Mapusaurus.map.getZoom() >= 10) {
            Mapusaurus.loadTractData(
                1,
                L.latLngBounds(L.latLng(expandedS, expandedW),
                               L.latLng(expandedN, expandedE)));
        }
    },

    /* Load census tract geo data (by pages) into dataStore. Bounds should
     * remain consistent between pages of results */
    loadTractData: function(page, bounds) {
        //  This is north-western-hemisphere-centric for now
        $.getJSON('/shapes/tracts-in/?minlat=' + bounds.getSouth().toString() +
                  '&maxlat=' + bounds.getNorth().toString() +
                  '&minlon=' + bounds.getWest().toString() +
                  '&maxlon=' + bounds.getEast().toString() +
                  '&page_num=' + page.toString(),
                  function(data) {
            var newTracts = [];   //  geos we've never seen

            //  Collect new tracts, add them to dataStore
            _.each(data.features, function(feature) {
                var geoid = feature.properties.geoid;
                if (!_.has(Mapusaurus.dataStore.tract, geoid)) {
                    Mapusaurus.dataStore.tract[geoid] = feature;
                    newTracts.push(geoid);
                }
            });

            //  Check if there's anything new to draw, load stats data
            if (newTracts.length > 0) {
                Mapusaurus.updateDataWithoutGeos(newTracts);
                Mapusaurus.fetchMissingStats(newTracts);
            }

            //  Continue with next page of geo results
            if (data.features.length > 0) {
                Mapusaurus.loadTractData(page + 1, bounds);
            }
        });
    },

    /*  We may have previously loaded stats data without the geos. Run through
     *  that data and see if the new geo data matches */
    updateDataWithoutGeos: function(newTracts) {
        var toDraw = {},  // geoids by layer
            undrawnData = Mapusaurus.dataWithoutGeo.tract;
        //  For each layer
        _.each(_.keys(undrawnData), function (layerName) {
            toDraw[layerName] = [];

            //  For each shape
            _.each(newTracts, function(geoid) {
                var geoProps = Mapusaurus.dataStore.tract[geoid].properties;
                //  Check if the data can now be drawn
                if (_.has(undrawnData[layerName], geoid)) {
                    geoProps['layer_' + layerName] =
                        undrawnData[layerName][geoid];
                    toDraw[layerName].push(geoid);
                    delete undrawnData[layerName][geoid];
                }
            });
        });
        Mapusaurus.draw(toDraw);
    },

    /* We have geos without their associated stats - kick off the load */
    fetchMissingStats: function(newTracts) {
        //  For each layer
        _.each(_.keys(Mapusaurus.layers.tract), function(layerName) {
            //  We only care about unseen stat data
            var missingData = _.filter(newTracts, function(geoid) {
              return !_.has(Mapusaurus.dataStore.tract[geoid].properties,
                            'layer_' + layerName);
            });
            //  convert to state + county strings
            missingData = _.map(missingData, function(geoid) {
                var geo = Mapusaurus.dataStore.tract[geoid];
                return geo.properties.statefp + geo.properties.countyfp;
            });
            //  remove any duplicates; we end with what state/counties need to
            //  be retrieved
            missingData = _.uniq(missingData);

            //  start loading the data for each county
            _.each(missingData, function(stateCounty) {
                var state = stateCounty.substr(0, 2),
                    county = stateCounty.substr(2);
                Mapusaurus.loadLayerData(layerName, state, county);
            });
        });
    },

    /* Each layer has a different end point associated with it. Use that to
     * load (and eventually, draw) the layer stats */
    loadLayerData: function(layerName, state, county) {
        var url = null;
        switch(layerName) {
            case 'minority':
                url = ('/census/race-summary?state_fips=' + state +
                       '&county_fips=' + county);
                break;
            case 'loanVolume':
                url = ('/hmda/volume?state_fips=' + state +
                       '&county_fips=' + county +
                       '&lender=' + Mapusaurus.urlParam('lender'));
                break;
            default:
                window.alert('Unknown layer to load');
        }

        //  Now kick off the load for that layer
        $.getJSON(url, function(data) {
            var toDraw = {};
            toDraw[layerName] = [];
            _.each(_.keys(data), function(geoid) {
                var geo = Mapusaurus.dataStore.tract[geoid];
                //  Have not loaded the geo data yet
                if (!geo) {
                    Mapusaurus.dataWithoutGeo.tract[layerName][geoid] =
                        data[geoid];
                //  Have the geo data, but haven't drawn the stats yet
                } else if (!geo.properties['layer_' + layerName]) {
                    geo.properties['layer_' + layerName] = data[geoid];
                    toDraw[layerName].push(geoid);
                }
            });
            Mapusaurus.draw(toDraw);
        });
    },

    /* Given a list of geo ids, segmented by layer name, add them to the
     * leaflet layer. */
    draw: function(layerToGeoids) {
        // For each layer
        _.each(_.keys(layerToGeoids), function(layerName) {
            var geoData = _.map(layerToGeoids[layerName], function(geoid) {
              return Mapusaurus.dataStore.tract[geoid];
            });
            switch(layerName) {
                case 'minority':
                    Mapusaurus.layers.tract.minority.addData(geoData);
                    Mapusaurus.layers.tract.minority.bringToBack();
                    break;
                case 'loanVolume':
                    _.each(geoData, function(geo) {
                        Mapusaurus.layers.tract.loanVolume.addLayer(
                            Mapusaurus.makeBubble(geo.properties)
                        );
                    });
                    break;
            }
        });
    },

    /* Styles/extras for originations layer */
    makeBubble: function(geoProps) {
        var data = geoProps['layer_loanVolume'],
            circle = L.circle([geoProps.intptlat, geoProps.intptlon],
                              100 * data['volume_per_100_households'],
                              Mapusaurus.bubbleStyle);
        //  keep expected functionality with double clicking
        circle.on('dblclick', function(ev) {
            Mapusaurus.map.setZoomAround(
                ev.latlng, Mapusaurus.map.getZoom() + 1);
        });
        circle.on('mouseover', function() {
            var div = $('

', {
                id: 'household-popup-' + geoProps.geoid,
                css: Mapusaurus.hoverCSS
            });
            div.html(data['volume'] + ' loans
' +
                     data['num_households'] + ' households');
            div.appendTo('#map');
        });
        circle.on('mouseout', function() {
            $('#household-popup-' +
              geoProps.geoid).remove();
        });
        return circle;
    },

    /* Style/extras for each census tract in the minorities layer */
    eachMinority: function(feature, layer) {
      var nonMinorityPercent = feature.properties['layer_minority'][
          'non_hisp_white_only_perc'];
      layer.setStyle({
          fillColor: Mapusaurus.getColorValue(1 - nonMinorityPercent),
          fillOpacity: 0.7,
          weight: 2,
          color: '#babbbd'
      });
      //  keep expected functionality with double clicking
      layer.on('dblclick', function(ev) {
        Mapusaurus.map.setZoomAround(ev.latlng, Mapusaurus.map.getZoom() + 1);
      });
      layer.on('mouseover', function() {
        $('

', {
          id: 'perc-popup-' + feature.properties.geoid,
          text: (nonMinorityPercent * 100).toFixed() +
                 '% Non-hispanic White-Only',
          css: Mapusaurus.hoverCSS
        }).appendTo('#map');
      });
      layer.on('mouseout', function() {
        $('#perc-popup-' + feature.properties.geoid).remove();
      });
    },

    colorRanges: [
        {
            upperBound: 0.5,
            colors: {
                lowR: 255,
                lowG: 255,
                lowB: 217,
                highR: 242,
                highG: 251,
                highB: 184
            }
        },
        {
            upperBound: 0.8,
            colors: {
                lowR: 198,
                lowG: 234,
                lowB: 178,
                highR: 124,
                highG: 206,
                highB: 187
            }
        },
        {
            upperBound: 1.1,
            colors: {
                lowR: 14,
                lowG: 144,
                lowB: 194,
                highR: 29,
                highG: 92,
                highB: 170
            }
        }
    ],

    toBucket: function(percent) {
        var i,
            len = Mapusaurus.colorRanges.length;
        for (i = 0; i < len; i++) {
            if (Mapusaurus.colorRanges[i]['upperBound'] > percent) {
                return Mapusaurus.colorRanges[i]['colors'];
            }
        }
    },

    getColorValue: function(percent) {
        var colorVals = Mapusaurus.toBucket(percent);
        return Mapusaurus.colorFromPercent(percent, colorVals);
    },

    /* Given low and high colors and a percent, figure out the RGB of said
     * percent in that scale */
    colorFromPercent: function(percent, c) {
        var diffR = (c.highR - c.lowR) * percent,
            diffG = (c.highG - c.lowG) * percent,
            diffB = (c.highB - c.lowB) * percent;
        return 'rgb(' + (c.lowR + diffR).toFixed() + ', ' +
               (c.lowG + diffG).toFixed() + ', ' +
               (c.lowB + diffB).toFixed() + ')';
    }
};
<commit_msg>Fix some bugs with color selection<commit_after>'use strict';

var Mapusaurus = {
    //  Leaflet map
    map: null,
    //  Leaflet layers
    layers: {tract: {minority: null}},
    //  Stores geo data, along with fields for layers
    dataStore: {tract: {}},
    //  Stores stat data when the associated geos aren't loaded
    dataWithoutGeo: {tract: {minority: {}}},
    //  Some style info
    bubbleStyle: {fillColor: '#fff', fillOpacity: 0.9, weight: 2,
                  color: '#000'},
    //  @todo: just make this a class
    hoverCSS: {position: 'absolute', bottom: '85px', left: '50px',
               zIndex: 1002, backgroundColor: '#fff', padding: '8px',
               border: '1px solid #ccc'},

    initialize: function (map) {
        map.setView([41.88, -87.63], 12);
        Mapusaurus.map = map;
        Mapusaurus.layers.tract.minority = L.geoJson(
            {type: 'FeatureCollection', features: []},
            {onEachFeature: Mapusaurus.eachMinority}
        );
        Mapusaurus.layers.tract.minority.addTo(map);
        if (Mapusaurus.urlParam('lender')) {
            Mapusaurus.layers.tract.loanVolume = L.layerGroup([]);
            Mapusaurus.layers.tract.loanVolume.addTo(map);
            Mapusaurus.dataWithoutGeo.tract.loanVolume = {};
        }
        //  @todo: really, we only care about the part of the viewport which
        //  is new
        map.on('moveend', Mapusaurus.reloadGeo);
        //  @todo: really, we only care on zoom-out + part which is new
        map.on('zoomend', Mapusaurus.reloadGeo);
        //  Kick it off
        Mapusaurus.reloadGeo();
    },

    /* Naive url parameter parser */
    urlParam: function(field) {
        var url = window.location.search.replace('?', ''),
            keyValueStrs = url.split('&'),
            pairs = _.map(keyValueStrs, function(keyValueStr) {
                return keyValueStr.split('=');
            }),
            params = _.reduce(pairs, function(soFar, pair) {
                if (pair.length === 2) {
                    soFar[pair[0]] = pair[1];
                }
                return soFar;
            }, {});
        return params[field];
    },

    /* Whenever the map is shifted/zoomed, reload geo data */
    reloadGeo: function() {
        var bounds = Mapusaurus.map.getBounds(),
            halfWidth = Math.abs(bounds.getEast() - bounds.getWest()) / 2,
            halfHeight = Math.abs(bounds.getNorth() - bounds.getSouth()) / 2,
            //  NW-hemisphere centric
            expandedN = bounds.getNorth() + halfHeight,
            expandedS = bounds.getSouth() - halfHeight,
            expandedW = bounds.getWest() - halfWidth,
            expandedE = bounds.getEast() + halfWidth;

        /* To be responsive, only load census tract data at zoom-level 10
         * or above */
        if (Mapusaurus.map.getZoom() >= 10) {
            Mapusaurus.loadTractData(
                1,
                L.latLngBounds(L.latLng(expandedS, expandedW),
                               L.latLng(expandedN, expandedE)));
        }
    },

    /* Load census tract geo data (by pages) into dataStore. Bounds should
     * remain consistent between pages of results */
    loadTractData: function(page, bounds) {
        //  This is north-western-hemisphere-centric for now
        $.getJSON('/shapes/tracts-in/?minlat=' + bounds.getSouth().toString() +
                  '&maxlat=' + bounds.getNorth().toString() +
                  '&minlon=' + bounds.getWest().toString() +
                  '&maxlon=' + bounds.getEast().toString() +
                  '&page_num=' + page.toString(),
                  function(data) {
            var newTracts = [];   //  geos we've never seen

            //  Collect new tracts, add them to dataStore
            _.each(data.features, function(feature) {
                var geoid = feature.properties.geoid;
                if (!_.has(Mapusaurus.dataStore.tract, geoid)) {
                    Mapusaurus.dataStore.tract[geoid] = feature;
                    newTracts.push(geoid);
                }
            });

            //  Check if there's anything new to draw, load stats data
            if (newTracts.length > 0) {
                Mapusaurus.updateDataWithoutGeos(newTracts);
                Mapusaurus.fetchMissingStats(newTracts);
            }

            //  Continue with next page of geo results
            if (data.features.length > 0) {
                Mapusaurus.loadTractData(page + 1, bounds);
            }
        });
    },

    /*  We may have previously loaded stats data without the geos. Run through
     *  that data and see if the new geo data matches */
    updateDataWithoutGeos: function(newTracts) {
        var toDraw = {},  // geoids by layer
            undrawnData = Mapusaurus.dataWithoutGeo.tract;
        //  For each layer
        _.each(_.keys(undrawnData), function (layerName) {
            toDraw[layerName] = [];

            //  For each shape
            _.each(newTracts, function(geoid) {
                var geoProps = Mapusaurus.dataStore.tract[geoid].properties;
                //  Check if the data can now be drawn
                if (_.has(undrawnData[layerName], geoid)) {
                    geoProps['layer_' + layerName] =
                        undrawnData[layerName][geoid];
                    toDraw[layerName].push(geoid);
                    delete undrawnData[layerName][geoid];
                }
            });
        });
        Mapusaurus.draw(toDraw);
    },

    /* We have geos without their associated stats - kick off the load */
    fetchMissingStats: function(newTracts) {
        //  For each layer
        _.each(_.keys(Mapusaurus.layers.tract), function(layerName) {
            //  We only care about unseen stat data
            var missingData = _.filter(newTracts, function(geoid) {
              return !_.has(Mapusaurus.dataStore.tract[geoid].properties,
                            'layer_' + layerName);
            });
            //  convert to state + county strings
            missingData = _.map(missingData, function(geoid) {
                var geo = Mapusaurus.dataStore.tract[geoid];
                return geo.properties.statefp + geo.properties.countyfp;
            });
            //  remove any duplicates; we end with what state/counties need to
            //  be retrieved
            missingData = _.uniq(missingData);

            //  start loading the data for each county
            _.each(missingData, function(stateCounty) {
                var state = stateCounty.substr(0, 2),
                    county = stateCounty.substr(2);
                Mapusaurus.loadLayerData(layerName, state, county);
            });
        });
    },

    /* Each layer has a different end point associated with it. Use that to
     * load (and eventually, draw) the layer stats */
    loadLayerData: function(layerName, state, county) {
        var url = null;
        switch(layerName) {
            case 'minority':
                url = ('/census/race-summary?state_fips=' + state +
                       '&county_fips=' + county);
                break;
            case 'loanVolume':
                url = ('/hmda/volume?state_fips=' + state +
                       '&county_fips=' + county +
                       '&lender=' + Mapusaurus.urlParam('lender'));
                break;
            default:
                window.alert('Unknown layer to load');
        }

        //  Now kick off the load for that layer
        $.getJSON(url, function(data) {
            var toDraw = {};
            toDraw[layerName] = [];
            _.each(_.keys(data), function(geoid) {
                var geo = Mapusaurus.dataStore.tract[geoid];
                //  Have not loaded the geo data yet
                if (!geo) {
                    Mapusaurus.dataWithoutGeo.tract[layerName][geoid] =
                        data[geoid];
                //  Have the geo data, but haven't drawn the stats yet
                } else if (!geo.properties['layer_' + layerName]) {
                    geo.properties['layer_' + layerName] = data[geoid];
                    toDraw[layerName].push(geoid);
                }
            });
            Mapusaurus.draw(toDraw);
        });
    },

    /* Given a list of geo ids, segmented by layer name, add them to the
     * leaflet layer. */
    draw: function(layerToGeoids) {
        // For each layer
        _.each(_.keys(layerToGeoids), function(layerName) {
            var geoData = _.map(layerToGeoids[layerName], function(geoid) {
              return Mapusaurus.dataStore.tract[geoid];
            });
            switch(layerName) {
                case 'minority':
                    Mapusaurus.layers.tract.minority.addData(geoData);
                    Mapusaurus.layers.tract.minority.bringToBack();
                    break;
                case 'loanVolume':
                    _.each(geoData, function(geo) {
                        Mapusaurus.layers.tract.loanVolume.addLayer(
                            Mapusaurus.makeBubble(geo.properties)
                        );
                    });
                    break;
            }
        });
    },

    /* Styles/extras for originations layer */
    makeBubble: function(geoProps) {
        var data = geoProps['layer_loanVolume'],
            circle = L.circle([geoProps.intptlat, geoProps.intptlon],
                              100 * data['volume_per_100_households'],
                              Mapusaurus.bubbleStyle);
        //  keep expected functionality with double clicking
        circle.on('dblclick', function(ev) {
            Mapusaurus.map.setZoomAround(
                ev.latlng, Mapusaurus.map.getZoom() + 1);
        });
        circle.on('mouseover', function() {
            var div = $('

', {
                id: 'household-popup-' + geoProps.geoid,
                css: Mapusaurus.hoverCSS
            });
            div.html(data['volume'] + ' loans
' +
                     data['num_households'] + ' households');
            div.appendTo('#map');
        });
        circle.on('mouseout', function() {
            $('#household-popup-' +
              geoProps.geoid).remove();
        });
        return circle;
    },

    /* Style/extras for each census tract in the minorities layer */
    eachMinority: function(feature, layer) {
      var nonMinorityPercent = feature.properties['layer_minority'][
          'non_hisp_white_only_perc'];
      layer.setStyle({
          fillColor: Mapusaurus.getColorValue(1 - nonMinorityPercent),
          fillOpacity: 0.7,
          weight: 2,
          color: '#babbbd'
      });
      //  keep expected functionality with double clicking
      layer.on('dblclick', function(ev) {
        Mapusaurus.map.setZoomAround(ev.latlng, Mapusaurus.map.getZoom() + 1);
      });
      layer.on('mouseover', function() {
        $('

', {
          id: 'perc-popup-' + feature.properties.geoid,
          text: (nonMinorityPercent * 100).toFixed() +
                 '% Non-hispanic White-Only',
          css: Mapusaurus.hoverCSS
        }).appendTo('#map');
      });
      layer.on('mouseout', function() {
        $('#perc-popup-' + feature.properties.geoid).remove();
      });
    },

    colorRanges: [
        {
            span: 0.5,
            lowerBound: 0,
            colors: {
                lowR: 255,
                lowG: 255,
                lowB: 217,
                highR: 198,
                highG: 234,
                highB: 178
            }
        },
        {
            span: 0.3,
            lowerBound: 0.5,
            colors: {
                lowR: 198,
                lowG: 234,
                lowB: 178,
                highR: 14,
                highG: 144,
                highB: 194
            }
        },
        {
            span: 0.2,
            lowerBound: 0.8,
            colors: {
                lowR: 14,
                lowG: 144,
                lowB: 194,
                highR: 29,
                highG: 92,
                highB: 170
            }
        }
    ],

    toBucket: function(percent) {
        var i,
            len = Mapusaurus.colorRanges.length;
        for (i = 0; i < len - 1; i++) {
            //  Next bucket is too far
            if (Mapusaurus.colorRanges[i + 1].lowerBound > percent) {
                return Mapusaurus.colorRanges[i];
            }
        }
        return Mapusaurus.colorRanges[len - 1];  //  last color
    },

    getColorValue: function(percent) {
        var bucket = Mapusaurus.toBucket(percent),
            // convert given percentage to percents within bucket's bounds
            bucketPercent = (percent - bucket.lowerBound) / bucket.span;
        return Mapusaurus.colorFromPercent(bucketPercent, bucket.colors);
    },

    /* Given low and high colors and a percent, figure out the RGB of said
     * percent in that scale */
    colorFromPercent: function(percent, c) {
        var diffR = (c.highR - c.lowR) * percent,
            diffG = (c.highG - c.lowG) * percent,
            diffB = (c.highB - c.lowB) * percent;
        return 'rgb(' + (c.lowR + diffR).toFixed() + ', ' +
               (c.lowG + diffG).toFixed() + ', ' +
               (c.lowB + diffB).toFixed() + ')';
    }
};
<|endoftext|>


<commit_before>'use strict';

function FloatingText(width, text, type, scene, is_2D_text) {

    /*   __   __        __  ___  __        __  ___  __   __
        /  ` /  \ |\ | /__`  |  |__) |  | /  `  |  /  \ |__)
        \__, \__/ | \| .__/  |  |  \ \__/ \__,  |  \__/ |  \ */
    this.is_2D_text = is_2D_text;
    this.width         = width;
    this.type          = type;
    this.scene         = scene;
    this.object3D      = new THREE.Object3D();

    this.current_color = null;
    this.default_color = null;

    this.format_type   = null;

    // Default value.
    this.normal_depth  = 1;

    if (this.type === TYPE_PASSWORD) {
        this.text = '';
        for (var c = 0; c < text.length; c++) {
            this.text += '*';
        }
        this.hidden_text = text;
    } else {
        this.text = text;
    }

    // Call the child initialize functions.
    this.initialize();

    // Gets called from child functions.
    this.final_initialize = function() {
        if(!is_defined(this.current_color)) {
            switch (this.type) {
            case TYPE_BUTTON:
            case TYPE_CHECK_BOX:
                this.set_default_color(COLOR_TEXT_BUTTON);
                this.maintain_engage_when_tabbed_to = false;
                this.engable = false;
                break;
            case TYPE_CONSTANT:
                this.set_default_color(COLOR_TEXT_CONSTANT);
                this.engable = false;
                break;
            case TYPE_TITLE:
                this.set_default_color(COLOR_TEXT_DEFAULT);
                break;
            default:
                this.set_default_color(COLOR_TEXT_DEFAULT);
                break;
            }
        }

        if (this.type === TYPE_BUTTON) {
            // Inherit from InheritableButton.
            InheritableButton.call(this);
        }
    };

    /*   ___            __  ___    __        __
        |__  |  | |\ | /  `  |  | /  \ |\ | /__`
        |    \__/ | \| \__,  |  | \__/ | \| .__/ */
    this.set_format_type = function(format_type) {
        this.format_type = format_type;
    };

    this.set_default_color = function(default_color) {
        if (is_list(default_color)) {
            if (this.is_2D_text) {
                this.default_color = default_color[COLOR_STRING_INDEX];
            } else {
                this.default_color = default_color[COLOR_HEX_INDEX];
            }
        } else {
            if (!this.is_2D_text) {
                if (default_color.toString().includes('#')) {
                    default_color = parseInt(default_color.replace('#', '0x'));
                }
            }
            this.default_color = default_color;
        }
        this.current_color = this.default_color;
        if (!is_defined(this.previous_default_color)) {
            this.previous_default_color = this.default_color;
        }
        this._update_color();
    };

    // Gets called in constructor so defining this function first.
    this.update_color = function(color) {
        if (is_list(color)) {
            var color_to_set = null;
            if (this.is_2D_text) {
                color_to_set = color[COLOR_STRING_INDEX];
            } else {
                color_to_set = color[COLOR_HEX_INDEX];
            }
            this.current_color = color_to_set;
            this._update_color();
        } else {
            if (this.is_2D_text) {
                this.current_color = color;
                this._update_color();
            } else {
                if (color.toString().includes('#')) {
                    color = parseInt(color.replace('#', '0x'));
                    this.current_color = color;
                    this._update_color();
                }
            }
        }
    };

    this.update_text = function(text) {
        if (this.get_text() !== text) {
            if (is_defined(this.value_pre_changed_function)) {
                this.value_pre_changed_function(text);
            }
            if (this.type === TYPE_PASSWORD) {
                this.hidden_text = '';
                this.text = '';
                for (var c = 0; c < text.length; c++) {
                    this.hidden_text += text.charAt(c);
                    this.text += '*';
                }
            } else {
                this.text = text;
            }
            this._update_text();
            if (is_defined(this.value_post_changed_function)) {
                this.value_post_changed_function(text);
            }
        }
    };

    this.get_text_as_value = function() {
        return parseInt(this.get_text());
    };

    this.get_text = function() {
        if (this.type === TYPE_PASSWORD) {
            return this.hidden_text;
        }
        return this.text;
    };

    this._add_character = function(character) {
        this.update_text(this.get_text() + character);
    };

    this._pop_character = function() {
        var t = this.get_text();
        this.update_text(t.slice(0, -1));
    };

    this.parse_text = function(text) {
        for (var i = 0; i < text.length; i++) {
            this._add_character(text.charAt(i));
        }
    };

    this.parse_keycode = function(event) {
        var keycode = event.keyCode;

        if (keycode === KEY_CODE_DELETE) {
            if (this.get_text().length > 0) {
                this._pop_character();
                MANAGER_AUDIO.play_typing_sound();
            }
        } else if (event.key.length === 1) {
            this._add_character(event.key);
            MANAGER_AUDIO.play_typing_sound();
        }
    };

    this.get_position = function() {
        return this.object3D.position;
    };

    this.update_position_and_look_at_origin = function(position_vector) {
        this.update_position_and_normal(position_vector, new THREE.Vector3(0 - position_vector.x, 0, 0 - position_vector.z));
    };

    this.update_position = function(position_vector) {
        // TODO : optimize

        this.object3D.position.x = position_vector.x + this.normal.x * this.normal_depth;
        this.object3D.position.y = position_vector.y + this.normal.y * this.normal_depth;
        this.object3D.position.z = position_vector.z + this.normal.z * this.normal_depth;

        this.x_without_normal = this.object3D.position.x - this.normal.x * this.normal_depth;
        this.y_without_normal = this.object3D.position.y - this.normal.y * this.normal_depth;
        this.z_without_normal = this.object3D.position.z - this.normal.z * this.normal_depth;
    };

    this.update_position_with_offset_xyz = function(x, y, z) {
        // TODO : optimize

        this.object3D.position.x = this.x_without_normal + x + this.normal.x * this.normal_depth;
        this.object3D.position.y = this.y_without_normal + y + this.normal.y * this.normal_depth;
        this.object3D.position.z = this.z_without_normal + z + this.normal.z * this.normal_depth;

        this.x_without_normal = this.object3D.position.x - this.normal.x * this.normal_depth;
        this.y_without_normal = this.object3D.position.y - this.normal.y * this.normal_depth;
        this.z_without_normal = this.object3D.position.z - this.normal.z * this.normal_depth;
    };

    this.set_normal_depth = function(depth) {
        if (depth <= 0) {
            this.normal_depth = 1;
        } else {
            this.normal_depth = depth;
        }
    };

    this.update_normal = function(normal) {
        this.normal = new THREE.Vector3(normal.x, normal.y, normal.z);
        this.normal.normalize();
        this.object3D.lookAt(new THREE.Vector3(this.object3D.position.x + this.normal.x * 100, this.object3D.position.y + this.normal.y * 100, this.object3D.position.z + this.normal.z * 100));
    };

    this.update_position_and_normal = function(position_vector, normal) {
        this.update_normal(normal);
        this.update_position(position_vector);
    };

    this.clear = function() {
        this._update_text('');
    };

    /*__   ___ ___ ___  ___  __   __
     / _` |__   |   |  |__  |__) /__`
     \__> |___  |   |  |___ |  \ .__/ */
    this.get_text_length = function() {
        if (this.is_2D_text) {
            return this.dynamic_texture.getTextLength(this.text);
        } else {
            return this.width;
        }
    };

    /* __  ___      ___  ___     __                  __   ___  __
      /__`  |   /\   |  |__     /  ` |__|  /\  |\ | / _` |__  /__`
      .__/  |  /~~\  |  |___    \__, |  | /~~\ | \| \__> |___ .__/ */
    this.state_change_look_at = function(being_looked_at) {
        if (being_looked_at) {
            if (this.hasOwnProperty('current_background_color')) {
                this.current_background_color = BACKGROUND_COLOR_FOCUS;
            }
            this.update_color(COLOR_HIGHLIGHT);
        } else {
            if (this.hasOwnProperty('current_background_color')) {
                this.current_background_color = this.default_background_color;
            }
            this.update_color(this.default_color);
        }
    };

    this.state_change_engage = function(being_engaged_with) {
        if (being_engaged_with) {
            if (this.type !== TYPE_BUTTON && this.type !== TYPE_CHECK_BOX) {
                CURRENT_PLAYER.engage();
            } else {
                this.being_engaged_with = false;
                CURRENT_PLAYER.disengage();

                if (MANAGER_WORLD.current_floating_cursor.engaged) {
                    l('disengage the cursor please!');
                    MANAGER_WORLD.current_floating_cursor.disengage();
                }
            }
        } else {
            CURRENT_PLAYER.disengage();

            if (MANAGER_WORLD.current_floating_cursor.engaged) {
                l('disengage the cursor please 2!');
                MANAGER_WORLD.current_floating_cursor.disengage();
            }
        }
    };
}<commit_msg>general updating 142<commit_after>'use strict';

function FloatingText(width, text, type, scene, is_2D_text) {

    // Needs to be defined here for now.
    this.get_text_length = function() {
        if (this.is_2D_text) {
            return this.dynamic_texture.getTextLength(this.text);
        } else {
            return this.width;
        }
    };

    /*   __   __        __  ___  __        __  ___  __   __
        /  ` /  \ |\ | /__`  |  |__) |  | /  `  |  /  \ |__)
        \__, \__/ | \| .__/  |  |  \ \__/ \__,  |  \__/ |  \ */
    this.is_2D_text = is_2D_text;
    this.width         = width;
    this.type          = type;
    this.scene         = scene;
    this.object3D      = new THREE.Object3D();

    this.current_color = null;
    this.default_color = null;

    this.format_type   = null;

    // Default value.
    this.normal_depth  = 1;

    if (this.type === TYPE_PASSWORD) {
        this.hidden_text = text;
        this.text = '';
        for (var c = 0; c < this.hidden_text.length; c++) {
            this.text += '*';
        }
    } else {
        this.text = text;
    }

    // Call the child initialize functions.
    this.initialize();

    // Gets called from child functions.
    this.final_initialize = function() {
        if(!is_defined(this.current_color)) {
            switch (this.type) {
            case TYPE_BUTTON:
            case TYPE_CHECK_BOX:
                this.set_default_color(COLOR_TEXT_BUTTON);
                this.maintain_engage_when_tabbed_to = false;
                this.engable = false;
                break;
            case TYPE_CONSTANT:
                this.set_default_color(COLOR_TEXT_CONSTANT);
                this.engable = false;
                break;
            case TYPE_TITLE:
                this.set_default_color(COLOR_TEXT_DEFAULT);
                break;
            default:
                this.set_default_color(COLOR_TEXT_DEFAULT);
                break;
            }
        }

        if (this.type === TYPE_BUTTON) {
            // Inherit from InheritableButton.
            InheritableButton.call(this);
        }
    };

    /*   ___            __  ___    __        __
        |__  |  | |\ | /  `  |  | /  \ |\ | /__`
        |    \__/ | \| \__,  |  | \__/ | \| .__/ */
    this.set_format_type = function(format_type) {
        this.format_type = format_type;
    };

    this.set_default_color = function(default_color) {
        if (is_list(default_color)) {
            if (this.is_2D_text) {
                this.default_color = default_color[COLOR_STRING_INDEX];
            } else {
                this.default_color = default_color[COLOR_HEX_INDEX];
            }
        } else {
            if (!this.is_2D_text) {
                if (default_color.toString().includes('#')) {
                    default_color = parseInt(default_color.replace('#', '0x'));
                }
            }
            this.default_color = default_color;
        }
        this.current_color = this.default_color;
        if (!is_defined(this.previous_default_color)) {
            this.previous_default_color = this.default_color;
        }
        this._update_color();
    };

    // Gets called in constructor so defining this function first.
    this.update_color = function(color) {
        if (is_list(color)) {
            var color_to_set = null;
            if (this.is_2D_text) {
                color_to_set = color[COLOR_STRING_INDEX];
            } else {
                color_to_set = color[COLOR_HEX_INDEX];
            }
            this.current_color = color_to_set;
            this._update_color();
        } else {
            if (this.is_2D_text) {
                this.current_color = color;
                this._update_color();
            } else {
                if (color.toString().includes('#')) {
                    color = parseInt(color.replace('#', '0x'));
                    this.current_color = color;
                    this._update_color();
                }
            }
        }
    };

    this.update_text = function(text) {
        if (this.get_text() !== text) {
            if (is_defined(this.value_pre_changed_function)) {
                this.value_pre_changed_function(text);
            }
            if (this.type === TYPE_PASSWORD) {
                this.hidden_text = '';
                this.text = '';
                for (var c = 0; c < text.length; c++) {
                    this.hidden_text += text.charAt(c);
                    this.text += '*';
                }
            } else {
                this.text = text;
            }
            this._update_text();
            if (is_defined(this.value_post_changed_function)) {
                this.value_post_changed_function(text);
            }
        }
    };

    this.get_text_as_value = function() {
        return parseInt(this.get_text());
    };

    this.get_text = function() {
        if (this.type === TYPE_PASSWORD) {
            return this.hidden_text;
        }
        return this.text;
    };

    this._add_character = function(character) {
        this.update_text(this.get_text() + character);
    };

    this._pop_character = function() {
        var t = this.get_text();
        this.update_text(t.slice(0, -1));
    };

    this.parse_text = function(text) {
        for (var i = 0; i < text.length; i++) {
            this._add_character(text.charAt(i));
        }
    };

    this.parse_keycode = function(event) {
        var keycode = event.keyCode;

        if (keycode === KEY_CODE_DELETE) {
            if (this.get_text().length > 0) {
                this._pop_character();
                MANAGER_AUDIO.play_typing_sound();
            }
        } else if (event.key.length === 1) {
            this._add_character(event.key);
            MANAGER_AUDIO.play_typing_sound();
        }
    };

    this.get_position = function() {
        return this.object3D.position;
    };

    this.update_position_and_look_at_origin = function(position_vector) {
        this.update_position_and_normal(position_vector, new THREE.Vector3(0 - position_vector.x, 0, 0 - position_vector.z));
    };

    this.update_position = function(position_vector) {
        // TODO : optimize

        this.object3D.position.x = position_vector.x + this.normal.x * this.normal_depth;
        this.object3D.position.y = position_vector.y + this.normal.y * this.normal_depth;
        this.object3D.position.z = position_vector.z + this.normal.z * this.normal_depth;

        this.x_without_normal = this.object3D.position.x - this.normal.x * this.normal_depth;
        this.y_without_normal = this.object3D.position.y - this.normal.y * this.normal_depth;
        this.z_without_normal = this.object3D.position.z - this.normal.z * this.normal_depth;
    };

    this.update_position_with_offset_xyz = function(x, y, z) {
        // TODO : optimize

        this.object3D.position.x = this.x_without_normal + x + this.normal.x * this.normal_depth;
        this.object3D.position.y = this.y_without_normal + y + this.normal.y * this.normal_depth;
        this.object3D.position.z = this.z_without_normal + z + this.normal.z * this.normal_depth;

        this.x_without_normal = this.object3D.position.x - this.normal.x * this.normal_depth;
        this.y_without_normal = this.object3D.position.y - this.normal.y * this.normal_depth;
        this.z_without_normal = this.object3D.position.z - this.normal.z * this.normal_depth;
    };

    this.set_normal_depth = function(depth) {
        if (depth <= 0) {
            this.normal_depth = 1;
        } else {
            this.normal_depth = depth;
        }
    };

    this.update_normal = function(normal) {
        this.normal = new THREE.Vector3(normal.x, normal.y, normal.z);
        this.normal.normalize();
        this.object3D.lookAt(new THREE.Vector3(this.object3D.position.x + this.normal.x * 100, this.object3D.position.y + this.normal.y * 100, this.object3D.position.z + this.normal.z * 100));
    };

    this.update_position_and_normal = function(position_vector, normal) {
        this.update_normal(normal);
        this.update_position(position_vector);
    };

    this.clear = function() {
        this._update_text('');
    };

    /*__   ___ ___ ___  ___  __   __
     / _` |__   |   |  |__  |__) /__`
     \__> |___  |   |  |___ |  \ .__/ */

    /* __  ___      ___  ___     __                  __   ___  __
      /__`  |   /\   |  |__     /  ` |__|  /\  |\ | / _` |__  /__`
      .__/  |  /~~\  |  |___    \__, |  | /~~\ | \| \__> |___ .__/ */
    this.state_change_look_at = function(being_looked_at) {
        if (being_looked_at) {
            if (this.hasOwnProperty('current_background_color')) {
                this.current_background_color = BACKGROUND_COLOR_FOCUS;
            }
            this.update_color(COLOR_HIGHLIGHT);
        } else {
            if (this.hasOwnProperty('current_background_color')) {
                this.current_background_color = this.default_background_color;
            }
            this.update_color(this.default_color);
        }
    };

    this.state_change_engage = function(being_engaged_with) {
        if (being_engaged_with) {
            if (this.type !== TYPE_BUTTON && this.type !== TYPE_CHECK_BOX) {
                CURRENT_PLAYER.engage();
            } else {
                this.being_engaged_with = false;
                CURRENT_PLAYER.disengage();

                if (MANAGER_WORLD.current_floating_cursor.engaged) {
                    l('disengage the cursor please!');
                    MANAGER_WORLD.current_floating_cursor.disengage();
                }
            }
        } else {
            CURRENT_PLAYER.disengage();

            if (MANAGER_WORLD.current_floating_cursor.engaged) {
                l('disengage the cursor please 2!');
                MANAGER_WORLD.current_floating_cursor.disengage();
            }
        }
    };
}<|endoftext|>


<commit_before>module.exports = {
  normalizeEntityName: function() {},

  afterInstall: function(options) {
    if (!('ember-cli-shims' in options.project.addonPackages)) {
      return this.addBowerPackageToProject('ember-cli-shims', '~0.1.1');
    }
  }
};
<commit_msg>Adding ember-cli-shims to bower is not longer needed nor advised. (#306)<commit_after><|endoftext|>


<commit_before>/**
 * Output view for KBaseFBA.FBAPathwayAnalysis objects.
 *
 * Fetches workspaces object, computes stats, and renders view for data using plotly.
 *
 * @param Takes a {type: <type>, ws: <workspace>, obj: <obj>}, where <type>
 * is a workspace type, and where <ws>/<obj> is a pair of workspace/object names or ids.
 *
 * @author nconrad <nconrad@anl.gov>
 * @public
 */

 define (
	[
		'kbwidget',
		'bootstrap',
		'jquery',
		'plotly',
		'kbaseAuthenticatedWidget',
		'KBModeling'
	], function(
		KBWidget,
		bootstrap,
		$,
		Plotly,
		kbaseAuthenticatedWidget,
		KBModeling
	) {

    return KBWidget({
        name: "kbaseExpressionAnalysis",
        parent : kbaseAuthenticatedWidget,
        version: "1.0.0",
        options: {},
        init: function(input) {
            var self = this;
            this._super(input);
            var container = this.$elem;

            // api helper
            var api = new KBModeling( self.authToken() ).kbapi;

            // accept workspace/object ids or strings
            if (isNaN(input.ws) && isNaN(input.obj) )
                var param = {workspace: input.ws, name: input.obj};
            else if (!isNaN(input.ws) && !isNaN(input.obj) )
                var param = {ref: input.ws+'/'+input.obj};

            // get data, format, and render data
            api('ws', 'get_objects', [param])
                .then(function(res) {
                    var data = formatData(res[0].data);
                    render(data.values, data.y);
                })

            // takes KBaseFBA.FBAPathwayAnalysis data,
            // and returns data needed to render stacked bar chart
            function formatData(data) {
                var pathways = data.pathways;

                var y = [];
                var values = {
                    gpRxnsFluxP: [],
                    gsrFluxMExpM: [],
                    gsrFluxMExpP: [],
                    gsrFluxPExpN: [],
                    gsrFluxPExpP: []
                }

                var i = pathways.length;
                while (i--) {
                    var o = pathways[i];
                    y.push(o.pathwayName + ' ('+o.totalModelReactions+')');

                    var total = o.gpRxnsFluxP + o.gsrFluxMExpM + o.gsrFluxMExpP +
                                o.gsrFluxPExpN + o.gsrFluxPExpP;

                    values.gpRxnsFluxP.push( o.gpRxnsFluxP / total * 100);
                    values.gsrFluxMExpM.push(o.gsrFluxMExpM / total * 100 );
                    values.gsrFluxMExpP.push(o.gsrFluxMExpP / total * 100 );
                    values.gsrFluxPExpN.push(o.gsrFluxPExpN / total * 100 );
                    values.gsrFluxPExpP.push(o.gsrFluxPExpP / total * 100 );
                }

                return {values: values, y: y};
            }

            function render(values, y) {
                var basopts = {
                    x: null,
                    y: y,
                    name: null,
                    orientation: 'h',
                    marker: {
                        color: null,
                        width: 1
                    },
                    type: 'bar'
                };

                var trace1 = $.extend({}, basopts, {
                    x: values.gsrFluxPExpP,
                    name: 'GAR Active flux and expression',
                    marker: {
                        color: 'rgba(243, 13, 13, .7)'
                    }
                });

                var trace2 = $.extend({}, basopts, {
                    x: values.gsrFluxMExpM,
                    name: 'GAR No flux or expression',
                    marker: {
                        color: 'rgba(99, 78, 58,.8)'
                    }
                });

                var trace3 = $.extend({}, basopts, {
                    x: values.gsrFluxMExpP,
                    name: 'GAR No flux, but active expression',
                    marker: {
                        color: 'rgba(173, 169, 86, .7)'
                    }
                });

                var trace4 = $.extend({}, basopts, {
                    x: values.gsrFluxPExpN,
                    name: 'Active flux, but no expression',
                    marker: {
                        color: 'rgba(64, 153, 62, .8)'
                    }
                });

                var trace5 = $.extend({}, basopts, {
                    x: values.gpRxnsFluxP,
                    name: 'Active gapfilled reactions',
                    marker: {
                        color: 'rgba(33, 150, 243, .8)'
                    }
                });

                var data = [trace1, trace2, trace3, trace4, trace5]

                var layout = {
                    title: 'Flux Balance Analysis Against Gene Expression',
                    barmode: 'stack',
                    margin: {
                       l: 350
                    },
                    height: 1000,
                    xaxis: {
                        title: 'Percent of each category',
                        titlefont: {
                            color: '#7f7f7f'
                        }
                    }
                };

                // add container
                var vizContainer = $('<div>').uniqueId();
                container.append(vizContainer);
                var id = vizContainer.attr('id');

                // render
                Plotly.newPlot(id, data, layout);

            }

            return this;
        },
    })

})
<commit_msg>Fixed issue with expression analysis widget<commit_after>/**
 * Output view for KBaseFBA.FBAPathwayAnalysis objects.
 *
 * Fetches workspaces object, computes stats, and renders view for data using plotly.
 *
 * @param Takes a {type: <type>, ws: <workspace>, obj: <obj>}, where <type>
 * is a workspace type, and where <ws>/<obj> is a pair of workspace/object names or ids.
 *
 * @author nconrad <nconrad@anl.gov>
 * @public
 */

 define (
	[
		'kbwidget',
		'bootstrap',
		'jquery',
		'plotly',
		'kbaseAuthenticatedWidget',
		'KBModeling'
	], function(
		KBWidget,
		bootstrap,
		$,
		Plotly,
		kbaseAuthenticatedWidget
		// KBModeling
	) {

    return KBWidget({
        name: "kbaseExpressionAnalysis",
        parent : kbaseAuthenticatedWidget,
        version: "1.0.0",
        options: {},
        init: function(input) {
            var self = this;
            this._super(input);
            var container = this.$elem;

            // api helper
            var api = new KBModeling( self.authToken() ).kbapi;

            // accept workspace/object ids or strings
            if (isNaN(input.ws) && isNaN(input.obj) )
                var param = {workspace: input.ws, name: input.obj};
            else if (!isNaN(input.ws) && !isNaN(input.obj) )
                var param = {ref: input.ws+'/'+input.obj};

            // get data, format, and render data
            api('ws', 'get_objects', [param])
                .then(function(res) {
                    var data = formatData(res[0].data);
                    render(data.values, data.y);
                })

            // takes KBaseFBA.FBAPathwayAnalysis data,
            // and returns data needed to render stacked bar chart
            function formatData(data) {
                var pathways = data.pathways;

                var y = [];
                var values = {
                    gpRxnsFluxP: [],
                    gsrFluxMExpM: [],
                    gsrFluxMExpP: [],
                    gsrFluxPExpN: [],
                    gsrFluxPExpP: []
                }

                var i = pathways.length;
                while (i--) {
                    var o = pathways[i];
                    y.push(o.pathwayName + ' ('+o.totalModelReactions+')');

                    var total = o.gpRxnsFluxP + o.gsrFluxMExpM + o.gsrFluxMExpP +
                                o.gsrFluxPExpN + o.gsrFluxPExpP;

                    values.gpRxnsFluxP.push( o.gpRxnsFluxP / total * 100);
                    values.gsrFluxMExpM.push(o.gsrFluxMExpM / total * 100 );
                    values.gsrFluxMExpP.push(o.gsrFluxMExpP / total * 100 );
                    values.gsrFluxPExpN.push(o.gsrFluxPExpN / total * 100 );
                    values.gsrFluxPExpP.push(o.gsrFluxPExpP / total * 100 );
                }

                return {values: values, y: y};
            }

            function render(values, y) {
                var basopts = {
                    x: null,
                    y: y,
                    name: null,
                    orientation: 'h',
                    marker: {
                        color: null,
                        width: 1
                    },
                    type: 'bar'
                };

                var trace1 = $.extend({}, basopts, {
                    x: values.gsrFluxPExpP,
                    name: 'GAR Active flux and expression',
                    marker: {
                        color: 'rgba(243, 13, 13, .7)'
                    }
                });

                var trace2 = $.extend({}, basopts, {
                    x: values.gsrFluxMExpM,
                    name: 'GAR No flux or expression',
                    marker: {
                        color: 'rgba(99, 78, 58,.8)'
                    }
                });

                var trace3 = $.extend({}, basopts, {
                    x: values.gsrFluxMExpP,
                    name: 'GAR No flux, but active expression',
                    marker: {
                        color: 'rgba(173, 169, 86, .7)'
                    }
                });

                var trace4 = $.extend({}, basopts, {
                    x: values.gsrFluxPExpN,
                    name: 'Active flux, but no expression',
                    marker: {
                        color: 'rgba(64, 153, 62, .8)'
                    }
                });

                var trace5 = $.extend({}, basopts, {
                    x: values.gpRxnsFluxP,
                    name: 'Active gapfilled reactions',
                    marker: {
                        color: 'rgba(33, 150, 243, .8)'
                    }
                });

                var data = [trace1, trace2, trace3, trace4, trace5]

                var layout = {
                    title: 'Flux Balance Analysis Against Gene Expression',
                    barmode: 'stack',
                    margin: {
                       l: 350
                    },
                    height: 1000,
                    xaxis: {
                        title: 'Percent of each category',
                        titlefont: {
                            color: '#7f7f7f'
                        }
                    }
                };

                // add container
                var vizContainer = $('<div>').uniqueId();
                container.append(vizContainer);
                var id = vizContainer.attr('id');

                // render
                Plotly.newPlot(id, data, layout);

            }

            return this;
        },
    })

})
<|endoftext|>