<commit_before>var debugger = new function()
{
  var self = this;
  var service = "ecmascript-debugger";

  this.getEvent = function()
  {
    proxy.GET( "/" + service, genericEventListener );
  }

  var genericEventListener = function(xml)
  {
    if(xml)
    {
      if( tagManager.handleResponse(xml) )
      {
        //alert('handled by tag manager');
      }
      else if( self[xml.documentElement.nodeName] )
      {
        //alert('handled by else if');
        self[xml.documentElement.nodeName](xml)
      }
      else
      {
        debug.output('not implemented: '+new XMLSerializer().serializeToString(xml));
      }
      debug.formatXML(new XMLSerializer().serializeToString(xml));
    }
    self.getEvent();
  }

  var runtimes = {};

  var addRuntime = function(id)
  {
    if( !(id in runtimes) )
    {
      runtimes[id] = null;
      self.getRuntime(id);
    }
  }

  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;
    for ( ; r_t=r_ts[i]; i++)
    {
      runtimeId = r_t.getNodeData('runtime-id');
      if(runtimeId)
      {
        runtime={};
        children = r_t.childNodes;
        for(j=0 ; child = children[j]; j++)
        {
          runtime[child.nodeName] = child.textContent;
        }
        runtimes[runtimeId] = runtime;
        document.getElementById('runtime-ids').render(templates.runtimeId(runtime))
      }
    }
  }

  var parseBacktrace = function(xml, runtime_id)
  {

    var _frames = xml.getElementsByTagName('frame'), frame = null, i = 0;
    var fn_name = '', line = '', script_id = '', argument_id = '', scope_id = '';
    var container = document.getElementById('backtrace');
    container.innerHTML = '';
    for( ; frame  = _frames[i]; i++ )
    {
      fn_name = frame.getNodeData('function-name');
      line = frame.getNodeData('line-number');
      script_id = frame.getNodeData('script-id');
      argument_id = frame.getNodeData('argument-count');
      scope_id = frame.getNodeData('variable-count');
      container.render(templates.frame(fn_name, line, runtime_id, script_id, argument_id, scope_id))
    }
  }

  var environment = {}

  /**** generic event listener ****/

  this['hello'] = function(xml)
  {
    var children = xml.documentElement.childNodes, child=null, i=0;
    for ( ; child = children[i]; i++)
    {
      environment[child.nodeName] = child.textContent;
    }
    document.getElementById('hello').render(templates.hello(environment));
    var config = storage.config_stop_at.get();
    var config_arr = [], prop = '';
    for ( prop in config )
    {
      config_arr[config_arr.length] = prop;
      config_arr[config_arr.length] = config[prop];
    }
    self.setConfiguration.apply(self, config_arr);
    document.getElementById('configuration').render(templates.configStopAt(config));
    document.getElementById('continues').render(templates.continues());
    helpers.setUpListeners();
    //helpers.verticalFrames.initFrames();
    //helpers.horizontalFrames.initFrames();
    //helpers.verticalFrames.setUpFrames()
    //self.getEvent();
  }

  this['new-script'] = function(xml)
  {

    var script = {};
    var children = xml.documentElement.childNodes, child=null, i=0;
    for ( ; child = children[i]; i++)
    {
      script[child.nodeName] = child.firstChild.nodeValue;
    }
    scripts[scripts.length] = script;
    addRuntime(script['runtime-id']);
    //proxy.POST("/" + service, "<break>"+script['runtime-id']+"</break>");
    //self.getEvent();
  }

  this['timeout'] = function()
  {
    //self.getEvent();
  }

  this['runtimes-reply'] = function(xml)
  {
    alert(88);
    var tag = xml.getNodeData('tag'), handler=null;
    if(tag && ( handler = tags[parseInt(tag)] ))
    {
      handler(xml);
    }
    else
    {
      throw "runtimes-reply, missing tag";
    }
    //self.getEvent();
  }
  /*

    <frame>

    <function-id>23</function-id>
    <argument-count>24</argument-count>
    <variable-count>25</variable-count>

    <source-position>
      <script-id>9</script-id>
      <line-number>5</line-number>
    </source-position>

    <object-value>
      <object-id>23</object-id>
      <object-attributes>
        <iscallable/>
        <isfunction/>
      </object-attributes>
      <function-name>foo</function-name>
    </object-value>

  </frame>

  */

  /*

  <thread-stopped-at>
  <runtime-id>2</runtime-id>
  <thread-id>8</thread-id>
  <script-id>10</script-id>
  <line-number>2</line-number>
  <stopped-reason>unknown</stopped-reason>
</thread-stopped-at>

<runtimes-reply>

CONTINUE ::= "<continue>"
                 RUNTIME-ID
                 THREAD-ID
                 MODE
               "</continue>" ;
RUNTIME-ID ::= "<runtime-id>" UNSIGNED "</runtime-id>" ;
THREAD-ID ::= "<thread-id>" UNSIGNED "</thread-id>" ;
MODE ::= "<mode>"
             ( "run" | "step-into-call" | "step-over-call" | "finish-call" )
           "</mode>" ;
*/

  var __stopAt = {}; // there can be only one stop at at the time

  var __stopAtId = 1;

  var getStopAtId = function()
  {
    return __stopAtId++;
  }

  this['thread-stopped-at'] = function(xml)
  {
    var stopAt = {};
    var id = getStopAtId();
    var children = xml.documentElement.childNodes, child=null, i=0;
    for ( ; child = children[i]; i++)
    {
      if(child.firstChild)
      {
        stopAt[child.nodeName] = child.firstChild.nodeValue;
      }
      else
      {
        opera.postError( "empty element in <thread-stopped-at> event");
        stopAt[child.nodeName] = null
      }
    }
    __stopAt[id] = stopAt;
    var line = parseInt( stopAt['line-number'] );
    if( typeof line == 'number' )
    {
      self.backtrace(stopAt);

      helpers.showLine( stopAt['script-id'], line );
      helpers.disableContinues(id, false);
    }
    else
    {
      throw 'not a line number: '+stopAt['line-number'];
    }
  }
/*

  'runtime-id'
  'script-id'
  'script-type'
  'script-data'
  'uri'

*/
  var scripts = [];

  this.getScripts=function(runtime_id)
  {
    var ret=[], script = null, i=0;
    for( ; script = scripts[i]; i++)
    {
      if(script['runtime-id'] == runtime_id)
      {
        ret[ret.length] = script;
      }
    }
    return ret;
  }

  this.getScript=function(script_id)
  {
    var script = null, i=0;
    for( ; script = scripts[i]; i++)
    {
      if(script['script-id'] == script_id)
      {
        return script;
      }
    }
    return null;
  }

  this.setup = function()
  {
    verticalFrames.init
    (
      document.body.getElementsByTagName('div')[0],
      function(){ return window.innerHeight }
    )
    action_handler.init();
    var host = location.host.split(':');
    proxy.onsetup = function()
    {
      if (!proxy.enable(service))
      {
        alert( "No service: " + service );
        return;
      }
      else
      {
        self.getEvent();
      }

    }
    proxy.configure(host[0], host[1]);
  }

  /**** commands ****/

  this.setConfiguration = function() // stopAt
  {
    var msg = "<set-configuration>", type='', bol='', i=0;
    for ( ; (type = arguments[i++]) && (bol=arguments[i]); i++ )
    {
      msg += "<stop-at>" +
          ( bol=='yes' ? "<yes/>" : "<no/>" ) +
          "<stop-type>"+type+"</stop-type>"+
        "</stop-at>";
    }
    msg += "</set-configuration>";
    proxy.POST("/" + service, msg);
  }

  this.getRuntime = function()
  {
    var msg = "<runtimes>";
    var tag = tagManager.setCB(this, parseRuntime);
    msg += "<tag>" + tag +"</tag>";
    var i=0, r_t=0;
    for ( ; r_t = arguments[i]; i++)
    {
      msg += "<runtime-id>" + r_t +"</runtime-id>";
    }
    msg += "</runtimes>";
    proxy.POST("/" + service, msg);
  }

  this.backtrace = function(stopAt)
  {
    var tag = tagManager.setCB(this, parseBacktrace, [stopAt['runtime-id']]);
    var msg = "<backtrace>";
    msg += "<tag>" + tag + "</tag>";
    msg += "<runtime-id>" + stopAt['runtime-id'] + "</runtime-id>";
    msg += "<thread-id>" + stopAt['thread-id'] + "</thread-id>";
    msg += "<maxframes>" + 100 + "</maxframes>";  // not sure what is correct here;
    msg += "</backtrace>";
    proxy.POST("/" + service, msg);
    //self.getEvent();
  }

  this.addBreakpoint = function(id, msg_how )
  {
    var msg = "<add-breakpoint>";
    msg += "<breakpoint-id>" + id + "</breakpoint-id>";
    msg += msg_how;
    msg += "</add-breakpoint>";
    proxy.POST("/" + service, msg);
  }

  var addBreakpointWithSourcePosition = function(script_id, line)
  {
    var msg = "<source-position>";
    msg += "<script-id>" + script_id + "</script-id>";
    msg += "<line-number>" + line + "</line-number>"
    msg += "</source-position>";
    return msg;
  }

  this.removeBreakpoint = function(id)
  {
    var msg = "<remove-breakpoint>";
    msg += "<breakpoint-id>" + id + "</breakpoint-id>";
    msg += "</remove-breakpoint>";
    proxy.POST("/" + service, msg);
  }

/*

  <thread-stopped-at>
  <runtime-id>2</runtime-id>
  <thread-id>8</thread-id>
  <script-id>10</script-id>
  <line-number>2</line-number>
  <stopped-reason>unknown</stopped-reason>
</thread-stopped-at>

CONTINUE ::= "<continue>"
                 RUNTIME-ID
                 THREAD-ID
                 MODE
               "</continue>" ;
RUNTIME-ID ::= "<runtime-id>" UNSIGNED "</runtime-id>" ;
THREAD-ID ::= "<thread-id>" UNSIGNED "</thread-id>" ;
MODE ::= "<mode>"
             ( "run" | "step-into-call" | "step-over-call" | "finish-call" )
           "</mode>" ;

*/

  this.__continue = function (stopAtId, mode)
  {
    var msg = "<continue>";
    msg += "<runtime-id>" + __stopAt[stopAtId]['runtime-id'] + "</runtime-id>";
    msg += "<thread-id>" + __stopAt[stopAtId]['thread-id'] + "</thread-id>";
    msg += "<mode>" + mode + "</mode>";
    msg += "</continue>";
    proxy.POST("/" + service, msg);
    //self.getEvent();
  }

  this.postCommandline = function(msg)
  {
    var msg = document.getElementById('command-line').getElementsByTagName('textarea')[0].value;
    proxy.POST("/" + service, msg);
  }

  var breakpoints = {};

  var __breakpointCounter = 1;

  var getBreakpointId = function()
  {
    return __breakpointCounter++;
  }

  var storeBreakpoint = function(script, line, id)
  {
    breakpoints[id] =
    {
      'script-id': script,
      'line': line
    }
    return id;
  }

  var clearBreakpoint = function(id)
  {
    delete breakpoints[id];
  }

  var getBreakpointsByScriptId = function(script_id)
  {
    var ret = [], cursor = null;
    for( cursor in breakpoints )
    {
      if ( breakpoints[cursor]['script-id'] == script_id )
      {
        ret[ret.length] = cursor;
      }
    }
    return ret;
  }

  var getBreakpointsByScriptIdAndLine = function(script_id, line)
  {
    var cursor = null, i=0;
    var b_p_ids = getBreakpointsByScriptId(script_id);
    for( ; cursor = b_p_ids[i]; i++ )
    {
      if ( breakpoints[cursor]['line'] == line )
      {
        return cursor;
      }
    }
    return null;
  }

  this.handleBreakpoint = function(script_id, line)
  {
    var b_p = getBreakpointsByScriptIdAndLine(script_id, line);
    if(b_p)
    {
      self.removeBreakpoint(b_p);
      clearBreakpoint(b_p);
      helpers.removeBreakpoint(b_p);
    }
    else
    {
      b_p = storeBreakpoint(script_id, line, getBreakpointId());
      self.addBreakpoint(b_p, addBreakpointWithSourcePosition(script_id, line));
      helpers.displayBreakpoint(line, b_p);
    }
  }

  /**** tags handling ****/

  var tags = {};
  var __tagCounter=0;

  var getTagId = function()
  {
    return __tagCounter++;
  }

  var setTagCB =function(tagId, cb)
  {
    tags[tagId] = cb;
  }

  var clearTagId = function(tagId)
  {
    delete tags[tagId];
  }

  //proxy.onReceive = this.getEvent;

}

onload = debugger.setup<commit_msg>updated the name for "argument-object" and "argument-object".<commit_after>var debugger = new function()
{
  var self = this;
  var service = "ecmascript-debugger";

  this.getEvent = function()
  {
    proxy.GET( "/" + service, genericEventListener );
  }

  var genericEventListener = function(xml)
  {
    if(xml)
    {
      if( tagManager.handleResponse(xml) )
      {
        //alert('handled by tag manager');
      }
      else if( self[xml.documentElement.nodeName] )
      {
        //alert('handled by else if');
        self[xml.documentElement.nodeName](xml)
      }
      else
      {
        debug.output('not implemented: '+new XMLSerializer().serializeToString(xml));
      }
      debug.formatXML(new XMLSerializer().serializeToString(xml));
    }
    self.getEvent();
  }

  var runtimes = {};

  var addRuntime = function(id)
  {
    if( !(id in runtimes) )
    {
      runtimes[id] = null;
      self.getRuntime(id);
    }
  }

  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;
    for ( ; r_t=r_ts[i]; i++)
    {
      runtimeId = r_t.getNodeData('runtime-id');
      if(runtimeId)
      {
        runtime={};
        children = r_t.childNodes;
        for(j=0 ; child = children[j]; j++)
        {
          runtime[child.nodeName] = child.textContent;
        }
        runtimes[runtimeId] = runtime;
        document.getElementById('runtime-ids').render(templates.runtimeId(runtime))
      }
    }
  }

  var parseBacktrace = function(xml, runtime_id)
  {

    var _frames = xml.getElementsByTagName('frame'), frame = null, i = 0;
    var fn_name = '', line = '', script_id = '', argument_id = '', scope_id = '';
    var container = document.getElementById('backtrace');
    container.innerHTML = '';
    for( ; frame  = _frames[i]; i++ )
    {
      fn_name = frame.getNodeData('function-name');
      line = frame.getNodeData('line-number');
      script_id = frame.getNodeData('script-id');
      argument_id = frame.getNodeData('argument-object');
      scope_id = frame.getNodeData('variable-object');
      container.render(templates.frame(fn_name, line, runtime_id, script_id, argument_id, scope_id))
    }
  }

  var environment = {}

  /**** generic event listener ****/

  this['hello'] = function(xml)
  {
    var children = xml.documentElement.childNodes, child=null, i=0;
    for ( ; child = children[i]; i++)
    {
      environment[child.nodeName] = child.textContent;
    }
    document.getElementById('hello').render(templates.hello(environment));
    var config = storage.config_stop_at.get();
    var config_arr = [], prop = '';
    for ( prop in config )
    {
      config_arr[config_arr.length] = prop;
      config_arr[config_arr.length] = config[prop];
    }
    self.setConfiguration.apply(self, config_arr);
    document.getElementById('configuration').render(templates.configStopAt(config));
    document.getElementById('continues').render(templates.continues());
    helpers.setUpListeners();
    //helpers.verticalFrames.initFrames();
    //helpers.horizontalFrames.initFrames();
    //helpers.verticalFrames.setUpFrames()
    //self.getEvent();
  }

  this['new-script'] = function(xml)
  {

    var script = {};
    var children = xml.documentElement.childNodes, child=null, i=0;
    for ( ; child = children[i]; i++)
    {
      script[child.nodeName] = child.firstChild.nodeValue;
    }
    scripts[scripts.length] = script;
    addRuntime(script['runtime-id']);
    //proxy.POST("/" + service, "<break>"+script['runtime-id']+"</break>");
    //self.getEvent();
  }

  this['timeout'] = function()
  {
    //self.getEvent();
  }

  this['runtimes-reply'] = function(xml)
  {
    alert(88);
    var tag = xml.getNodeData('tag'), handler=null;
    if(tag && ( handler = tags[parseInt(tag)] ))
    {
      handler(xml);
    }
    else
    {
      throw "runtimes-reply, missing tag";
    }
    //self.getEvent();
  }
  /*

    <frame>

    <function-id>23</function-id>
    <argument-count>24</argument-count>
    <variable-count>25</variable-count>

    <source-position>
      <script-id>9</script-id>
      <line-number>5</line-number>
    </source-position>

    <object-value>
      <object-id>23</object-id>
      <object-attributes>
        <iscallable/>
        <isfunction/>
      </object-attributes>
      <function-name>foo</function-name>
    </object-value>

  </frame>

  */

  /*

  <thread-stopped-at>
  <runtime-id>2</runtime-id>
  <thread-id>8</thread-id>
  <script-id>10</script-id>
  <line-number>2</line-number>
  <stopped-reason>unknown</stopped-reason>
</thread-stopped-at>

<runtimes-reply>

CONTINUE ::= "<continue>"
                 RUNTIME-ID
                 THREAD-ID
                 MODE
               "</continue>" ;
RUNTIME-ID ::= "<runtime-id>" UNSIGNED "</runtime-id>" ;
THREAD-ID ::= "<thread-id>" UNSIGNED "</thread-id>" ;
MODE ::= "<mode>"
             ( "run" | "step-into-call" | "step-over-call" | "finish-call" )
           "</mode>" ;
*/

  var __stopAt = {}; // there can be only one stop at at the time

  var __stopAtId = 1;

  var getStopAtId = function()
  {
    return __stopAtId++;
  }

  this['thread-stopped-at'] = function(xml)
  {
    var stopAt = {};
    var id = getStopAtId();
    var children = xml.documentElement.childNodes, child=null, i=0;
    for ( ; child = children[i]; i++)
    {
      if(child.firstChild)
      {
        stopAt[child.nodeName] = child.firstChild.nodeValue;
      }
      else
      {
        opera.postError( "empty element in <thread-stopped-at> event");
        stopAt[child.nodeName] = null
      }
    }
    __stopAt[id] = stopAt;
    var line = parseInt( stopAt['line-number'] );
    if( typeof line == 'number' )
    {
      self.backtrace(stopAt);

      helpers.showLine( stopAt['script-id'], line );
      helpers.disableContinues(id, false);
    }
    else
    {
      throw 'not a line number: '+stopAt['line-number'];
    }
  }
/*

  'runtime-id'
  'script-id'
  'script-type'
  'script-data'
  'uri'

*/
  var scripts = [];

  this.getScripts=function(runtime_id)
  {
    var ret=[], script = null, i=0;
    for( ; script = scripts[i]; i++)
    {
      if(script['runtime-id'] == runtime_id)
      {
        ret[ret.length] = script;
      }
    }
    return ret;
  }

  this.getScript=function(script_id)
  {
    var script = null, i=0;
    for( ; script = scripts[i]; i++)
    {
      if(script['script-id'] == script_id)
      {
        return script;
      }
    }
    return null;
  }

  this.setup = function()
  {
    verticalFrames.init
    (
      document.body.getElementsByTagName('div')[0],
      function(){ return window.innerHeight }
    )
    action_handler.init();
    var host = location.host.split(':');
    proxy.onsetup = function()
    {
      if (!proxy.enable(service))
      {
        alert( "No service: " + service );
        return;
      }
      else
      {
        self.getEvent();
      }

    }
    proxy.configure(host[0], host[1]);
  }

  /**** commands ****/

  this.setConfiguration = function() // stopAt
  {
    var msg = "<set-configuration>", type='', bol='', i=0;
    for ( ; (type = arguments[i++]) && (bol=arguments[i]); i++ )
    {
      msg += "<stop-at>" +
          ( bol=='yes' ? "<yes/>" : "<no/>" ) +
          "<stop-type>"+type+"</stop-type>"+
        "</stop-at>";
    }
    msg += "</set-configuration>";
    proxy.POST("/" + service, msg);
  }

  this.getRuntime = function()
  {
    var msg = "<runtimes>";
    var tag = tagManager.setCB(this, parseRuntime);
    msg += "<tag>" + tag +"</tag>";
    var i=0, r_t=0;
    for ( ; r_t = arguments[i]; i++)
    {
      msg += "<runtime-id>" + r_t +"</runtime-id>";
    }
    msg += "</runtimes>";
    proxy.POST("/" + service, msg);
  }

  this.backtrace = function(stopAt)
  {
    var tag = tagManager.setCB(this, parseBacktrace, [stopAt['runtime-id']]);
    var msg = "<backtrace>";
    msg += "<tag>" + tag + "</tag>";
    msg += "<runtime-id>" + stopAt['runtime-id'] + "</runtime-id>";
    msg += "<thread-id>" + stopAt['thread-id'] + "</thread-id>";
    msg += "<maxframes>" + 100 + "</maxframes>";  // not sure what is correct here;
    msg += "</backtrace>";
    proxy.POST("/" + service, msg);
    //self.getEvent();
  }

  this.addBreakpoint = function(id, msg_how )
  {
    var msg = "<add-breakpoint>";
    msg += "<breakpoint-id>" + id + "</breakpoint-id>";
    msg += msg_how;
    msg += "</add-breakpoint>";
    proxy.POST("/" + service, msg);
  }

  var addBreakpointWithSourcePosition = function(script_id, line)
  {
    var msg = "<source-position>";
    msg += "<script-id>" + script_id + "</script-id>";
    msg += "<line-number>" + line + "</line-number>"
    msg += "</source-position>";
    return msg;
  }

  this.removeBreakpoint = function(id)
  {
    var msg = "<remove-breakpoint>";
    msg += "<breakpoint-id>" + id + "</breakpoint-id>";
    msg += "</remove-breakpoint>";
    proxy.POST("/" + service, msg);
  }

/*

  <thread-stopped-at>
  <runtime-id>2</runtime-id>
  <thread-id>8</thread-id>
  <script-id>10</script-id>
  <line-number>2</line-number>
  <stopped-reason>unknown</stopped-reason>
</thread-stopped-at>

CONTINUE ::= "<continue>"
                 RUNTIME-ID
                 THREAD-ID
                 MODE
               "</continue>" ;
RUNTIME-ID ::= "<runtime-id>" UNSIGNED "</runtime-id>" ;
THREAD-ID ::= "<thread-id>" UNSIGNED "</thread-id>" ;
MODE ::= "<mode>"
             ( "run" | "step-into-call" | "step-over-call" | "finish-call" )
           "</mode>" ;

*/

  this.__continue = function (stopAtId, mode)
  {
    var msg = "<continue>";
    msg += "<runtime-id>" + __stopAt[stopAtId]['runtime-id'] + "</runtime-id>";
    msg += "<thread-id>" + __stopAt[stopAtId]['thread-id'] + "</thread-id>";
    msg += "<mode>" + mode + "</mode>";
    msg += "</continue>";
    proxy.POST("/" + service, msg);
    //self.getEvent();
  }

  this.postCommandline = function(msg)
  {
    var msg = document.getElementById('command-line').getElementsByTagName('textarea')[0].value;
    proxy.POST("/" + service, msg);
  }

  var breakpoints = {};

  var __breakpointCounter = 1;

  var getBreakpointId = function()
  {
    return __breakpointCounter++;
  }

  var storeBreakpoint = function(script, line, id)
  {
    breakpoints[id] =
    {
      'script-id': script,
      'line': line
    }
    return id;
  }

  var clearBreakpoint = function(id)
  {
    delete breakpoints[id];
  }

  var getBreakpointsByScriptId = function(script_id)
  {
    var ret = [], cursor = null;
    for( cursor in breakpoints )
    {
      if ( breakpoints[cursor]['script-id'] == script_id )
      {
        ret[ret.length] = cursor;
      }
    }
    return ret;
  }

  var getBreakpointsByScriptIdAndLine = function(script_id, line)
  {
    var cursor = null, i=0;
    var b_p_ids = getBreakpointsByScriptId(script_id);
    for( ; cursor = b_p_ids[i]; i++ )
    {
      if ( breakpoints[cursor]['line'] == line )
      {
        return cursor;
      }
    }
    return null;
  }

  this.handleBreakpoint = function(script_id, line)
  {
    var b_p = getBreakpointsByScriptIdAndLine(script_id, line);
    if(b_p)
    {
      self.removeBreakpoint(b_p);
      clearBreakpoint(b_p);
      helpers.removeBreakpoint(b_p);
    }
    else
    {
      b_p = storeBreakpoint(script_id, line, getBreakpointId());
      self.addBreakpoint(b_p, addBreakpointWithSourcePosition(script_id, line));
      helpers.displayBreakpoint(line, b_p);
    }
  }

  /**** tags handling ****/

  var tags = {};
  var __tagCounter=0;

  var getTagId = function()
  {
    return __tagCounter++;
  }

  var setTagCB =function(tagId, cb)
  {
    tags[tagId] = cb;
  }

  var clearTagId = function(tagId)
  {
    delete tags[tagId];
  }

  //proxy.onReceive = this.getEvent;

}

onload = debugger.setup<|endoftext|>


<commit_before>'use strict';

function debounce(func, wait, immediate) {
  var timeout;
  return function() {
    var context = this;
    var args = arguments;
    var later = function() {
      timeout = null;
      if (!immediate) {
        func.apply(context, args);
      }
    };
    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) {
      func.apply(context, args);
    }
  };
}

chrome.omnibox.onInputEntered.addListener(function(text) {
  var url = 'http://everyone.khresmoi.eu/hon-search';
  if (text) {
    url += '?start=0&fq=docType:html&group.field=domain' +
      '&overrideQ=&searchLanguage=en&q=' + encodeURIComponent(text);
  }
  chrome.tabs.getSelected(null, function(tab) {
    chrome.tabs.update(tab.id, {url: url});
  });
});

chrome.webRequest.onCompleted.addListener(debounce(function(details) {
  chrome.tabs.executeScript(
    details.tabId, {
      file: 'bower_components/jquery/dist/jquery.min.js',
      allFrames: true,
    }
  );
  chrome.tabs.executeScript(
    details.tabId, {
      file: 'scripts/utils/tld.js',
      allFrames: true,
    }
  );
  chrome.tabs.executeScript(
    details.tabId, {
      file: 'scripts/kconnect.js',
      allFrames: true,
    }
  );
  chrome.tabs.executeScript(details.tabId, {
    file: 'scripts/contentscript.js',
    allFrames: true,
  });
}, 1000), {
  urls: [
    '*://*.google.com/*',
    '*://*.google.ac/*',
    '*://*.google.ad/*',
    '*://*.google.ae/*',
    '*://*.google.com.af/*',
    '*://*.google.com.ag/*',
    '*://*.google.com.ai/*',
    '*://*.google.al/*',
    '*://*.google.am/*',
    '*://*.google.co.ao/*',
    '*://*.google.com.ar/*',
    '*://*.google.as/*',
    '*://*.google.at/*',
    '*://*.google.com/au/*',
    '*://*.google.az/*',
    '*://*.google.ba/*',
    '*://*.google.com.bd/*',
    '*://*.google.be/*',
    '*://*.google.bf/*',
    '*://*.google.bg/*',
    '*://*.google.com.bh/*',
    '*://*.google.bi/*',
    '*://*.google.bj/*',
    '*://*.google.com.bn/*',
    '*://*.google.com.bo/*',
    '*://*.google.bs/*',
    '*://*.google.bt/*',
    '*://*.google.co.bw/*',
    '*://*.google.by/*',
    '*://*.google.com.bz/*',
    '*://*.google.ca/*',
    '*://*.google.com.kh/*',
    '*://*.google.cc/*',
    '*://*.google.cd/*',
    '*://*.google.cf/*',
    '*://*.google.cat/*',
    '*://*.google.cg/*',
    '*://*.google.ch/*',
    '*://*.google.ci/*',
    '*://*.google.co.ck/*',
    '*://*.google.cl/*',
    '*://*.google.cm/*',
    '*://*.google.cn/*',
    '*://*.google.com.co/*',
    '*://*.google.co.cr/*',
    '*://*.google.com.cu/*',
    '*://*.google.cv/*',
    '*://*.google.com.cy/*',
    '*://*.google.cz/*',
    '*://*.google.de/*',
    '*://*.google.dj/*',
    '*://*.google.dk/*',
    '*://*.google.dm/*',
    '*://*.google.com.do/*',
    '*://*.google.dz/*',
    '*://*.google.com.ec/*',
    '*://*.google.ee/*',
    '*://*.google.com.eg/*',
    '*://*.google.es/*',
    '*://*.google.com.et/*',
    '*://*.google.fi/*',
    '*://*.google.fj/*',
    '*://*.google.fm/*',
    '*://*.google.fr/*',
    '*://*.google.ga/*',
    '*://*.google.ge/*',
    '*://*.google.gf/*',
    '*://*.google.gg/*',
    '*://*.google.com.gh/*',
    '*://*.google.com.gi/*',
    '*://*.google.gl/*',
    '*://*.google.gm/*',
    '*://*.google.gp/*',
    '*://*.google.gr/*',
    '*://*.google.com.gt/*',
    '*://*.google.gy/*',
    '*://*.google.com.hk/*',
    '*://*.google.hn/*',
    '*://*.google.hr/*',
    '*://*.google.ht/*',
    '*://*.google.hu/*',
    '*://*.google.co.id/*',
    '*://*.google.im/*',
    '*://*.google.co.in/*',
    '*://*.google.io/*',
    '*://*.google.is/*',
    '*://*.google.it/*',
    '*://*.google.je/*',
    '*://*.google.com.jm/*',
    '*://*.google.jo/*',
    '*://*.google.co.jp/*',
    '*://*.google.co.ke/*',
    '*://*.google.ki/*',
    '*://*.google.kg/*',
    '*://*.google.co.kr/*',
    '*://*.google.com.kw/*',
    '*://*.google.kz/*',
    '*://*.google.la/*',
    '*://*.google.com.lb/*',
    '*://*.google.com.lc/*',
    '*://*.google.li/*',
    '*://*.google.lk/*',
    '*://*.google.co.ls/*',
    '*://*.google.lt/*',
    '*://*.google.lu/*',
    '*://*.google.lv/*',
    '*://*.google.com.ly/*',
    '*://*.google.co.ma/*',
    '*://*.google.md/*',
    '*://*.google.me/*',
    '*://*.google.mg/*',
    '*://*.google.mk/*',
    '*://*.google.ml/*',
    '*://*.google.com.mm/*',
    '*://*.google.mn/*',
    '*://*.google.ms/*',
    '*://*.google.com.mt/*',
    '*://*.google.mu/*',
    '*://*.google.mv/*',
    '*://*.google.mw/*',
    '*://*.google.com.mx/*',
    '*://*.google.com.my/*',
    '*://*.google.co.mz/*',
    '*://*.google.com.na/*',
    '*://*.google.ne/*',
    '*://*.google.nf/*',
    '*://*.google.ng/*',
    '*://*.google.com.ni/*',
    '*://*.google.nl/*',
    '*://*.google.no/*',
    '*://*.google.com.np/*',
    '*://*.google.nr/*',
    '*://*.google.nu/*',
    '*://*.google.co.nz/*',
    '*://*.google.com.om/*',
    '*://*.google.com.pk/*',
    '*://*.google.com.pa/*',
    '*://*.google.com.pe/*',
    '*://*.google.com.ph/*',
    '*://*.google.pl/*',
    '*://*.google.com.pg/*',
    '*://*.google.pn/*',
    '*://*.google.com.pr/*',
    '*://*.google.ps/*',
    '*://*.google.pt/*',
    '*://*.google.com.py/*',
    '*://*.google.com.qa/*',
    '*://*.google.ro/*',
    '*://*.google.rs/*',
    '*://*.google.ru/*',
    '*://*.google.rw/*',
    '*://*.google.com.sa/*',
    '*://*.google.com.sb/*',
    '*://*.google.sc/*',
    '*://*.google.se/*',
    '*://*.google.com.sg/*',
    '*://*.google.sh/*',
    '*://*.google.si/*',
    '*://*.google.sk/*',
    '*://*.google.com.sl/*',
    '*://*.google.sn/*',
    '*://*.google.sm/*',
    '*://*.google.so/*',
    '*://*.google.st/*',
    '*://*.google.sr/*',
    '*://*.google.com.sv/*',
    '*://*.google.td/*',
    '*://*.google.tg/*',
    '*://*.google.co.th/*',
    '*://*.google.com.tj/*',
    '*://*.google.tk/*',
    '*://*.google.tl/*',
    '*://*.google.tm/*',
    '*://*.google.to/*',
    '*://*.google.tn/*',
    '*://*.google.com.tr/*',
    '*://*.google.tt/*',
    '*://*.google.com.tw/*',
    '*://*.google.co.tz/*',
    '*://*.google.com.ua/*',
    '*://*.google.co.ug/*',
    '*://*.google.co.uk/*',
    '*://*.google.us/*',
    '*://*.google.com.uy/*',
    '*://*.google.co.uz/*',
    '*://*.google.com.vc/*',
    '*://*.google.co.ve/*',
    '*://*.google.vg/*',
    '*://*.google.co.vi/*',
    '*://*.google.com.vn/*',
    '*://*.google.vu/*',
    '*://*.google.ws/*',
    '*://*.google.co.za/*',
    '*://*.google.co.zm/*',
    '*://*.google.co.zw/*',
    '*://*.bing.com/*',
    '*://*.search.yahoo.com/*',
  ],
  types: ['xmlhttprequest'],
});
<commit_msg>omnibox test<commit_after>'use strict';

function debounce(func, wait, immediate) {
  var timeout;
  return function() {
    var context = this;
    var args = arguments;
    var later = function() {
      timeout = null;
      if (!immediate) {
        func.apply(context, args);
      }
    };
    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) {
      func.apply(context, args);
    }
  };
}

if (chrome.omnibox) {
  chrome.omnibox.onInputEntered.addListener(function (text) {
    var url = 'http://everyone.khresmoi.eu/hon-search';
    if (text) {
      url += '?start=0&fq=docType:html&group.field=domain' +
      '&overrideQ=&searchLanguage=en&q=' + encodeURIComponent(text);
    }
    chrome.tabs.getSelected(null, function (tab) {
      chrome.tabs.update(tab.id, {url: url});
    });
  });
}

chrome.webRequest.onCompleted.addListener(debounce(function(details) {
  chrome.tabs.executeScript(
    details.tabId, {
      file: 'bower_components/jquery/dist/jquery.min.js',
      allFrames: true,
    }
  );
  chrome.tabs.executeScript(
    details.tabId, {
      file: 'scripts/utils/tld.js',
      allFrames: true,
    }
  );
  chrome.tabs.executeScript(
    details.tabId, {
      file: 'scripts/kconnect.js',
      allFrames: true,
    }
  );
  chrome.tabs.executeScript(details.tabId, {
    file: 'scripts/contentscript.js',
    allFrames: true,
  });
}, 1000), {
  urls: [
    '*://*.google.com/*',
    '*://*.google.ac/*',
    '*://*.google.ad/*',
    '*://*.google.ae/*',
    '*://*.google.com.af/*',
    '*://*.google.com.ag/*',
    '*://*.google.com.ai/*',
    '*://*.google.al/*',
    '*://*.google.am/*',
    '*://*.google.co.ao/*',
    '*://*.google.com.ar/*',
    '*://*.google.as/*',
    '*://*.google.at/*',
    '*://*.google.com/au/*',
    '*://*.google.az/*',
    '*://*.google.ba/*',
    '*://*.google.com.bd/*',
    '*://*.google.be/*',
    '*://*.google.bf/*',
    '*://*.google.bg/*',
    '*://*.google.com.bh/*',
    '*://*.google.bi/*',
    '*://*.google.bj/*',
    '*://*.google.com.bn/*',
    '*://*.google.com.bo/*',
    '*://*.google.bs/*',
    '*://*.google.bt/*',
    '*://*.google.co.bw/*',
    '*://*.google.by/*',
    '*://*.google.com.bz/*',
    '*://*.google.ca/*',
    '*://*.google.com.kh/*',
    '*://*.google.cc/*',
    '*://*.google.cd/*',
    '*://*.google.cf/*',
    '*://*.google.cat/*',
    '*://*.google.cg/*',
    '*://*.google.ch/*',
    '*://*.google.ci/*',
    '*://*.google.co.ck/*',
    '*://*.google.cl/*',
    '*://*.google.cm/*',
    '*://*.google.cn/*',
    '*://*.google.com.co/*',
    '*://*.google.co.cr/*',
    '*://*.google.com.cu/*',
    '*://*.google.cv/*',
    '*://*.google.com.cy/*',
    '*://*.google.cz/*',
    '*://*.google.de/*',
    '*://*.google.dj/*',
    '*://*.google.dk/*',
    '*://*.google.dm/*',
    '*://*.google.com.do/*',
    '*://*.google.dz/*',
    '*://*.google.com.ec/*',
    '*://*.google.ee/*',
    '*://*.google.com.eg/*',
    '*://*.google.es/*',
    '*://*.google.com.et/*',
    '*://*.google.fi/*',
    '*://*.google.fj/*',
    '*://*.google.fm/*',
    '*://*.google.fr/*',
    '*://*.google.ga/*',
    '*://*.google.ge/*',
    '*://*.google.gf/*',
    '*://*.google.gg/*',
    '*://*.google.com.gh/*',
    '*://*.google.com.gi/*',
    '*://*.google.gl/*',
    '*://*.google.gm/*',
    '*://*.google.gp/*',
    '*://*.google.gr/*',
    '*://*.google.com.gt/*',
    '*://*.google.gy/*',
    '*://*.google.com.hk/*',
    '*://*.google.hn/*',
    '*://*.google.hr/*',
    '*://*.google.ht/*',
    '*://*.google.hu/*',
    '*://*.google.co.id/*',
    '*://*.google.im/*',
    '*://*.google.co.in/*',
    '*://*.google.io/*',
    '*://*.google.is/*',
    '*://*.google.it/*',
    '*://*.google.je/*',
    '*://*.google.com.jm/*',
    '*://*.google.jo/*',
    '*://*.google.co.jp/*',
    '*://*.google.co.ke/*',
    '*://*.google.ki/*',
    '*://*.google.kg/*',
    '*://*.google.co.kr/*',
    '*://*.google.com.kw/*',
    '*://*.google.kz/*',
    '*://*.google.la/*',
    '*://*.google.com.lb/*',
    '*://*.google.com.lc/*',
    '*://*.google.li/*',
    '*://*.google.lk/*',
    '*://*.google.co.ls/*',
    '*://*.google.lt/*',
    '*://*.google.lu/*',
    '*://*.google.lv/*',
    '*://*.google.com.ly/*',
    '*://*.google.co.ma/*',
    '*://*.google.md/*',
    '*://*.google.me/*',
    '*://*.google.mg/*',
    '*://*.google.mk/*',
    '*://*.google.ml/*',
    '*://*.google.com.mm/*',
    '*://*.google.mn/*',
    '*://*.google.ms/*',
    '*://*.google.com.mt/*',
    '*://*.google.mu/*',
    '*://*.google.mv/*',
    '*://*.google.mw/*',
    '*://*.google.com.mx/*',
    '*://*.google.com.my/*',
    '*://*.google.co.mz/*',
    '*://*.google.com.na/*',
    '*://*.google.ne/*',
    '*://*.google.nf/*',
    '*://*.google.ng/*',
    '*://*.google.com.ni/*',
    '*://*.google.nl/*',
    '*://*.google.no/*',
    '*://*.google.com.np/*',
    '*://*.google.nr/*',
    '*://*.google.nu/*',
    '*://*.google.co.nz/*',
    '*://*.google.com.om/*',
    '*://*.google.com.pk/*',
    '*://*.google.com.pa/*',
    '*://*.google.com.pe/*',
    '*://*.google.com.ph/*',
    '*://*.google.pl/*',
    '*://*.google.com.pg/*',
    '*://*.google.pn/*',
    '*://*.google.com.pr/*',
    '*://*.google.ps/*',
    '*://*.google.pt/*',
    '*://*.google.com.py/*',
    '*://*.google.com.qa/*',
    '*://*.google.ro/*',
    '*://*.google.rs/*',
    '*://*.google.ru/*',
    '*://*.google.rw/*',
    '*://*.google.com.sa/*',
    '*://*.google.com.sb/*',
    '*://*.google.sc/*',
    '*://*.google.se/*',
    '*://*.google.com.sg/*',
    '*://*.google.sh/*',
    '*://*.google.si/*',
    '*://*.google.sk/*',
    '*://*.google.com.sl/*',
    '*://*.google.sn/*',
    '*://*.google.sm/*',
    '*://*.google.so/*',
    '*://*.google.st/*',
    '*://*.google.sr/*',
    '*://*.google.com.sv/*',
    '*://*.google.td/*',
    '*://*.google.tg/*',
    '*://*.google.co.th/*',
    '*://*.google.com.tj/*',
    '*://*.google.tk/*',
    '*://*.google.tl/*',
    '*://*.google.tm/*',
    '*://*.google.to/*',
    '*://*.google.tn/*',
    '*://*.google.com.tr/*',
    '*://*.google.tt/*',
    '*://*.google.com.tw/*',
    '*://*.google.co.tz/*',
    '*://*.google.com.ua/*',
    '*://*.google.co.ug/*',
    '*://*.google.co.uk/*',
    '*://*.google.us/*',
    '*://*.google.com.uy/*',
    '*://*.google.co.uz/*',
    '*://*.google.com.vc/*',
    '*://*.google.co.ve/*',
    '*://*.google.vg/*',
    '*://*.google.co.vi/*',
    '*://*.google.com.vn/*',
    '*://*.google.vu/*',
    '*://*.google.ws/*',
    '*://*.google.co.za/*',
    '*://*.google.co.zm/*',
    '*://*.google.co.zw/*',
    '*://*.bing.com/*',
    '*://*.search.yahoo.com/*',
  ],
  types: ['xmlhttprequest'],
});
<|endoftext|>


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

    angular.module('scaleApp').controller('aisJobLoadController', function ($scope, scaleConfig, scaleService, loadService) {
        var chart = null,
            colArr = [],
            xArr = [],
            pendingArr = [],
            queuedArr = [],
            runningArr = [],
            removeIds = [],
            legendHide = [];

        $scope.filterValue = 1;
        $scope.filterDuration = 'w';
        $scope.filterDurations = ['M', 'w', 'd'];
        $scope.zoomEnabled = false;
        $scope.zoomClass = 'btn-default';
        $scope.zoomText = 'Enable Zoom';
        $scope.jobLoadData = {};
        $scope.loadingJobLoad = true;
        $scope.jobLoadError = null;
        $scope.jobLoadErrorStatus = null;
        $scope.total = 0;
        $scope.chartStyle = '';

        var jobLoadParams = {
            started: moment.utc().subtract($scope.filterValue, $scope.filterDuration).startOf('d').toDate(), ended: moment.utc().endOf('d').toDate(), job_type_id: null, job_type_name: null, job_type_category: null, url: null
        };

        $scope.toggleZoom = function () {
            $scope.zoomEnabled = !$scope.zoomEnabled;
            chart.zoom.enable($scope.zoomEnabled);
            if ($scope.zoomEnabled) {
                $scope.zoomClass = 'btn-primary';
                $scope.zoomText = 'Disable Zoom';
            } else {
                $scope.zoomClass = 'btn-default';
                $scope.zoomText = 'Enable Zoom';
            }
        };

        var initChart = function () {
            colArr = [];
            xArr = [];
            pendingArr = [];
            queuedArr = [];
            runningArr = [];

            /*
            // x axis values
            var numHours = moment.utc(jobLoadParams.ended).diff(moment.utc(jobLoadParams.started), 'h');
            for (var i = 0; i < numHours; i++) {
                xArr.push(moment.utc(jobLoadParams.started).add(i, 'h').startOf('h').toDate());
            }

            // data values
            _.forEach(xArr, function (xDate) {
                var dataObj = _.find($scope.jobLoadData.results, function (d) {
                    return moment.utc(d.time).startOf('h').isSame(xDate, 'hour');
                });
                // push 0 if data for xDate is not present in queryDates
                pendingArr.push(dataObj ? dataObj.pending_count : 0);
                queuedArr.push(dataObj ? dataObj.queued_count : 0);
                runningArr.push(dataObj ? dataObj.running_count : 0);
            });

            xArr.unshift('x');
            pendingArr.unshift('Pending');
            queuedArr.unshift('Queued');
            runningArr.unshift('Running');
            */

            xArr = _.pluck($scope.jobLoadData.results, 'time');
            _.forEach(xArr, function (d, i) {
                xArr[i] = moment.utc(d).toDate();
            });
            xArr.unshift('x');

            var pendingArr = _.pluck($scope.jobLoadData.results, 'pending_count'),
                queuedArr = _.pluck($scope.jobLoadData.results, 'queued_count'),
                runningArr = _.pluck($scope.jobLoadData.results, 'running_count');

            pendingArr.unshift('Pending');
            queuedArr.unshift('Queued');
            runningArr.unshift('Running');

            // add to colArr
            colArr = [xArr, pendingArr, queuedArr, runningArr];

            var types = {},
                type = {},
                groups = [];

            _.forEach(colArr, function(col){
                    type = {};
                    if (col[0] !== 'x') {
                        type[col[0]] = 'area';
                        groups.push(col[0]);
                    }
                angular.extend(types, type);
            });

            //if (chart) {
                /*
                chart.groups([groups]);
                chart.load({
                    columns: colArr,
                    types: types,
                });
                */
                /*
                chart.flow({
                    columns: colArr
                });
                */
            //} else {
            if (chart) {
                chart.flush();
            }
                // chart config
                chart = c3.generate({
                    bindto: '#job-load',
                    data: {
                        x: 'x',
                        columns: colArr,
                        types: types,
                        groups: [groups],
                        colors: {
                            Pending: scaleConfig.colors.chart_pink,
                            Queued: scaleConfig.colors.chart_purple,
                            Running: scaleConfig.colors.chart_blue
                        }
                    },
                    transition: {
                        duration: 700
                    },
                    tooltip: {
                        format: {
                            title: function (x) {
                                return moment.utc(x).startOf('h').format(scaleConfig.dateFormats.day_second);
                            }
                        }
                    },
                    axis: {
                        x: {
                            type: 'timeseries',
                            tick: {
                                format: function (d) {
                                    return moment.utc(d).format(scaleConfig.dateFormats.day);
                                }
                            }
                        }
                    }
                });
            //}
            $scope.loadingJobLoad = false;
        };

        var getJobLoad = function (showPageLoad) {
            if (showPageLoad) {
                $scope.$parent.loading = true;
            } else {
                $scope.loadingJobLoad = true;
            }
            jobLoadParams.started = moment.utc().subtract($scope.filterValue, $scope.filterDuration).startOf('d').toDate();
            jobLoadParams.ended = moment.utc(jobLoadParams.started).add(1, $scope.filterDuration).endOf('d').toDate();
            jobLoadParams.page_size = 1000;

            loadService.getJobLoad(jobLoadParams).then(null, null, function (result) {
                if (result.$resolved) {
                    $scope.jobLoadData = result;
                    initChart();
                } else {
                    if (result.statusText && result.statusText !== '') {
                        $scope.jobLoadErrorStatus = result.statusText;
                    }
                    $scope.jobLoadError = 'Unable to retrieve job load.';
                }
                if (showPageLoad) {
                    $scope.$parent.loading = false;
                } else {
                    $scope.loadingJobLoad = false;
                }
            });
        };

        $scope.updateJobLoadRange = function (action) {
            if (action === 'older') {
                $scope.filterValue++;
            } else if (action === 'newer') {
                if ($scope.filterValue > 1) {
                    $scope.filterValue--;
                }
            } else if (action === 'today') {
                $scope.filterValue = 1;
            }
            getJobLoad(true);
        };

        $scope.$watch('filterValue', function (value) {
            var $jobLoadNewer = $('.job-load-newer'),
                $jobLoadToday = $('.job-load-today');

            if (value > 1) {
                $jobLoadNewer.removeAttr('disabled');
                $jobLoadToday.removeAttr('disabled');
            } else {
                $jobLoadNewer.attr('disabled', 'disabled');
                $jobLoadToday.attr('disabled', 'disabled');
            }
        });

        getJobLoad();

        if ($scope.autoHeight) {
            // set chart height
            angular.element(document).ready(function () {
                // set container heights equal to available page height
                var viewport = scaleService.getViewportSize(),
                    offset = scaleConfig.headerOffset,
                    headerOffset = $('.job-load-header').height(),
                    legendOffset = $('.job-load-legend-label').height(),
                    filterOffset = $('.job-load-filter').height(),
                    chartMaxHeight = viewport.height - offset - headerOffset - legendOffset - filterOffset - 5;

                $scope.chartStyle = 'height: ' + chartMaxHeight + 'px; max-height: ' + chartMaxHeight + 'px;';
            });
        }
    });
})();
<commit_msg>Fix height issue with job load chart<commit_after>(function () {
    'use strict';

    angular.module('scaleApp').controller('aisJobLoadController', function ($scope, scaleConfig, scaleService, loadService) {
        var chart = null,
            colArr = [],
            xArr = [],
            pendingArr = [],
            queuedArr = [],
            runningArr = [],
            removeIds = [],
            legendHide = [];

        $scope.filterValue = 1;
        $scope.filterDuration = 'w';
        $scope.filterDurations = ['M', 'w', 'd'];
        $scope.zoomEnabled = false;
        $scope.zoomClass = 'btn-default';
        $scope.zoomText = 'Enable Zoom';
        $scope.jobLoadData = {};
        $scope.loadingJobLoad = true;
        $scope.jobLoadError = null;
        $scope.jobLoadErrorStatus = null;
        $scope.total = 0;
        $scope.chartStyle = '';

        var jobLoadParams = {
            started: moment.utc().subtract($scope.filterValue, $scope.filterDuration).startOf('d').toDate(), ended: moment.utc().endOf('d').toDate(), job_type_id: null, job_type_name: null, job_type_category: null, url: null
        };

        $scope.toggleZoom = function () {
            $scope.zoomEnabled = !$scope.zoomEnabled;
            chart.zoom.enable($scope.zoomEnabled);
            if ($scope.zoomEnabled) {
                $scope.zoomClass = 'btn-primary';
                $scope.zoomText = 'Disable Zoom';
            } else {
                $scope.zoomClass = 'btn-default';
                $scope.zoomText = 'Enable Zoom';
            }
        };

        var initChart = function () {
            colArr = [];
            xArr = [];
            pendingArr = [];
            queuedArr = [];
            runningArr = [];

            /*
            // x axis values
            var numHours = moment.utc(jobLoadParams.ended).diff(moment.utc(jobLoadParams.started), 'h');
            for (var i = 0; i < numHours; i++) {
                xArr.push(moment.utc(jobLoadParams.started).add(i, 'h').startOf('h').toDate());
            }

            // data values
            _.forEach(xArr, function (xDate) {
                var dataObj = _.find($scope.jobLoadData.results, function (d) {
                    return moment.utc(d.time).startOf('h').isSame(xDate, 'hour');
                });
                // push 0 if data for xDate is not present in queryDates
                pendingArr.push(dataObj ? dataObj.pending_count : 0);
                queuedArr.push(dataObj ? dataObj.queued_count : 0);
                runningArr.push(dataObj ? dataObj.running_count : 0);
            });

            xArr.unshift('x');
            pendingArr.unshift('Pending');
            queuedArr.unshift('Queued');
            runningArr.unshift('Running');
            */

            xArr = _.pluck($scope.jobLoadData.results, 'time');
            _.forEach(xArr, function (d, i) {
                xArr[i] = moment.utc(d).toDate();
            });
            xArr.unshift('x');

            var pendingArr = _.pluck($scope.jobLoadData.results, 'pending_count'),
                queuedArr = _.pluck($scope.jobLoadData.results, 'queued_count'),
                runningArr = _.pluck($scope.jobLoadData.results, 'running_count');

            pendingArr.unshift('Pending');
            queuedArr.unshift('Queued');
            runningArr.unshift('Running');

            // add to colArr
            colArr = [xArr, pendingArr, queuedArr, runningArr];

            var types = {},
                type = {},
                groups = [];

            _.forEach(colArr, function(col){
                    type = {};
                    if (col[0] !== 'x') {
                        type[col[0]] = 'area';
                        groups.push(col[0]);
                    }
                angular.extend(types, type);
            });

            //if (chart) {
                /*
                chart.groups([groups]);
                chart.load({
                    columns: colArr,
                    types: types,
                });
                */
                /*
                chart.flow({
                    columns: colArr
                });
                */
            //} else {
            if (chart) {
                chart.flush();
            }
                // chart config
                chart = c3.generate({
                    bindto: '#job-load',
                    data: {
                        x: 'x',
                        columns: colArr,
                        types: types,
                        groups: [groups],
                        colors: {
                            Pending: scaleConfig.colors.chart_pink,
                            Queued: scaleConfig.colors.chart_purple,
                            Running: scaleConfig.colors.chart_blue
                        }
                    },
                    transition: {
                        duration: 700
                    },
                    tooltip: {
                        format: {
                            title: function (x) {
                                return moment.utc(x).startOf('h').format(scaleConfig.dateFormats.day_second);
                            }
                        }
                    },
                    axis: {
                        x: {
                            type: 'timeseries',
                            tick: {
                                format: function (d) {
                                    return moment.utc(d).format(scaleConfig.dateFormats.day);
                                }
                            }
                        }
                    }
                });
            //}
            $scope.loadingJobLoad = false;
        };

        var getJobLoad = function (showPageLoad) {
            if (showPageLoad) {
                $scope.$parent.loading = true;
            } else {
                $scope.loadingJobLoad = true;
            }
            jobLoadParams.started = moment.utc().subtract($scope.filterValue, $scope.filterDuration).startOf('d').toDate();
            jobLoadParams.ended = moment.utc(jobLoadParams.started).add(1, $scope.filterDuration).endOf('d').toDate();
            jobLoadParams.page_size = 1000;

            loadService.getJobLoad(jobLoadParams).then(null, null, function (result) {
                if (result.$resolved) {
                    $scope.jobLoadData = result;
                    initChart();
                } else {
                    if (result.statusText && result.statusText !== '') {
                        $scope.jobLoadErrorStatus = result.statusText;
                    }
                    $scope.jobLoadError = 'Unable to retrieve job load.';
                }
                if (showPageLoad) {
                    $scope.$parent.loading = false;
                } else {
                    $scope.loadingJobLoad = false;
                }
            });
        };

        $scope.updateJobLoadRange = function (action) {
            if (action === 'older') {
                $scope.filterValue++;
            } else if (action === 'newer') {
                if ($scope.filterValue > 1) {
                    $scope.filterValue--;
                }
            } else if (action === 'today') {
                $scope.filterValue = 1;
            }
            getJobLoad(true);
        };

        $scope.$watch('filterValue', function (value) {
            var $jobLoadNewer = $('.job-load-newer'),
                $jobLoadToday = $('.job-load-today');

            if (value > 1) {
                $jobLoadNewer.removeAttr('disabled');
                $jobLoadToday.removeAttr('disabled');
            } else {
                $jobLoadNewer.attr('disabled', 'disabled');
                $jobLoadToday.attr('disabled', 'disabled');
            }
        });

        if ($scope.autoHeight) {
            // set chart height
            angular.element(document).ready(function () {
                // set container heights equal to available page height
                var viewport = scaleService.getViewportSize(),
                    offset = scaleConfig.headerOffset,
                    headerOffset = $('.job-load-header').height(),
                    legendOffset = $('.job-load-legend-label').height(),
                    filterOffset = $('.job-load-filter').outerHeight(true),
                    chartMaxHeight = viewport.height - offset - headerOffset - legendOffset - filterOffset - 5;

                $scope.chartStyle = 'height: ' + chartMaxHeight + 'px; max-height: ' + chartMaxHeight + 'px;';
                getJobLoad();
            });
        }
    });
})();
<|endoftext|>


<commit_before>'use strict';

function init() {
  // Initialise la listHON
  hon_listHON.init();
}
init();

function debounce(func, wait, immediate) {
  var timeout;
  return function() {
    var context = this;
    var args = arguments;
    var later = function() {
      timeout = null;
      if (!immediate) {
        func.apply(context, args);
      }
    };
    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) {
      func.apply(context, args);
    }
  };
}

function checkHonCode(url) {
  hon_listHON.checkURL(hon_listHON.formatHREF(url)).then(function(code) {
    if (code) {
      chrome.browserAction.setIcon({path: 'images/icon-48.png'});
      chrome.browserAction.setTitle({
        title: chrome.i18n.getMessage('iconTooltipValid')
      });
    } else {
      chrome.browserAction.setIcon({path: 'images/icon-invalid-48.png'});
      chrome.browserAction.setTitle({
        title: chrome.i18n.getMessage('iconTooltipInvalid')
      });
    }
  });
}

chrome.omnibox.onInputEntered.addListener(function(text) {
  var url = 'https://www.hon.ch/HONcode/Search/search.html';
  if (text) {
    url += '?siteurl=&cref=http%3A%2F%2Fwww.hon.ch' +
    '%2FCSE%2FHONCODE%2Fcontextlink.xml&sa=Search&hl=en&cof=FORID%3A11&q=' +
    encodeURIComponent(text);
  }
  chrome.tabs.getSelected(null, function(tab) {
    chrome.tabs.update(tab.id, {url: url});
  });
});

chrome.tabs.onActivated.addListener(function(activeInfo) {
  chrome.tabs.get(activeInfo.tabId, function(tab) {
    checkHonCode(tab.url);
  });
});

chrome.tabs.onUpdated.addListener(function() {
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    checkHonCode(tabs[0].url);
  });
});

chrome.windows.onFocusChanged.addListener(function() {
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    checkHonCode(tabs[0].url);
  });
});

chrome.browserAction.onClicked.addListener(function(tab) {
  hon_listHON.checkURL(hon_listHON.formatHREF(tab.url)).then(function(code) {
    if (code) {
      var language   = navigator.language.substring(0,2);
      var action_url = 'http://services.hon.ch/cgi-bin/Plugin/redirect.pl?' +
        code + '+' + language;
      chrome.tabs.create({ url: action_url });
    }
  });
});

chrome.webRequest.onCompleted.addListener(debounce(function(details) {
    chrome.tabs.executeScript(
      details.tabId, {
        file: 'bower_components/jquery/dist/jquery.min.js',
        allFrames: true,
      }
    );
    chrome.tabs.executeScript(
      details.tabId, {
        file: 'scripts/utils/tld.js',
        allFrames: true,
      }
    );
    chrome.tabs.executeScript(
      details.tabId, {
        file: 'scripts/utils/md5.js',
        allFrames: true,
      }
    );
    chrome.tabs.executeScript(
      details.tabId, {
        file: 'scripts/utils/hash.js',
        allFrames: true,
      }
    );
    chrome.tabs.executeScript(
      details.tabId, {
        file: 'scripts/honcode.js',
        allFrames: true,
      }
    );
    chrome.tabs.executeScript(
      details.tabId, {
        file: 'scripts/utils/listHON.js',
        allFrames: true,
      }
    );
    chrome.tabs.executeScript(details.tabId, {
      file: 'scripts/contentscript.js',
      allFrames: true,
    });
  }, 1000), {
  urls: [
    '*://*.google.com/*',
    '*://*.google.ac/*',
    '*://*.google.ad/*',
    '*://*.google.ae/*',
    '*://*.google.com.af/*',
    '*://*.google.com.ag/*',
    '*://*.google.com.ai/*',
    '*://*.google.al/*',
    '*://*.google.am/*',
    '*://*.google.co.ao/*',
    '*://*.google.com.ar/*',
    '*://*.google.as/*',
    '*://*.google.at/*',
    '*://*.google.com/au/*',
    '*://*.google.az/*',
    '*://*.google.ba/*',
    '*://*.google.com.bd/*',
    '*://*.google.be/*',
    '*://*.google.bf/*',
    '*://*.google.bg/*',
    '*://*.google.com.bh/*',
    '*://*.google.bi/*',
    '*://*.google.bj/*',
    '*://*.google.com.bn/*',
    '*://*.google.com.bo/*',
    '*://*.google.bs/*',
    '*://*.google.bt/*',
    '*://*.google.co.bw/*',
    '*://*.google.by/*',
    '*://*.google.com.bz/*',
    '*://*.google.ca/*',
    '*://*.google.com.kh/*',
    '*://*.google.cc/*',
    '*://*.google.cd/*',
    '*://*.google.cf/*',
    '*://*.google.cat/*',
    '*://*.google.cg/*',
    '*://*.google.ch/*',
    '*://*.google.ci/*',
    '*://*.google.co.ck/*',
    '*://*.google.cl/*',
    '*://*.google.cm/*',
    '*://*.google.cn/*',
    '*://*.google.com.co/*',
    '*://*.google.co.cr/*',
    '*://*.google.com.cu/*',
    '*://*.google.cv/*',
    '*://*.google.com.cy/*',
    '*://*.google.cz/*',
    '*://*.google.de/*',
    '*://*.google.dj/*',
    '*://*.google.dk/*',
    '*://*.google.dm/*',
    '*://*.google.com.do/*',
    '*://*.google.dz/*',
    '*://*.google.com.ec/*',
    '*://*.google.ee/*',
    '*://*.google.com.eg/*',
    '*://*.google.es/*',
    '*://*.google.com.et/*',
    '*://*.google.fi/*',
    '*://*.google.fj/*',
    '*://*.google.fm/*',
    '*://*.google.fr/*',
    '*://*.google.ga/*',
    '*://*.google.ge/*',
    '*://*.google.gf/*',
    '*://*.google.gg/*',
    '*://*.google.com.gh/*',
    '*://*.google.com.gi/*',
    '*://*.google.gl/*',
    '*://*.google.gm/*',
    '*://*.google.gp/*',
    '*://*.google.gr/*',
    '*://*.google.com.gt/*',
    '*://*.google.gy/*',
    '*://*.google.com.hk/*',
    '*://*.google.hn/*',
    '*://*.google.hr/*',
    '*://*.google.ht/*',
    '*://*.google.hu/*',
    '*://*.google.co.id/*',
    '*://*.google.im/*',
    '*://*.google.co.in/*',
    '*://*.google.io/*',
    '*://*.google.is/*',
    '*://*.google.it/*',
    '*://*.google.je/*',
    '*://*.google.com.jm/*',
    '*://*.google.jo/*',
    '*://*.google.co.jp/*',
    '*://*.google.co.ke/*',
    '*://*.google.ki/*',
    '*://*.google.kg/*',
    '*://*.google.co.kr/*',
    '*://*.google.com.kw/*',
    '*://*.google.kz/*',
    '*://*.google.la/*',
    '*://*.google.com.lb/*',
    '*://*.google.com.lc/*',
    '*://*.google.li/*',
    '*://*.google.lk/*',
    '*://*.google.co.ls/*',
    '*://*.google.lt/*',
    '*://*.google.lu/*',
    '*://*.google.lv/*',
    '*://*.google.com.ly/*',
    '*://*.google.co.ma/*',
    '*://*.google.md/*',
    '*://*.google.me/*',
    '*://*.google.mg/*',
    '*://*.google.mk/*',
    '*://*.google.ml/*',
    '*://*.google.com.mm/*',
    '*://*.google.mn/*',
    '*://*.google.ms/*',
    '*://*.google.com.mt/*',
    '*://*.google.mu/*',
    '*://*.google.mv/*',
    '*://*.google.mw/*',
    '*://*.google.com.mx/*',
    '*://*.google.com.my/*',
    '*://*.google.co.mz/*',
    '*://*.google.com.na/*',
    '*://*.google.ne/*',
    '*://*.google.nf/*',
    '*://*.google.ng/*',
    '*://*.google.com.ni/*',
    '*://*.google.nl/*',
    '*://*.google.no/*',
    '*://*.google.com.np/*',
    '*://*.google.nr/*',
    '*://*.google.nu/*',
    '*://*.google.co.nz/*',
    '*://*.google.com.om/*',
    '*://*.google.com.pk/*',
    '*://*.google.com.pa/*',
    '*://*.google.com.pe/*',
    '*://*.google.com.ph/*',
    '*://*.google.pl/*',
    '*://*.google.com.pg/*',
    '*://*.google.pn/*',
    '*://*.google.com.pr/*',
    '*://*.google.ps/*',
    '*://*.google.pt/*',
    '*://*.google.com.py/*',
    '*://*.google.com.qa/*',
    '*://*.google.ro/*',
    '*://*.google.rs/*',
    '*://*.google.ru/*',
    '*://*.google.rw/*',
    '*://*.google.com.sa/*',
    '*://*.google.com.sb/*',
    '*://*.google.sc/*',
    '*://*.google.se/*',
    '*://*.google.com.sg/*',
    '*://*.google.sh/*',
    '*://*.google.si/*',
    '*://*.google.sk/*',
    '*://*.google.com.sl/*',
    '*://*.google.sn/*',
    '*://*.google.sm/*',
    '*://*.google.so/*',
    '*://*.google.st/*',
    '*://*.google.sr/*',
    '*://*.google.com.sv/*',
    '*://*.google.td/*',
    '*://*.google.tg/*',
    '*://*.google.co.th/*',
    '*://*.google.com.tj/*',
    '*://*.google.tk/*',
    '*://*.google.tl/*',
    '*://*.google.tm/*',
    '*://*.google.to/*',
    '*://*.google.tn/*',
    '*://*.google.com.tr/*',
    '*://*.google.tt/*',
    '*://*.google.com.tw/*',
    '*://*.google.co.tz/*',
    '*://*.google.com.ua/*',
    '*://*.google.co.ug/*',
    '*://*.google.co.uk/*',
    '*://*.google.us/*',
    '*://*.google.com.uy/*',
    '*://*.google.co.uz/*',
    '*://*.google.com.vc/*',
    '*://*.google.co.ve/*',
    '*://*.google.vg/*',
    '*://*.google.co.vi/*',
    '*://*.google.com.vn/*',
    '*://*.google.vu/*',
    '*://*.google.ws/*',
    '*://*.google.co.za/*',
    '*://*.google.co.zm/*',
    '*://*.google.co.zw/*',
    '*://*.bing.com/*',
    '*://*.search.yahoo.com/*',
    '*://*.wikipedia.org/*',
    '*://*.nlm.nih.gov/medlineplus/*',
  ],
  types: ['xmlhttprequest'],
});
<commit_msg>check if tab and tab.url exist<commit_after>'use strict';

function init() {
  // Initialise la listHON
  hon_listHON.init();
}
init();

function debounce(func, wait, immediate) {
  var timeout;
  return function() {
    var context = this;
    var args = arguments;
    var later = function() {
      timeout = null;
      if (!immediate) {
        func.apply(context, args);
      }
    };
    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) {
      func.apply(context, args);
    }
  };
}

function checkHonCode(url) {
  hon_listHON.checkURL(hon_listHON.formatHREF(url)).then(function(code) {
    if (code) {
      chrome.browserAction.setIcon({path: 'images/icon-48.png'});
      chrome.browserAction.setTitle({
        title: chrome.i18n.getMessage('iconTooltipValid')
      });
    } else {
      chrome.browserAction.setIcon({path: 'images/icon-invalid-48.png'});
      chrome.browserAction.setTitle({
        title: chrome.i18n.getMessage('iconTooltipInvalid')
      });
    }
  });
}

chrome.omnibox.onInputEntered.addListener(function(text) {
  var url = 'https://www.hon.ch/HONcode/Search/search.html';
  if (text) {
    url += '?siteurl=&cref=http%3A%2F%2Fwww.hon.ch' +
    '%2FCSE%2FHONCODE%2Fcontextlink.xml&sa=Search&hl=en&cof=FORID%3A11&q=' +
    encodeURIComponent(text);
  }
  chrome.tabs.getSelected(null, function(tab) {
    chrome.tabs.update(tab.id, {url: url});
  });
});

chrome.tabs.onActivated.addListener(function(activeInfo) {
  chrome.tabs.get(activeInfo.tabId, function(tab) {
    checkHonCode(tab.url);
  });
});

chrome.tabs.onUpdated.addListener(function() {
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    if (tabs[0] && tabs[0].url) {
      checkHonCode(tabs[0].url);
    }
  });
});

chrome.windows.onFocusChanged.addListener(function() {
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    if (tabs[0] && tabs[0].url) {
      checkHonCode(tabs[0].url);
    }
  });
});

chrome.browserAction.onClicked.addListener(function(tab) {
  hon_listHON.checkURL(hon_listHON.formatHREF(tab.url)).then(function(code) {
    if (code) {
      var language   = navigator.language.substring(0,2);
      var action_url = 'http://services.hon.ch/cgi-bin/Plugin/redirect.pl?' +
        code + '+' + language;
      chrome.tabs.create({ url: action_url });
    }
  });
});

chrome.webRequest.onCompleted.addListener(debounce(function(details) {
    chrome.tabs.executeScript(
      details.tabId, {
        file: 'bower_components/jquery/dist/jquery.min.js',
        allFrames: true,
      }
    );
    chrome.tabs.executeScript(
      details.tabId, {
        file: 'scripts/utils/tld.js',
        allFrames: true,
      }
    );
    chrome.tabs.executeScript(
      details.tabId, {
        file: 'scripts/utils/md5.js',
        allFrames: true,
      }
    );
    chrome.tabs.executeScript(
      details.tabId, {
        file: 'scripts/utils/hash.js',
        allFrames: true,
      }
    );
    chrome.tabs.executeScript(
      details.tabId, {
        file: 'scripts/honcode.js',
        allFrames: true,
      }
    );
    chrome.tabs.executeScript(
      details.tabId, {
        file: 'scripts/utils/listHON.js',
        allFrames: true,
      }
    );
    chrome.tabs.executeScript(details.tabId, {
      file: 'scripts/contentscript.js',
      allFrames: true,
    });
  }, 1000), {
  urls: [
    '*://*.google.com/*',
    '*://*.google.ac/*',
    '*://*.google.ad/*',
    '*://*.google.ae/*',
    '*://*.google.com.af/*',
    '*://*.google.com.ag/*',
    '*://*.google.com.ai/*',
    '*://*.google.al/*',
    '*://*.google.am/*',
    '*://*.google.co.ao/*',
    '*://*.google.com.ar/*',
    '*://*.google.as/*',
    '*://*.google.at/*',
    '*://*.google.com/au/*',
    '*://*.google.az/*',
    '*://*.google.ba/*',
    '*://*.google.com.bd/*',
    '*://*.google.be/*',
    '*://*.google.bf/*',
    '*://*.google.bg/*',
    '*://*.google.com.bh/*',
    '*://*.google.bi/*',
    '*://*.google.bj/*',
    '*://*.google.com.bn/*',
    '*://*.google.com.bo/*',
    '*://*.google.bs/*',
    '*://*.google.bt/*',
    '*://*.google.co.bw/*',
    '*://*.google.by/*',
    '*://*.google.com.bz/*',
    '*://*.google.ca/*',
    '*://*.google.com.kh/*',
    '*://*.google.cc/*',
    '*://*.google.cd/*',
    '*://*.google.cf/*',
    '*://*.google.cat/*',
    '*://*.google.cg/*',
    '*://*.google.ch/*',
    '*://*.google.ci/*',
    '*://*.google.co.ck/*',
    '*://*.google.cl/*',
    '*://*.google.cm/*',
    '*://*.google.cn/*',
    '*://*.google.com.co/*',
    '*://*.google.co.cr/*',
    '*://*.google.com.cu/*',
    '*://*.google.cv/*',
    '*://*.google.com.cy/*',
    '*://*.google.cz/*',
    '*://*.google.de/*',
    '*://*.google.dj/*',
    '*://*.google.dk/*',
    '*://*.google.dm/*',
    '*://*.google.com.do/*',
    '*://*.google.dz/*',
    '*://*.google.com.ec/*',
    '*://*.google.ee/*',
    '*://*.google.com.eg/*',
    '*://*.google.es/*',
    '*://*.google.com.et/*',
    '*://*.google.fi/*',
    '*://*.google.fj/*',
    '*://*.google.fm/*',
    '*://*.google.fr/*',
    '*://*.google.ga/*',
    '*://*.google.ge/*',
    '*://*.google.gf/*',
    '*://*.google.gg/*',
    '*://*.google.com.gh/*',
    '*://*.google.com.gi/*',
    '*://*.google.gl/*',
    '*://*.google.gm/*',
    '*://*.google.gp/*',
    '*://*.google.gr/*',
    '*://*.google.com.gt/*',
    '*://*.google.gy/*',
    '*://*.google.com.hk/*',
    '*://*.google.hn/*',
    '*://*.google.hr/*',
    '*://*.google.ht/*',
    '*://*.google.hu/*',
    '*://*.google.co.id/*',
    '*://*.google.im/*',
    '*://*.google.co.in/*',
    '*://*.google.io/*',
    '*://*.google.is/*',
    '*://*.google.it/*',
    '*://*.google.je/*',
    '*://*.google.com.jm/*',
    '*://*.google.jo/*',
    '*://*.google.co.jp/*',
    '*://*.google.co.ke/*',
    '*://*.google.ki/*',
    '*://*.google.kg/*',
    '*://*.google.co.kr/*',
    '*://*.google.com.kw/*',
    '*://*.google.kz/*',
    '*://*.google.la/*',
    '*://*.google.com.lb/*',
    '*://*.google.com.lc/*',
    '*://*.google.li/*',
    '*://*.google.lk/*',
    '*://*.google.co.ls/*',
    '*://*.google.lt/*',
    '*://*.google.lu/*',
    '*://*.google.lv/*',
    '*://*.google.com.ly/*',
    '*://*.google.co.ma/*',
    '*://*.google.md/*',
    '*://*.google.me/*',
    '*://*.google.mg/*',
    '*://*.google.mk/*',
    '*://*.google.ml/*',
    '*://*.google.com.mm/*',
    '*://*.google.mn/*',
    '*://*.google.ms/*',
    '*://*.google.com.mt/*',
    '*://*.google.mu/*',
    '*://*.google.mv/*',
    '*://*.google.mw/*',
    '*://*.google.com.mx/*',
    '*://*.google.com.my/*',
    '*://*.google.co.mz/*',
    '*://*.google.com.na/*',
    '*://*.google.ne/*',
    '*://*.google.nf/*',
    '*://*.google.ng/*',
    '*://*.google.com.ni/*',
    '*://*.google.nl/*',
    '*://*.google.no/*',
    '*://*.google.com.np/*',
    '*://*.google.nr/*',
    '*://*.google.nu/*',
    '*://*.google.co.nz/*',
    '*://*.google.com.om/*',
    '*://*.google.com.pk/*',
    '*://*.google.com.pa/*',
    '*://*.google.com.pe/*',
    '*://*.google.com.ph/*',
    '*://*.google.pl/*',
    '*://*.google.com.pg/*',
    '*://*.google.pn/*',
    '*://*.google.com.pr/*',
    '*://*.google.ps/*',
    '*://*.google.pt/*',
    '*://*.google.com.py/*',
    '*://*.google.com.qa/*',
    '*://*.google.ro/*',
    '*://*.google.rs/*',
    '*://*.google.ru/*',
    '*://*.google.rw/*',
    '*://*.google.com.sa/*',
    '*://*.google.com.sb/*',
    '*://*.google.sc/*',
    '*://*.google.se/*',
    '*://*.google.com.sg/*',
    '*://*.google.sh/*',
    '*://*.google.si/*',
    '*://*.google.sk/*',
    '*://*.google.com.sl/*',
    '*://*.google.sn/*',
    '*://*.google.sm/*',
    '*://*.google.so/*',
    '*://*.google.st/*',
    '*://*.google.sr/*',
    '*://*.google.com.sv/*',
    '*://*.google.td/*',
    '*://*.google.tg/*',
    '*://*.google.co.th/*',
    '*://*.google.com.tj/*',
    '*://*.google.tk/*',
    '*://*.google.tl/*',
    '*://*.google.tm/*',
    '*://*.google.to/*',
    '*://*.google.tn/*',
    '*://*.google.com.tr/*',
    '*://*.google.tt/*',
    '*://*.google.com.tw/*',
    '*://*.google.co.tz/*',
    '*://*.google.com.ua/*',
    '*://*.google.co.ug/*',
    '*://*.google.co.uk/*',
    '*://*.google.us/*',
    '*://*.google.com.uy/*',
    '*://*.google.co.uz/*',
    '*://*.google.com.vc/*',
    '*://*.google.co.ve/*',
    '*://*.google.vg/*',
    '*://*.google.co.vi/*',
    '*://*.google.com.vn/*',
    '*://*.google.vu/*',
    '*://*.google.ws/*',
    '*://*.google.co.za/*',
    '*://*.google.co.zm/*',
    '*://*.google.co.zw/*',
    '*://*.bing.com/*',
    '*://*.search.yahoo.com/*',
    '*://*.wikipedia.org/*',
    '*://*.nlm.nih.gov/medlineplus/*',
  ],
  types: ['xmlhttprequest'],
});
<|endoftext|>


<commit_before>import React, { Component } from "react";
import classNames from "classnames";
import * as TYPES from "../middleware/constants";
import _ from "lodash";

const helper = require("../middleware/helper");

export default class MultiRange extends Component {
	constructor(props) {
		super(props);
		this.state = {
			selected: []
		};
		this.type = "range";
		this.urlParams = helper.URLParams.get(this.props.componentId, true);
		this.handleChange = this.handleChange.bind(this);
		this.resetState = this.resetState.bind(this);
		this.handleTagClick = this.handleTagClick.bind(this);
		this.customQuery = this.customQuery.bind(this);
	}

	// Set query information
	componentWillMount() {
		this.setQueryInfo();
		this.checkDefault(this.props);
		this.listenFilter();
	}

	componentWillReceiveProps(nextProps) {
		this.checkDefault(nextProps);
	}

	componentWillUnmount() {
		if(this.filterListener) {
			this.filterListener.remove();
		}
	}

	listenFilter() {
		this.filterListener = helper.sensorEmitter.addListener("clearFilter", (data) => {
			if(data === this.props.componentId) {
				this.changeValue(null);
			}
		});
	}

	checkDefault(props) {
		this.urlParams = helper.URLParams.get(props.componentId, true);
		const defaultValue = this.urlParams !== null ? this.urlParams : props.defaultSelected;
		this.changeValue(defaultValue);
	}

	changeValue(defaultValue) {
		if (!_.isEqual(this.defaultSelected, defaultValue)) {
			this.defaultSelected = defaultValue;
			if(defaultValue) {
				this.resetState();
				const records = this.props.data.filter(record => defaultValue.indexOf(record.label) > -1);
				if (records && records.length) {
					setTimeout(this.handleChange.bind(this, records), 1000);
				}
			} else {
				this.handleChange(null);
			}
		}
	}

	// set the query type and input data
	setQueryInfo() {
		const obj = {
			key: this.props.componentId,
			value: {
				queryType: this.type,
				inputData: this.props.appbaseField,
				customQuery: this.props.customQuery ? this.props.customQuery : this.customQuery,
				reactiveId: this.context.reactiveId,
				showFilter: this.props.showFilter,
				filterLabel: this.props.filterLabel ? this.props.filterLabel : this.props.componentId,
				component: "MultiRange",
				defaultSelected: this.urlParams !== null ? this.urlParams : this.props.defaultSelected
			}
		};
		helper.selectedSensor.setSensorInfo(obj);
	}

	// build query for this sensor only
	customQuery(record) {
		function generateRangeQuery(appbaseField) {
			if (record.length > 0) {
				return record.map(singleRecord => ({
					range: {
						[appbaseField]: {
							gte: singleRecord.start,
							lte: singleRecord.end,
							boost: 2.0
						}
					}
				}));
			}
			return null;
		}

		if (record) {
			const query = {
				bool: {
					should: generateRangeQuery(this.props.appbaseField),
					minimum_should_match: 1,
					boost: 1.0
				}
			};
			return query;
		}
		return null;
	}

	// handle the input change and pass the value inside sensor info
	handleChange(record) {
		let selected = this.state.selected;
		let selectedIndex = null;
		let records = record;

		function setRecord(selectedRecord, index, item) {
			if (item.label === selectedRecord.label) {
				selectedIndex = index;
				selected.splice(index, 1);
			}
		}

		if(record) {
			if (selected === null) {
				selected = [];
			}
			if (!_.isArray(record)) {
				records = [record];
			}
			records.forEach((item) => {
				selected.forEach((selectedRecord, index) => {
					setRecord(selectedRecord, index, item);
				});
			});

			if (selectedIndex === null) {
				records.forEach((item) => {
					selected.push(item);
				});
			}
		} else {
			selected = null;
		}
		selected = selected === "" ? null : selected;
		selected = selected && selected.length ? selected : null;
		this.defaultSelected = selected;

		this.setState({
			selected
		});

		const obj = {
			key: this.props.componentId,
			value: selected
		};

		// pass the selected sensor value with componentId as key,
		const isExecuteQuery = true;
		if (this.props.onValueChange) {
			this.props.onValueChange(obj.value);
		}
		helper.URLParams.update(this.props.componentId, this.getSelectedLabels(selected), this.props.URLParams);
		helper.selectedSensor.set(obj, isExecuteQuery);
	}

	getSelectedLabels(selected) {
		return selected ? selected.map(item => item.label) : null;
	}

	resetState() {
		this.setState({
			selected: []
		});
		const obj = {
			key: this.props.componentId,
			value: []
		};
		// pass the selected sensor value with componentId as key,
		const isExecuteQuery = true;
		helper.URLParams.update(this.props.componentId, null, this.props.URLParams);
		helper.selectedSensor.set(obj, isExecuteQuery);
	}

	handleTagClick(label) {
		const target = this.state.selected.filter(record => record.label === label);
		this.handleChange(target[0]);
	}

	renderButtons() {
		let buttons;
		const selectedText = this.state.selected ? this.state.selected.map(record => record.label) : "";
		if (this.props.data) {
			buttons = this.props.data.map(record => (

 this.handleChange(record)}>
					<input
						type="checkbox"
						className="rbc-checkbox-item"
						checked={selectedText.indexOf(record.label) > -1}
						value={record.label}
					/>
					{record.label}

				));
		}
		return buttons;
	}

	// render
	render() {
		let title = null;
		const TagItemsArray = [];

		if (this.props.title) {
			title = (
{this.props.title}
);
		}

		if (this.state.selected && this.props.showTags) {
			this.state.selected.forEach((item) => {
				TagItemsArray.push(<Tag
					key={item.label}
					value={item.label}
					onClick={this.handleTagClick}
				/>);
			});
		}

		const cx = classNames({
			"rbc-title-active": this.props.title,
			"rbc-title-inactive": !this.props.title
		});

		return (
			<div className={`rbc rbc-multirange col s12 col-xs-12 card thumbnail ${cx}`} style={this.props.componentStyle}>

					{title}

						{
							TagItemsArray.length ?

									{TagItemsArray}

 :
							null
						}
						{this.renderButtons()}

		);
	}
}

const Tag = (props) => {
	return (
		 props.onClick(props.value)} className="rbc-tag-item col">
			×
			{props.value}

	);
}

Tag.propTypes = {
	onClick: React.PropTypes.func.isRequired,
	value: React.PropTypes.string.isRequired
};

MultiRange.propTypes = {
	appbaseField: React.PropTypes.string.isRequired,
	componentId: React.PropTypes.string.isRequired,
	title: React.PropTypes.oneOfType([
		React.PropTypes.string,
		React.PropTypes.element
	]),
	data: React.PropTypes.any.isRequired,
	defaultSelected: React.PropTypes.array,
	customQuery: React.PropTypes.func,
	onValueChange: React.PropTypes.func,
	componentStyle: React.PropTypes.object,
	URLParams: React.PropTypes.bool,
	showFilter: React.PropTypes.bool,
	filterLabel: React.PropTypes.string,
	showTags: React.PropTypes.bool
};

// Default props value
MultiRange.defaultProps = {
	URLParams: false,
	showFilter: true,
	showTags: true
};

// context type
MultiRange.contextTypes = {
	appbaseRef: React.PropTypes.any.isRequired,
	type: React.PropTypes.any.isRequired,
	reactiveId: React.PropTypes.number
};

MultiRange.types = {
	componentId: TYPES.STRING,
	appbaseField: TYPES.STRING,
	appbaseFieldType: TYPES.NUMBER,
	title: TYPES.STRING,
	data: TYPES.OBJECT,
	defaultSelected: TYPES.ARRAY,
	customQuery: TYPES.FUNCTION,
	componentStyle: TYPES.OBJECT,
	URLParams: TYPES.BOOLEAN,
	showFilter: TYPES.BOOLEAN,
	showTags: TYPES.BOOLEAN,
	filterLabel: TYPES.STRING
};
<commit_msg>Add showCheckbox prop to MultiRange for #89<commit_after>import React, { Component } from "react";
import classNames from "classnames";
import * as TYPES from "../middleware/constants";
import _ from "lodash";

const helper = require("../middleware/helper");

export default class MultiRange extends Component {
	constructor(props) {
		super(props);
		this.state = {
			selected: []
		};
		this.type = "range";
		this.urlParams = helper.URLParams.get(this.props.componentId, true);
		this.handleChange = this.handleChange.bind(this);
		this.resetState = this.resetState.bind(this);
		this.handleTagClick = this.handleTagClick.bind(this);
		this.customQuery = this.customQuery.bind(this);
	}

	// Set query information
	componentWillMount() {
		this.setQueryInfo();
		this.checkDefault(this.props);
		this.listenFilter();
	}

	componentWillReceiveProps(nextProps) {
		this.checkDefault(nextProps);
	}

	componentWillUnmount() {
		if(this.filterListener) {
			this.filterListener.remove();
		}
	}

	listenFilter() {
		this.filterListener = helper.sensorEmitter.addListener("clearFilter", (data) => {
			if(data === this.props.componentId) {
				this.changeValue(null);
			}
		});
	}

	checkDefault(props) {
		this.urlParams = helper.URLParams.get(props.componentId, true);
		const defaultValue = this.urlParams !== null ? this.urlParams : props.defaultSelected;
		this.changeValue(defaultValue);
	}

	changeValue(defaultValue) {
		if (!_.isEqual(this.defaultSelected, defaultValue)) {
			this.defaultSelected = defaultValue;
			if(defaultValue) {
				this.resetState();
				const records = this.props.data.filter(record => defaultValue.indexOf(record.label) > -1);
				if (records && records.length) {
					setTimeout(this.handleChange.bind(this, records), 1000);
				}
			} else {
				this.handleChange(null);
			}
		}
	}

	// set the query type and input data
	setQueryInfo() {
		const obj = {
			key: this.props.componentId,
			value: {
				queryType: this.type,
				inputData: this.props.appbaseField,
				customQuery: this.props.customQuery ? this.props.customQuery : this.customQuery,
				reactiveId: this.context.reactiveId,
				showFilter: this.props.showFilter,
				filterLabel: this.props.filterLabel ? this.props.filterLabel : this.props.componentId,
				component: "MultiRange",
				defaultSelected: this.urlParams !== null ? this.urlParams : this.props.defaultSelected
			}
		};
		helper.selectedSensor.setSensorInfo(obj);
	}

	// build query for this sensor only
	customQuery(record) {
		function generateRangeQuery(appbaseField) {
			if (record.length > 0) {
				return record.map(singleRecord => ({
					range: {
						[appbaseField]: {
							gte: singleRecord.start,
							lte: singleRecord.end,
							boost: 2.0
						}
					}
				}));
			}
			return null;
		}

		if (record) {
			const query = {
				bool: {
					should: generateRangeQuery(this.props.appbaseField),
					minimum_should_match: 1,
					boost: 1.0
				}
			};
			return query;
		}
		return null;
	}

	// handle the input change and pass the value inside sensor info
	handleChange(record) {
		let selected = this.state.selected;
		let selectedIndex = null;
		let records = record;

		function setRecord(selectedRecord, index, item) {
			if (item.label === selectedRecord.label) {
				selectedIndex = index;
				selected.splice(index, 1);
			}
		}

		if(record) {
			if (selected === null) {
				selected = [];
			}
			if (!_.isArray(record)) {
				records = [record];
			}
			records.forEach((item) => {
				selected.forEach((selectedRecord, index) => {
					setRecord(selectedRecord, index, item);
				});
			});

			if (selectedIndex === null) {
				records.forEach((item) => {
					selected.push(item);
				});
			}
		} else {
			selected = null;
		}
		selected = selected === "" ? null : selected;
		selected = selected && selected.length ? selected : null;
		this.defaultSelected = selected;

		this.setState({
			selected
		});

		const obj = {
			key: this.props.componentId,
			value: selected
		};

		// pass the selected sensor value with componentId as key,
		const isExecuteQuery = true;
		if (this.props.onValueChange) {
			this.props.onValueChange(obj.value);
		}
		helper.URLParams.update(this.props.componentId, this.getSelectedLabels(selected), this.props.URLParams);
		helper.selectedSensor.set(obj, isExecuteQuery);
	}

	getSelectedLabels(selected) {
		return selected ? selected.map(item => item.label) : null;
	}

	resetState() {
		this.setState({
			selected: []
		});
		const obj = {
			key: this.props.componentId,
			value: []
		};
		// pass the selected sensor value with componentId as key,
		const isExecuteQuery = true;
		helper.URLParams.update(this.props.componentId, null, this.props.URLParams);
		helper.selectedSensor.set(obj, isExecuteQuery);
	}

	handleTagClick(label) {
		const target = this.state.selected.filter(record => record.label === label);
		this.handleChange(target[0]);
	}

	renderButtons() {
		let buttons;
		const selectedText = this.state.selected ? this.state.selected.map(record => record.label) : "";
		if (this.props.data) {
			buttons = this.props.data.map((record) => {
				const cx = classNames({
					"rbc-checkbox-active": this.props.showCheckbox,
					"rbc-checkbox-inactive": !this.props.showCheckbox,
					"rbc-list-item-active": selectedText.indexOf(record.label) !== -1,
					"rbc-list-item-inactive": selectedText.indexOf(record.label) === -1
				});

				return (
					<div className={`rbc-list-item row ${cx}`} key={record.label} onClick={() => this.handleChange(record)}>
						<input
							type="checkbox"
							className="rbc-checkbox-item"
							checked={selectedText.indexOf(record.label) > -1}
							value={record.label}
						/>
						{record.label}

				);
			});
		}
		return buttons;
	}

	// render
	render() {
		let title = null;
		const TagItemsArray = [];

		if (this.props.title) {
			title = (
{this.props.title}
);
		}

		if (this.state.selected && this.props.showTags) {
			this.state.selected.forEach((item) => {
				TagItemsArray.push(<Tag
					key={item.label}
					value={item.label}
					onClick={this.handleTagClick}
				/>);
			});
		}

		const cx = classNames({
			"rbc-title-active": this.props.title,
			"rbc-title-inactive": !this.props.title,
			"rbc-checkbox-active": this.props.showCheckbox,
			"rbc-checkbox-inactive": !this.props.showCheckbox
		});

		return (
			<div className={`rbc rbc-multirange col s12 col-xs-12 card thumbnail ${cx}`} style={this.props.componentStyle}>

					{title}

						{
							TagItemsArray.length ?

									{TagItemsArray}

 :
							null
						}
						{this.renderButtons()}

		);
	}
}

const Tag = (props) => {
	return (
		 props.onClick(props.value)} className="rbc-tag-item col">
			×
			{props.value}

	);
}

Tag.propTypes = {
	onClick: React.PropTypes.func.isRequired,
	value: React.PropTypes.string.isRequired
};

MultiRange.propTypes = {
	appbaseField: React.PropTypes.string.isRequired,
	componentId: React.PropTypes.string.isRequired,
	title: React.PropTypes.oneOfType([
		React.PropTypes.string,
		React.PropTypes.element
	]),
	data: React.PropTypes.any.isRequired,
	defaultSelected: React.PropTypes.array,
	customQuery: React.PropTypes.func,
	onValueChange: React.PropTypes.func,
	componentStyle: React.PropTypes.object,
	URLParams: React.PropTypes.bool,
	showFilter: React.PropTypes.bool,
	filterLabel: React.PropTypes.string,
	showTags: React.PropTypes.bool,
	showCheckbox: React.PropTypes.bool
};

// Default props value
MultiRange.defaultProps = {
	URLParams: false,
	showFilter: true,
	showTags: true,
	showCheckbox: true
};

// context type
MultiRange.contextTypes = {
	appbaseRef: React.PropTypes.any.isRequired,
	type: React.PropTypes.any.isRequired,
	reactiveId: React.PropTypes.number
};

MultiRange.types = {
	componentId: TYPES.STRING,
	appbaseField: TYPES.STRING,
	appbaseFieldType: TYPES.NUMBER,
	title: TYPES.STRING,
	data: TYPES.OBJECT,
	defaultSelected: TYPES.ARRAY,
	customQuery: TYPES.FUNCTION,
	componentStyle: TYPES.OBJECT,
	URLParams: TYPES.BOOLEAN,
	showFilter: TYPES.BOOLEAN,
	showTags: TYPES.BOOLEAN,
	filterLabel: TYPES.STRING,
	showCheckbox: TYPES.BOOLEAN
};
<|endoftext|>


<commit_before>import gpio from 'gpio';

// pin 38 GPIO 20 - for trigger
const trig = gpio.export(38, {
  direction: 'out'
});

// pin 37 GPIO 26 - for echo
const echo = gpio.export(37, {
  direction: 'in'
});
const speedSound = 34000;
responsiveVoice.speak('');
let start = 0;
let end = 0;
let timeDiff = 0;
let distance = 0;

function getDistance() {
  // resetting trigger
  console.log('resetting trigger');
  trig.set(0);
  setTimeout(function() {
    console.log("initial trig value (0): " + trig.value); // should be 0
    console.log('turning on sensor');
    trig.set();
    setTimeout(function() {
      console.log('turning off sensor');
      trig.set(0);
      start = new Date().getTime / 1000;
      console.log('start time set to ' + start);
      if (echo.value === 0) {
        console.log('Echo is zero');
        start = new Date().getTime / 1000;
        console.log('start time reset to ' + start);
      } else {
        console.log('Echo is ' + echo.value);

        end = new Date().getTime() / 1000;
        console.log('end time set to ' + end);
        timeDiff = end - start;
        console.log('time diff = ' + timeDiff);
        distance = (timeDiff * speedSound) / 2;
        console.log('Distance = ' + distance);

        if (distance < 60) {
          console.log('User is within 2ft.');
          return true;
        }
      }

      setTimeout(getDistance, 500);
    }, 10);
  }, 500);
}

module.exports = {
  getDistance
};
<commit_msg>added more logs<commit_after>import gpio from 'gpio';

// pin 38 GPIO 20 - for trigger
const trig = gpio.export(38, {
  direction: 'out'
});

// pin 37 GPIO 26 - for echo
const echo = gpio.export(37, {
  direction: 'in'
});
const speedSound = 34000;
let start = 0;
let end = 0;
let timeDiff = 0;
let distance = 0;

function getDistance() {
  responsiveVoice.speak('');
  // resetting trigger
  console.log('resetting trigger');
  trig.set(0);
  setTimeout(function() {
    console.log("initial trig value (0): " + trig.value); // should be 0
    console.log('turning on sensor');
    trig.set();
    setTimeout(function() {
      console.log('turning off sensor');
      trig.set(0);
      start = new Date().getTime / 1000;
      console.log('start time set to ' + start);
      if (echo.value === 0) {
        console.log('Echo is zero');
        start = new Date().getTime / 1000;
        console.log('start time reset to ' + start);
      } else {
        console.log('Echo is ' + echo.value);

        end = new Date().getTime() / 1000;
        console.log('end time set to ' + end);
        timeDiff = end - start;
        console.log('time diff = ' + timeDiff);
        distance = (timeDiff * speedSound) / 2;
        console.log('Distance = ' + distance);

        if (distance < 60) {
          console.log('User is within 2ft.');
          return true;
        }
      }

      setTimeout(getDistance, 500);
    }, 10);
  }, 500);
}

module.exports = {
  getDistance
};
<|endoftext|>