<commit_before>$.fn.sendvalue = function(trigger){
  $(this).each(function(){
    var self = this;
    var el = $(self);
    el.keydown(function(e){
      if(e.which == 13) {
        trigger.call(self,el.val());
        return false;
      }
      else
        return true;
    });
  });
};

$.fn.livechange = function(ms,trigger){
  $(this).each(function(){
    var self = this;
    var el = $(self);
    var last_val;
    var check = function(){
      var val = el.val();
      if(val != last_val)
        trigger.call(self);
      last_val = val;
    };
    var checker;
    var restart = function(){
      clearTimeout(checker);
      checker = setInterval(check,ms);
    };
    restart();
    el.keypress(restart).change(restart);
  });
};

(function(){

  ////////////////////////////////////////////////////////////////////////////////
  // State
  var sessionToken = null;
  var element_count = 0, el_table = {};
  var tp_enable_log = $.cookie('tp_log') == "true";
  var signal_count = 0;

  document.head = document.head || document.getElementsByTagName('head')[0];

  ////////////////////////////////////////////////////////////////////////////////
  // Logging
  window.do_logging = function(x){
    $.cookie('tp_log',x.toString());
  };

  function console_log(){
    if (tp_enable_log) { window.console.log.apply(window.console,arguments); }
  }

  ////////////////////////////////////////////////////////////////////////////////
  // Main entry point
  $(document).ready(function(){
    // initCommunicationHTTP();
    initCommunicationWebSockets();
  });

  ////////////////////////////////////////////////////////////////////////////////
  // Client-server communication
  // - GET and POST requests

  // Initialize communication via HTTP requests.
  function initCommunicationHTTP() {
    setTimeout(function(){
      waitForEvents();
    })
  }

  // Poll instruction from the server.
  function waitForEvents(){
    console_log("Polling… (%d signals so far)",signal_count);
    var data = { token: sessionToken };
    var cmd = sessionToken != null? 'poll' : 'init';
    if(cmd == 'init')
      data.info = window.location.href;
    var req = $.ajax({
      dataType: 'json',
      url: cmd,
      data: data,
      success: function(events){
        if(sessionToken == null) {
          sessionToken = req.getResponseHeader('Set-Token').match(/[0-9]+/)*1;
        }
        console_log("Running event" +(events.length>1?'s':'') +"…")
        if(events.length){
          console_log('Event list:');
          runMultipleEvents(events);
        } else {
          runEvent(events, signalEvent, function(response){
            maybeReply(response, waitForEvents);
          });
        }
      },
      error: function(reply){
        console_log("Error, waiting…");
        setTimeout(function(){
          waitForEvents();
        },5000);
      }
    });
  }

  function runMultipleEvents(events){
    if(events.length == 0) {
      return waitForEvents();
    }
    runEvent(events.shift(), signalEvent, function(response){
      maybeReply(response, function(){
        runMultipleEvents(events);
      });
    });
  }

  // Send an event to the server.
  function signalEvent(value) {
    signal({ Event: value}, function (){});
  }

  // Send a reply to the server if necessary.
  function maybeReply(response, continuation) {
    if (response != undefined) { signal(response, continuation); }
    else { continuation(); }
  }

  // Send response back to the server.
  function signal(signal,continuation){
    signal_count++;
    console_log('Signal: %s',JSON.stringify(signal));
    $.ajax({
      dataType: 'json',
      url:'signal',
      data: { token: sessionToken, signal: JSON.stringify(signal) },
      success: function(){
        continuation();
      },
      error: function(reply){
        console_log("Error: %o",reply);
      }
    });
  }

  ////////////////////////////////////////////////////////////////////////////////
  // Client-server communication
  // - WebSockets

  // Initialize client-server communication via WebSockets.
  function initCommunicationWebSockets() {
    var url = 'ws:' + window.location.href.toString().slice(5) + 'websocket';
    var ws  = new WebSocket(url);

    $(window).unload( function () {
      // Make sure that the WebSocket is closed when the browser window is closed.
      ws.close();
    });

    var sendEvent = function (elid, key, params) {
      ws.send(JSON.stringify({ Event :
          { Element : { Element : elid }
          , EventId : key
          , Params  : params
          }
        }));
    }
    var reply     = function (response) {
      if (response != undefined)
        ws.send(JSON.stringify(response));
    }
    // Send ping message in regular intervals.
    // We expect pong messages in return to keep the connection alive.
    function ping(){
      ws.send("ping");
      window.setTimeout(ping,2000);
    }

    ws.onopen = function (e){
      ping();
      ws.onmessage = function (msg) {
        // console_log("WebSocket message: %o",msg);
        if (msg.data != "pong")
          { runEvent(JSON.parse(msg.data), sendEvent, reply); }
      }
      ws.onclose = function (e) {
        console_log("WebSocket closed: %o", e);
      }
      ws.onerror = function (e) {
        console_log("WebSocket error: %o", e);
      }
    }
  }

  ////////////////////////////////////////////////////////////////////////////////
  // FFI - Execute and reply to commands from the server

  function runEvent(event,sendEvent,reply){
    // reply();      -- Continue without replying to the server.
    // reply(value); -- Send  value  back to the server.
    // sendEvent     -- Function that sends a message { Event : value } to the server.

    console_log("Event: %s",JSON.stringify(event));
    for(var key in event){
      switch(key){

      case "CallDeferredFunction": {
        // FIXME: CallDeferredFunction probably doesn't work right now.
        var call        = event.CallDeferredFunction;
        var closure     = call[0];
        var theFunction = eval(call[1]);
        var params      = call[2];
        theFunction.apply(window, params.concat(function(){
          console_log(this);
          var args = Array.prototype.slice.call(arguments,0);
          sendEvent(closure[0],closure[1],args);
        }));
        reply();
        break;
      }
      case "RunJSFunction": {
        eval(event.RunJSFunction);
        reply();
        break;
      }
      case "CallJSFunction": {
        var result = eval(event.CallJSFunction);
        reply({FunctionResult : result});
        break;
      }
      case "Delete": {
        deleteElid(event.Delete);
        reply();
        break;
      }
      case "Debug": {
        if(window.console)
          console.log("Server debug: %o",event.Debug);
        reply();
        break;
      }
      case "GetElementsByTagName": {
        var elements = document.getElementsByTagName(event.GetElementsByTagName);
        var els = [];
        var len = elements.length;
        for(var i = 0; i < len; i++) {
          els.push({
            Element: elementToElid(elements[i])
          });
        }
        reply({ Elements: els });
        break;
      }
      case "GetElementsById": {
        // Note that this is the html ID, not the elid that is the key of the el_table.
        var ids = event.GetElementsById;
        var els = [];
        for(var i = 0; i < ids.length; i++) {
            var match = document.getElementById(ids[i]);
            if (match != null) {
                els.push({
                  Element: elementToElid(match)
                });
            }
        }
        reply({ Elements: els });
        break;
      }
      case "GetElementsByClassName": {
        var elements = document.getElementsByClassName(event.GetElementsByClassName);
        var els = [];
        var len = elements.length;
        for(var i = 0; i < len; i++) {
          els.push({
            Element: elementToElid(elements[i])
          });
        }
        reply({ Elements: els });
        break;
      }
      case "SetStyle": {
        var set = event.SetStyle;
        var id = set[0];
        var style = set[1];
        var el = elidToElement(id);
        var len = style.length;
        for(var i = 0; i < len; i++){
          el.style[style[i][0]] = style[i][1];
        }
        reply();
        break;
      }
      case "SetAttr": {
        var set   = event.SetAttr;
        var id    = set[0];
        var key   = set[1];
        var value = set[2];
        var el    = elidToElement(id);
        $(el).attr(key,value);
        reply();
        break;
      }
      case "GetValue": {
        var id = event.GetValue;
        var el = elidToElement(id);
        var value = $(el).val();
        reply({ Value: value });
        break;
      }
      case "GetValues": {
        var ids = event.GetValues;
        var len = ids.length;
        var values = [];
        for(var i = 0; i < len; i++) {
          values.push($(elidToElement(ids[i])).val());
        }
        reply({ Values: values });
        break;
      }
      case "Append": {
        var append = event.Append;
        $(elidToElement(append[0])).append($(elidToElement(append[1])));
        reply();
        break;
      }
      case "SetText": {
        var set = event.SetText;
        $(elidToElement(set[0])).text(set[1]);
        reply();
        break;
      }
      case "SetTitle": {
        document.title = event.SetTitle;
        reply();
        break;
      }
      case "SetHtml": {
        var set = event.SetHtml;
        $(elidToElement(set[0])).html(set[1]);
        reply();
        break;
      }
      case "Bind": {
        var bind        = event.Bind;
        var eventType   = bind[0];
        var elid        = bind[1];
        var el          = elidToElement(elid);
        console_log('event type: ' + eventType);
        if(eventType == 'livechange') {
          $(el).livechange(300,function(e){
            sendEvent(elid,eventType, [$(el).val()]);
            return true;
          });
        } else if(eventType == 'sendvalue') {
          $(el).sendvalue(function(x){
            sendEvent(elid,eventType, [x]);
          });
        } else if(eventType.match('dragstart|dragenter|dragover|dragleave|drag|drop|dragend')) {
          $(el).bind(eventType,function(e){
            sendEvent(elid,eventType,
                e.originalEvent.dataTransfer
                    ? [e.originalEvent.dataTransfer.getData("dragData")]
                    : []
              );
            return true;
          });
        } else if(eventType.match('mousemove')) {
          $(el).bind(eventType,function(e){
            sendEvent(elid,eventType, [e.pageX.toString(), e.pageY.toString()]);
            return true;
          });
        } else if(eventType.match('keydown|keyup')) {
          $(el).bind(eventType,function(e){
            sendEvent(elid,eventType, [e.keyCode.toString()]);
            return true;
          });
        } else {
          $(el).bind(eventType,function(e){
            sendEvent(elid,eventType, e.which ? [e.which.toString()] : []);
            return true;
          });
        }
        reply();
        break;
      }
      default: reply();
      }
    }
  }

  ////////////////////////////////////////////////////////////////////////////////
  // FFI - marshaling

  // When the server creates elements, it assigns them a string "elid".
  // This elidToElement function is used to sync the elids on the server with the
  // elids on this client code.  Lookups on elids that do not already exist in the client
  // table are created and added automatically.
  function elidToElement(elid){
    if(elid == 'body')
      return document.body;
    else if(elid == 'head')
      return document.head;
    else if(el_table[elid]){
      return el_table[elid];
    } else {
      if(elid[0] == '*'){
        var create = elid.split(':');
        var element = document.createElement(create[1]);
        element.elid   = elid;
        el_table[elid] = element;
        return element;
      } else {
        throw "Unknown element: " + elid;
      }
    }
  }

  // Get/generate a elid for an element.  This function is used for cases in which the
  // element is accessed without knowing an elid from the server, such as when the
  // element is retrieved by type or html ID attribute.  The element is then added to
  // elid lookup table using the new elid.
  // Note: The mapping between  elids  and  DOM elements  must be bijective.
  function elementToElid(element){
    if(element.elid) {
        return element.elid;
	  }
	  else if (element === document.body) {
        return "body";
    }
	  else if (element === document.head) {
        return "head";
    }
    else {
        var elid = "!" + element_count.toString();
        element_count++;
        element.elid   = elid;
        el_table[elid] = element;
        return elid;
    }
  }

  // Delete element from the table
  function deleteElid(elid){
    var el = el_table[elid];
    if (el) {
      $(el).detach(); // Should be detached already, but make sure
      delete el_table[elid];
    }
  }

  ////////////////////////////////////////////////////////////////////////////////
  // FFI - additional primitive functions

  window.jquery_animate = function(el_id,props,duration,easing,complete){
    var el = elidToElement(JSON.parse(el_id));
    $(el).animate(JSON.parse(props),
                  duration * 1,
                  easing * 1,
                  complete);
  }

  window.jquery_scrollToBottom = function(el){
    $(el).scrollTop(el.scrollHeight);
  };

  function prim_audio_stop(audio){
    audio.pause();
    audio.currentTime = 0;
  }

  // see http://stackoverflow.com/a/9722502/403805
  CanvasRenderingContext2D.prototype.clear =
    CanvasRenderingContext2D.prototype.clear || function (preserveTransform) {
      if (preserveTransform) {
        this.save();
        this.setTransform(1, 0, 0, 1, 0, 0);
      }

      this.clearRect(0, 0, this.canvas.width, this.canvas.height);

      if (preserveTransform) {
        this.restore();
      }
  };

})();
<commit_msg>Remove possibility of returning 'elid' for elements that have not been created by the server. This affects 'getElementByTag', but is necessary to ensure that the server has full control over garbage collection.<commit_after>$.fn.sendvalue = function(trigger){
  $(this).each(function(){
    var self = this;
    var el = $(self);
    el.keydown(function(e){
      if(e.which == 13) {
        trigger.call(self,el.val());
        return false;
      }
      else
        return true;
    });
  });
};

$.fn.livechange = function(ms,trigger){
  $(this).each(function(){
    var self = this;
    var el = $(self);
    var last_val;
    var check = function(){
      var val = el.val();
      if(val != last_val)
        trigger.call(self);
      last_val = val;
    };
    var checker;
    var restart = function(){
      clearTimeout(checker);
      checker = setInterval(check,ms);
    };
    restart();
    el.keypress(restart).change(restart);
  });
};

(function(){

  ////////////////////////////////////////////////////////////////////////////////
  // State
  var sessionToken = null;
  var el_table = {};
  var tp_enable_log = $.cookie('tp_log') == "true";
  var signal_count = 0;

  document.head = document.head || document.getElementsByTagName('head')[0];

  ////////////////////////////////////////////////////////////////////////////////
  // Logging
  window.do_logging = function(x){
    $.cookie('tp_log',x.toString());
  };

  function console_log(){
    if (tp_enable_log) { window.console.log.apply(window.console,arguments); }
  }

  ////////////////////////////////////////////////////////////////////////////////
  // Main entry point
  $(document).ready(function(){
    // initCommunicationHTTP();
    initCommunicationWebSockets();
  });

  ////////////////////////////////////////////////////////////////////////////////
  // Client-server communication
  // - GET and POST requests

  // Initialize communication via HTTP requests.
  function initCommunicationHTTP() {
    setTimeout(function(){
      waitForEvents();
    })
  }

  // Poll instruction from the server.
  function waitForEvents(){
    console_log("Polling… (%d signals so far)",signal_count);
    var data = { token: sessionToken };
    var cmd = sessionToken != null? 'poll' : 'init';
    if(cmd == 'init')
      data.info = window.location.href;
    var req = $.ajax({
      dataType: 'json',
      url: cmd,
      data: data,
      success: function(events){
        if(sessionToken == null) {
          sessionToken = req.getResponseHeader('Set-Token').match(/[0-9]+/)*1;
        }
        console_log("Running event" +(events.length>1?'s':'') +"…")
        if(events.length){
          console_log('Event list:');
          runMultipleEvents(events);
        } else {
          runEvent(events, signalEvent, function(response){
            maybeReply(response, waitForEvents);
          });
        }
      },
      error: function(reply){
        console_log("Error, waiting…");
        setTimeout(function(){
          waitForEvents();
        },5000);
      }
    });
  }

  function runMultipleEvents(events){
    if(events.length == 0) {
      return waitForEvents();
    }
    runEvent(events.shift(), signalEvent, function(response){
      maybeReply(response, function(){
        runMultipleEvents(events);
      });
    });
  }

  // Send an event to the server.
  function signalEvent(value) {
    signal({ Event: value}, function (){});
  }

  // Send a reply to the server if necessary.
  function maybeReply(response, continuation) {
    if (response != undefined) { signal(response, continuation); }
    else { continuation(); }
  }

  // Send response back to the server.
  function signal(signal,continuation){
    signal_count++;
    console_log('Signal: %s',JSON.stringify(signal));
    $.ajax({
      dataType: 'json',
      url:'signal',
      data: { token: sessionToken, signal: JSON.stringify(signal) },
      success: function(){
        continuation();
      },
      error: function(reply){
        console_log("Error: %o",reply);
      }
    });
  }

  ////////////////////////////////////////////////////////////////////////////////
  // Client-server communication
  // - WebSockets

  // Initialize client-server communication via WebSockets.
  function initCommunicationWebSockets() {
    var url = 'ws:' + window.location.href.toString().slice(5) + 'websocket';
    var ws  = new WebSocket(url);

    $(window).unload( function () {
      // Make sure that the WebSocket is closed when the browser window is closed.
      ws.close();
    });

    var sendEvent = function (elid, key, params) {
      ws.send(JSON.stringify({ Event :
          { Element : { Element : elid }
          , EventId : key
          , Params  : params
          }
        }));
    }
    var reply     = function (response) {
      if (response != undefined)
        ws.send(JSON.stringify(response));
    }
    // Send ping message in regular intervals.
    // We expect pong messages in return to keep the connection alive.
    function ping(){
      ws.send("ping");
      window.setTimeout(ping,2000);
    }

    ws.onopen = function (e){
      ping();
      ws.onmessage = function (msg) {
        // console_log("WebSocket message: %o",msg);
        if (msg.data != "pong")
          { runEvent(JSON.parse(msg.data), sendEvent, reply); }
      }
      ws.onclose = function (e) {
        console_log("WebSocket closed: %o", e);
      }
      ws.onerror = function (e) {
        console_log("WebSocket error: %o", e);
      }
    }
  }

  ////////////////////////////////////////////////////////////////////////////////
  // FFI - Execute and reply to commands from the server

  function runEvent(event,sendEvent,reply){
    // reply();      -- Continue without replying to the server.
    // reply(value); -- Send  value  back to the server.
    // sendEvent     -- Function that sends a message { Event : value } to the server.

    console_log("Event: %s",JSON.stringify(event));
    for(var key in event){
      switch(key){

      case "CallDeferredFunction": {
        // FIXME: CallDeferredFunction probably doesn't work right now.
        var call        = event.CallDeferredFunction;
        var closure     = call[0];
        var theFunction = eval(call[1]);
        var params      = call[2];
        theFunction.apply(window, params.concat(function(){
          console_log(this);
          var args = Array.prototype.slice.call(arguments,0);
          sendEvent(closure[0],closure[1],args);
        }));
        reply();
        break;
      }
      case "RunJSFunction": {
        eval(event.RunJSFunction);
        reply();
        break;
      }
      case "CallJSFunction": {
        var result = eval(event.CallJSFunction);
        reply({FunctionResult : result});
        break;
      }
      case "Delete": {
        deleteElid(event.Delete);
        reply();
        break;
      }
      case "Debug": {
        if(window.console)
          console.log("Server debug: %o",event.Debug);
        reply();
        break;
      }
      case "GetElementsByTagName": {
        var elements = document.getElementsByTagName(event.GetElementsByTagName);
        var els = [];
        var len = elements.length;
        for(var i = 0; i < len; i++) {
          els.push({
            Element: elementToElid(elements[i])
          });
        }
        reply({ Elements: els });
        break;
      }
      case "GetElementsById": {
        // Note that this is the html ID, not the elid that is the key of the el_table.
        var ids = event.GetElementsById;
        var els = [];
        for(var i = 0; i < ids.length; i++) {
            var match = document.getElementById(ids[i]);
            if (match != null) {
                els.push({
                  Element: elementToElid(match)
                });
            }
        }
        reply({ Elements: els });
        break;
      }
      case "GetElementsByClassName": {
        var elements = document.getElementsByClassName(event.GetElementsByClassName);
        var els = [];
        var len = elements.length;
        for(var i = 0; i < len; i++) {
          els.push({
            Element: elementToElid(elements[i])
          });
        }
        reply({ Elements: els });
        break;
      }
      case "SetStyle": {
        var set = event.SetStyle;
        var id = set[0];
        var style = set[1];
        var el = elidToElement(id);
        var len = style.length;
        for(var i = 0; i < len; i++){
          el.style[style[i][0]] = style[i][1];
        }
        reply();
        break;
      }
      case "SetAttr": {
        var set   = event.SetAttr;
        var id    = set[0];
        var key   = set[1];
        var value = set[2];
        var el    = elidToElement(id);
        $(el).attr(key,value);
        reply();
        break;
      }
      case "GetValue": {
        var id = event.GetValue;
        var el = elidToElement(id);
        var value = $(el).val();
        reply({ Value: value });
        break;
      }
      case "GetValues": {
        var ids = event.GetValues;
        var len = ids.length;
        var values = [];
        for(var i = 0; i < len; i++) {
          values.push($(elidToElement(ids[i])).val());
        }
        reply({ Values: values });
        break;
      }
      case "Append": {
        var append = event.Append;
        $(elidToElement(append[0])).append($(elidToElement(append[1])));
        reply();
        break;
      }
      case "SetText": {
        var set = event.SetText;
        $(elidToElement(set[0])).text(set[1]);
        reply();
        break;
      }
      case "SetTitle": {
        document.title = event.SetTitle;
        reply();
        break;
      }
      case "SetHtml": {
        var set = event.SetHtml;
        $(elidToElement(set[0])).html(set[1]);
        reply();
        break;
      }
      case "Bind": {
        var bind        = event.Bind;
        var eventType   = bind[0];
        var elid        = bind[1];
        var el          = elidToElement(elid);
        console_log('event type: ' + eventType);
        if(eventType == 'livechange') {
          $(el).livechange(300,function(e){
            sendEvent(elid,eventType, [$(el).val()]);
            return true;
          });
        } else if(eventType == 'sendvalue') {
          $(el).sendvalue(function(x){
            sendEvent(elid,eventType, [x]);
          });
        } else if(eventType.match('dragstart|dragenter|dragover|dragleave|drag|drop|dragend')) {
          $(el).bind(eventType,function(e){
            sendEvent(elid,eventType,
                e.originalEvent.dataTransfer
                    ? [e.originalEvent.dataTransfer.getData("dragData")]
                    : []
              );
            return true;
          });
        } else if(eventType.match('mousemove')) {
          $(el).bind(eventType,function(e){
            sendEvent(elid,eventType, [e.pageX.toString(), e.pageY.toString()]);
            return true;
          });
        } else if(eventType.match('keydown|keyup')) {
          $(el).bind(eventType,function(e){
            sendEvent(elid,eventType, [e.keyCode.toString()]);
            return true;
          });
        } else {
          $(el).bind(eventType,function(e){
            sendEvent(elid,eventType, e.which ? [e.which.toString()] : []);
            return true;
          });
        }
        reply();
        break;
      }
      default: reply();
      }
    }
  }

  ////////////////////////////////////////////////////////////////////////////////
  // FFI - marshaling

  // When the server creates elements, it assigns them a string "elid".
  // This elidToElement function is used to sync the elids on the server with the
  // elids on this client code.  Lookups on elids that do not already exist in the client
  // table are created and added automatically.
  function elidToElement(elid){
    if(elid == 'body')
      return document.body;
    else if(elid == 'head')
      return document.head;
    else if(el_table[elid])
      return el_table[elid];
    else {
      if(elid[0] == '*'){
        var create = elid.split(':');
        var element = document.createElement(create[1]);
        element.elid   = elid;
        el_table[elid] = element;
        return element;
      } else {
        throw "Unknown element: " + elid;
      }
    }
  }

  // Get/generate a elid for an element.  This function is used for cases in which the
  // element is accessed without knowing an elid from the server, such as when the
  // element is retrieved by type or html ID attribute.  The element is then added to
  // elid lookup table using the new elid.
  // Note: The mapping between  elids  and  DOM elements  must be bijective.
  function elementToElid(element){
    if(element.elid)
      return element.elid;
	  else if (element === document.body)
      return "body";
	  else if (element === document.head)
      return "head";
    else {
      throw "Element requested, but does not have elid: " + element;
    }
  }

  // Delete element from the table
  function deleteElid(elid){
    var el = el_table[elid];
    if (el) {
      $(el).detach(); // Should be detached already, but make sure
      delete el_table[elid];
    }
  }

  ////////////////////////////////////////////////////////////////////////////////
  // FFI - additional primitive functions

  window.jquery_animate = function(el_id,props,duration,easing,complete){
    var el = elidToElement(JSON.parse(el_id));
    $(el).animate(JSON.parse(props),
                  duration * 1,
                  easing * 1,
                  complete);
  }

  window.jquery_scrollToBottom = function(el){
    $(el).scrollTop(el.scrollHeight);
  };

  function prim_audio_stop(audio){
    audio.pause();
    audio.currentTime = 0;
  }

  // see http://stackoverflow.com/a/9722502/403805
  CanvasRenderingContext2D.prototype.clear =
    CanvasRenderingContext2D.prototype.clear || function (preserveTransform) {
      if (preserveTransform) {
        this.save();
        this.setTransform(1, 0, 0, 1, 0, 0);
      }

      this.clearRect(0, 0, this.canvas.width, this.canvas.height);

      if (preserveTransform) {
        this.restore();
      }
  };

})();
<|endoftext|>


<commit_before><commit_msg>Fixed TypeError: `color` is expected to have type `string` https://github.com/kidoju/Kidoju-Widgets/issues/162<commit_after><|endoftext|>


<commit_before><commit_msg>Revert "Adding EST to formattedDate"<commit_after><|endoftext|>


<commit_before>steal('can/util', 'can/model', 'can/model/list', 'can/observe/attributes', function(can) {

module("can/observe/attributes");

test("literal converters and serializes", function(){
	can.Observe("Task1",{
		attributes: {
			createdAt: "date"
		},
		convert: {
			date: function(d){
				var months = ["jan", "feb", "mar"]
				return months[d.getMonth()]
			}
		},
		serialize: {
			date: function(d){
				var months = {"jan":0, "feb":1, "mar":2}
				return months[d]
			}
		}
	},{});
	can.Observe("Task2",{
		attributes: {
			createdAt: "date"
		},
		convert: {
			date: function(d){
				var months = ["apr", "may", "jun"]
				return months[d.getMonth()]
			}
		},
		serialize: {
			date: function(d){
				var months = {"apr":0, "may":1, "jun":2}
				return months[d]
			}
		}
	},{});
	var d = new Date();
	d.setMonth(1, 1)
	var task1=new Task1({
		createdAt: d,
		name:"Task1"
	});
	d.setMonth(2, 1)
	var task2=new Task2({
		createdAt: d,
		name:"Task2"
	});
	equals(task1.createdAt, "feb", "Task1 model convert");
	equals(task2.createdAt, "jun", "Task2 model convert");
	equals(task1.serialize().createdAt, 1, "Task1 model serialize");
	equals(task2.serialize().createdAt, 2, "Task2 model serialize");
	equals(task1.serialize().name, "Task1", "Task1 model default serialized");
	equals(task2.serialize().name, "Task2", "Task2 model default serialized");
});

var makeClasses= function(){
	can.Observe("AttrTest.Person", {
		serialize: function() {
			return "My name is " + this.name;
		}
	});
	can.Observe("AttrTest.Loan");
	can.Observe("AttrTest.Issue");

	AttrTest.Person.model = function(data){
		return new this(data);
	}
	AttrTest.Loan.models = function(data){
		return can.map(data, function(l){
			return new AttrTest.Loan(l)
		});
	}
	AttrTest.Issue.models = function(data){
		return can.map(data, function(l){
			return new AttrTest.Issue(l)
		});
	}
	can.Observe("AttrTest.Customer",
	{
		attributes : {
			person : "AttrTest.Person.model",
			loans : "AttrTest.Loan.models",
			issues : "AttrTest.Issue.models"
		}
	},
	{});
}

test("default converters", function(){
	var num = 1318541064012;
	equals( can.Observe.convert.date(num).getTime(), num, "converted to a date with a number" );
})

test("basic observe associations", function(){
	makeClasses();

	var c = new AttrTest.Customer({
		person : {
			id: 1,
			name: "Justin"
		},
		issues : [],
		loans : [
			{
				amount : 1000,
				id: 2
			},
			{
				amount : 19999,
				id: 3
			}
		]
	});

	equals(c.person.name, "Justin", "association present");

	equals(c.person.constructor, AttrTest.Person, "belongs to association typed");

	equals(c.issues.length, 0);

	equals(c.loans.length, 2);

	equals(c.loans[0].constructor, AttrTest.Loan);

});

test("single seralize w/ attr name", function(){
	var Breakfast = can.Observe({
		attributes: {
			time: "date"
		},
		serialize: {
			date: function(d){
				return d.getTime();
			}
		}
	},{});

	var time = new Date();
	var b = new Breakfast({
		time: time
	});

	equals(b.serialize('time'), time.getTime());
});

test("defaults", function(){
	var Zelda = can.Observe({
		defaults: {
			sword: 'Wooden Sword',
			shield: false,
			hearts: 3,
			rupees: 0
		}
	},{});

	var link = new Zelda({
		rupees: 255
	});

	equals(link.attr('sword'), 'Wooden Sword');
	equals(link.attr('rupees'), 255);
});

test("nested model attr", function(){
  can.Model('NestedAttrTest.User', {}, {});

  can.Model('NestedAttrTest.Task', {
      attributes : {
        owner : "NestedAttrTest.User.model"
      }
    }, {});

  can.Model('NestedAttrTest.Project',{
      attributes : {
        creator : "NestedAttrTest.User.model"
      }
    }, {});

    var michael = NestedAttrTest.User.model({ id : 17, name : 'Michael'});
    var amy = NestedAttrTest.User.model({ id : 29, name : 'Amy'});

    // add bindings so the objects get stored in the User.store
    michael.bind('foo', function(){});
    amy.bind('foo', function(){});

    var task = NestedAttrTest.Task.model({
      id : 1,
      name : "Do it!",
      owner : {id : 17}
    });

    var project = NestedAttrTest.Project.model({
      id : 1,
      name : "Get Things Done",
      creator : {id : 17}
    });

    task.bind('foo', function(){});
    project.bind('foo', function(){});

    equal(task.attr('owner.name'), 'Michael', 'owner hash correctly modeled');
    equal(project.attr('creator.name'), 'Michael', 'creator hash correctly modeled');

    task.attr({ owner : { id : 29, name : 'Amy'}});
    equal(task.attr('owner.name'), 'Amy', 'Task correctly updated to Amy user model');
    equal(task.attr('owner.id'), 29, 'Task correctly updated to Amy user model');

    equal(project.attr('creator.name'), 'Michael', 'Project creator should still be Michael');
    equal(project.attr('creator.id'), 17, 'Project creator should still be Michael');
    equal(NestedAttrTest.User.store[17].id, 17, "The model store should still have Michael associated by his id");
});

test("attr() should respect convert functions for lists when updating", function(){
  can.Model('ListTest.User', {}, {});
  can.Model.List('ListTest.User.List', {}, {});

  can.Model('ListTest.Task', {
    attributes : {
      project : "ListTest.Project.model"
    }
  }, {});

  can.Model('ListTest.Project',{
      attributes : {
        members : "ListTest.User.models"
      }
    }, {});

    var task = ListTest.Task.model({
      id : 1,
      name : "Do it!",
      project : {
        id : 789,
        name : "Get stuff done",
        members : []
      }
    });

    equal(task.project.members instanceof ListTest.User.List, true, "the list is a User List");

    task.attr({
      id : 1,
      project : {
        id : 789,
        members: [{ id : 72, name : "Andy"}, { id : 74, name : "Michael"}]
      }
    });

    equal(task.project.members instanceof ListTest.User.List, true, "the list is a User List");
    equal(task.project.members.length, 2, "The members were added");
    equal(task.project.members[0] instanceof ListTest.User, true, "The members was converted to a model object");
    equal(task.project.members[1] instanceof ListTest.User, true, "The user was converted to a model object");
});

test("plugin passes old value to converter", 2, function() {
	var Ob = can.Observe('AttrOldVal', {
		oldVal : function(val, oldVal) {
			if(val === 'first') {
				ok(!oldVal, 'First time does not have an old value');
			}
			if(val === 'second') {
				equal(oldVal, 'first', 'Old value is correct');
			}
			return val;
		},
		attributes : {
			test : 'AttrOldVal.oldVal'
		}
	}, {});

	var o = new Ob({
		test : 'first'
	});

	o.attr('test', 'second');
});

test("attr does not blow away old observable when going from empty to having items (#160)", function(){
	can.Model('EmptyListTest.User', {}, {});
	can.Model.List('EmptyListTest.User.List', {}, {});

	can.Model('EmptyListTest.Project',{
		attributes : {
			members : "EmptyListTest.User.models"
		}
	}, {});

	var project = EmptyListTest.Project.model({
		id : 789,
		members : []
	});

	var oldCid = project.attr("members")._cid;
	project.attr({members:['bob']});
	same(project.attr("members")._cid, oldCid, "should be the same observe, so that views bound to the old one get updates")
	equals(project.attr("members").length, 1, "list should have bob in it");
});

test("Default converters and boolean fix (#247)", function() {
	var MyObserve = can.Observe({
			attributes: {
				enabled: 'boolean',
				time: 'date',
				age: 'number'
			}
		}, {}),
		obs = new MyObserve({
			enabled: 'false',
			time: 1358980553275,
			age: '26'
		});

	deepEqual(obs.attr('enabled'), false, "Attribute got converted to boolean false");
	obs.attr('enabled', 'true');
	deepEqual(obs.attr('enabled'), true, "Attribute got converted to boolean true");

	obs.attr('enabled', '0');
	deepEqual(obs.attr('enabled'), false, "Attribute got converted to boolean false");
	obs.attr('enabled', '1');
	deepEqual(obs.attr('enabled'), true, "Attribute got converted to boolean true");

	deepEqual(obs.attr('age'), 26, "Age converted from string to number");
	equal(obs.attr('time').toString().indexOf('Wed Jan 23 2013 15:35:53'), 0, "Attribute is expected date");
});

})();<commit_msg>Just check for date instance.<commit_after>steal('can/util', 'can/model', 'can/model/list', 'can/observe/attributes', function(can) {

module("can/observe/attributes");

test("literal converters and serializes", function(){
	can.Observe("Task1",{
		attributes: {
			createdAt: "date"
		},
		convert: {
			date: function(d){
				var months = ["jan", "feb", "mar"]
				return months[d.getMonth()]
			}
		},
		serialize: {
			date: function(d){
				var months = {"jan":0, "feb":1, "mar":2}
				return months[d]
			}
		}
	},{});
	can.Observe("Task2",{
		attributes: {
			createdAt: "date"
		},
		convert: {
			date: function(d){
				var months = ["apr", "may", "jun"]
				return months[d.getMonth()]
			}
		},
		serialize: {
			date: function(d){
				var months = {"apr":0, "may":1, "jun":2}
				return months[d]
			}
		}
	},{});
	var d = new Date();
	d.setMonth(1, 1)
	var task1=new Task1({
		createdAt: d,
		name:"Task1"
	});
	d.setMonth(2, 1)
	var task2=new Task2({
		createdAt: d,
		name:"Task2"
	});
	equals(task1.createdAt, "feb", "Task1 model convert");
	equals(task2.createdAt, "jun", "Task2 model convert");
	equals(task1.serialize().createdAt, 1, "Task1 model serialize");
	equals(task2.serialize().createdAt, 2, "Task2 model serialize");
	equals(task1.serialize().name, "Task1", "Task1 model default serialized");
	equals(task2.serialize().name, "Task2", "Task2 model default serialized");
});

var makeClasses= function(){
	can.Observe("AttrTest.Person", {
		serialize: function() {
			return "My name is " + this.name;
		}
	});
	can.Observe("AttrTest.Loan");
	can.Observe("AttrTest.Issue");

	AttrTest.Person.model = function(data){
		return new this(data);
	}
	AttrTest.Loan.models = function(data){
		return can.map(data, function(l){
			return new AttrTest.Loan(l)
		});
	}
	AttrTest.Issue.models = function(data){
		return can.map(data, function(l){
			return new AttrTest.Issue(l)
		});
	}
	can.Observe("AttrTest.Customer",
	{
		attributes : {
			person : "AttrTest.Person.model",
			loans : "AttrTest.Loan.models",
			issues : "AttrTest.Issue.models"
		}
	},
	{});
}

test("default converters", function(){
	var num = 1318541064012;
	equals( can.Observe.convert.date(num).getTime(), num, "converted to a date with a number" );
})

test("basic observe associations", function(){
	makeClasses();

	var c = new AttrTest.Customer({
		person : {
			id: 1,
			name: "Justin"
		},
		issues : [],
		loans : [
			{
				amount : 1000,
				id: 2
			},
			{
				amount : 19999,
				id: 3
			}
		]
	});

	equals(c.person.name, "Justin", "association present");

	equals(c.person.constructor, AttrTest.Person, "belongs to association typed");

	equals(c.issues.length, 0);

	equals(c.loans.length, 2);

	equals(c.loans[0].constructor, AttrTest.Loan);

});

test("single seralize w/ attr name", function(){
	var Breakfast = can.Observe({
		attributes: {
			time: "date"
		},
		serialize: {
			date: function(d){
				return d.getTime();
			}
		}
	},{});

	var time = new Date();
	var b = new Breakfast({
		time: time
	});

	equals(b.serialize('time'), time.getTime());
});

test("defaults", function(){
	var Zelda = can.Observe({
		defaults: {
			sword: 'Wooden Sword',
			shield: false,
			hearts: 3,
			rupees: 0
		}
	},{});

	var link = new Zelda({
		rupees: 255
	});

	equals(link.attr('sword'), 'Wooden Sword');
	equals(link.attr('rupees'), 255);
});

test("nested model attr", function(){
  can.Model('NestedAttrTest.User', {}, {});

  can.Model('NestedAttrTest.Task', {
      attributes : {
        owner : "NestedAttrTest.User.model"
      }
    }, {});

  can.Model('NestedAttrTest.Project',{
      attributes : {
        creator : "NestedAttrTest.User.model"
      }
    }, {});

    var michael = NestedAttrTest.User.model({ id : 17, name : 'Michael'});
    var amy = NestedAttrTest.User.model({ id : 29, name : 'Amy'});

    // add bindings so the objects get stored in the User.store
    michael.bind('foo', function(){});
    amy.bind('foo', function(){});

    var task = NestedAttrTest.Task.model({
      id : 1,
      name : "Do it!",
      owner : {id : 17}
    });

    var project = NestedAttrTest.Project.model({
      id : 1,
      name : "Get Things Done",
      creator : {id : 17}
    });

    task.bind('foo', function(){});
    project.bind('foo', function(){});

    equal(task.attr('owner.name'), 'Michael', 'owner hash correctly modeled');
    equal(project.attr('creator.name'), 'Michael', 'creator hash correctly modeled');

    task.attr({ owner : { id : 29, name : 'Amy'}});
    equal(task.attr('owner.name'), 'Amy', 'Task correctly updated to Amy user model');
    equal(task.attr('owner.id'), 29, 'Task correctly updated to Amy user model');

    equal(project.attr('creator.name'), 'Michael', 'Project creator should still be Michael');
    equal(project.attr('creator.id'), 17, 'Project creator should still be Michael');
    equal(NestedAttrTest.User.store[17].id, 17, "The model store should still have Michael associated by his id");
});

test("attr() should respect convert functions for lists when updating", function(){
  can.Model('ListTest.User', {}, {});
  can.Model.List('ListTest.User.List', {}, {});

  can.Model('ListTest.Task', {
    attributes : {
      project : "ListTest.Project.model"
    }
  }, {});

  can.Model('ListTest.Project',{
      attributes : {
        members : "ListTest.User.models"
      }
    }, {});

    var task = ListTest.Task.model({
      id : 1,
      name : "Do it!",
      project : {
        id : 789,
        name : "Get stuff done",
        members : []
      }
    });

    equal(task.project.members instanceof ListTest.User.List, true, "the list is a User List");

    task.attr({
      id : 1,
      project : {
        id : 789,
        members: [{ id : 72, name : "Andy"}, { id : 74, name : "Michael"}]
      }
    });

    equal(task.project.members instanceof ListTest.User.List, true, "the list is a User List");
    equal(task.project.members.length, 2, "The members were added");
    equal(task.project.members[0] instanceof ListTest.User, true, "The members was converted to a model object");
    equal(task.project.members[1] instanceof ListTest.User, true, "The user was converted to a model object");
});

test("plugin passes old value to converter", 2, function() {
	var Ob = can.Observe('AttrOldVal', {
		oldVal : function(val, oldVal) {
			if(val === 'first') {
				ok(!oldVal, 'First time does not have an old value');
			}
			if(val === 'second') {
				equal(oldVal, 'first', 'Old value is correct');
			}
			return val;
		},
		attributes : {
			test : 'AttrOldVal.oldVal'
		}
	}, {});

	var o = new Ob({
		test : 'first'
	});

	o.attr('test', 'second');
});

test("attr does not blow away old observable when going from empty to having items (#160)", function(){
	can.Model('EmptyListTest.User', {}, {});
	can.Model.List('EmptyListTest.User.List', {}, {});

	can.Model('EmptyListTest.Project',{
		attributes : {
			members : "EmptyListTest.User.models"
		}
	}, {});

	var project = EmptyListTest.Project.model({
		id : 789,
		members : []
	});

	var oldCid = project.attr("members")._cid;
	project.attr({members:['bob']});
	same(project.attr("members")._cid, oldCid, "should be the same observe, so that views bound to the old one get updates")
	equals(project.attr("members").length, 1, "list should have bob in it");
});

test("Default converters and boolean fix (#247)", function() {
	var MyObserve = can.Observe({
			attributes: {
				enabled: 'boolean',
				time: 'date',
				age: 'number'
			}
		}, {}),
		obs = new MyObserve({
			enabled: 'false',
			time: 1358980553275,
			age: '26'
		});

	deepEqual(obs.attr('enabled'), false, "Attribute got converted to boolean false");
	obs.attr('enabled', 'true');
	deepEqual(obs.attr('enabled'), true, "Attribute got converted to boolean true");

	obs.attr('enabled', '0');
	deepEqual(obs.attr('enabled'), false, "Attribute got converted to boolean false");
	obs.attr('enabled', '1');
	deepEqual(obs.attr('enabled'), true, "Attribute got converted to boolean true");

	deepEqual(obs.attr('age'), 26, "Age converted from string to number");
	// It's ok to just check if it got converted to a date
	ok(obs.attr('time') instanceof Date, "Attribute is a date");
});

})();<|endoftext|>


<commit_before>let sounds = new Set();
let soundsMap = new Map();

let muted = false;
let loopMuted = false;
let initialized = true;

const MOBILE = /mobi/.test(window.navigator.userAgent.toLowerCase());

if(MOBILE) {
  initialized = false;

  let onTouchEnd = () => {
    window.removeEventListener("touchend", onTouchEnd);
    for (let sound of sounds) {
      sound._audio.play();
      if(!sound._audio.autoplay) {
        let pauseElement = function() {
          sound._audio.pause();
          sound._audio.removeEventListener("playing", pauseElement);
        }
        sound._audio.addEventListener("playing", pauseElement);
      }
    }
    initialized = true;
  };
  window.addEventListener("touchend", onTouchEnd);
}

export default class Sound {
  static set muted(value) {
    muted = value;
    for (let sound of sounds) {
      sound.muted = sound.muted;
    }
  }

  static get muted() {
    return muted;
  }

  static set loopMuted(value) {
    loopMuted = value;
    for (let sound of sounds) {
      sound.muted = sound.muted;
    }
  }

  static get loopMuted() {
    return loopMuted;
  }

  static add(src) {
    let sound = new Sound(src);
    return sound;
  }

  static get(name) {
    return soundsMap.get(name);
  }

  constructor(src, {
    name = /([^\\\/]*)\..*$/.exec(src)[1],
    amplification = 1,
    volume = 1,
    loop = false,
    autoplay = false
  } = {}) {
    this.name = name;

    sounds.add(this);
    if(this.name) {
      soundsMap.set(this.name, this);
    }

    this._audio = document.createElement("audio");
    this._audio.src = src;

    this.amplification = amplification;
    this.volume = volume;
    this.loop = loop;
    this.autoplay = autoplay;

    this.muted = muted;
  }

  get src() {
    return this._audio.src;
  }

  set src(value) {
    this._audio.src = value;
  }

  get muted() {
    return this._muted;
  }

  set muted(value) {
    this._muted = value;
    this._audio.muted = muted || loopMuted && this.loop ? true : value;
  }

  get paused() {
    return this._audio.paused;
  }

  get loop() {
    return this._audio.loop;
  }

  set loop(value) {
    this.muted = this.muted;
    this._audio.loop = value;
  }

  get currentTime() {
    return this._audio.currentTime;
  }

  set currentTime(value) {
    this._audio.currentTime = value;
  }

  get autoplay() {
    return this._audio.autoplay;
  }

  set autoplay(value) {
    this._audio.autoplay = value;
  }

  get duration() {
    return this._audio.duration;
  }

  set duration(value) {
    this._audio.duration = value;
  }

  get volume() {
    return this._volume;
  }

  set volume(value) {
    this._volume = value;
    this._audio.volume = this._volume * this.amplification;
  }

  play() {
    if(!initialized) {
      return;
    }
    this._audio.play();
  }

  stop() {
    this.currentTime = 0;
    this.pause();
  }

  pause() {
    this._audio.pause();
  }

  cloneNode() {
    let sound = new Sound(this.src, {
      name: null,
      volume: this.volume,
      amplification: this.amplification,
    });
    sound.muted = this.muted;
    sound.loop = this.loop;
    sound.currentTime = this.currentTime;

    return sound;
  }
}

Sound.muted = /\bmuted\b/.test(window.location.search);
Sound.loopMuted = /\bloopmuted\b/.test(window.location.search);
<commit_msg>pass src as an object parameter in Sound<commit_after>let sounds = new Set();
let soundsMap = new Map();

let muted = false;
let loopMuted = false;
let initialized = true;

const MOBILE = /mobi/.test(window.navigator.userAgent.toLowerCase());

if(MOBILE) {
  initialized = false;

  let onTouchEnd = () => {
    window.removeEventListener("touchend", onTouchEnd);
    for (let sound of sounds) {
      sound._audio.play();
      if(!sound._audio.autoplay) {
        let pauseElement = function() {
          sound._audio.pause();
          sound._audio.removeEventListener("playing", pauseElement);
        }
        sound._audio.addEventListener("playing", pauseElement);
      }
    }
    initialized = true;
  };
  window.addEventListener("touchend", onTouchEnd);
}

export default class Sound {
  static set muted(value) {
    muted = value;
    for (let sound of sounds) {
      sound.muted = sound.muted;
    }
  }

  static get muted() {
    return muted;
  }

  static set loopMuted(value) {
    loopMuted = value;
    for (let sound of sounds) {
      sound.muted = sound.muted;
    }
  }

  static get loopMuted() {
    return loopMuted;
  }

  static add(src) {
    let sound = new Sound(src);
    return sound;
  }

  static get(name) {
    return soundsMap.get(name);
  }

  constructor({
    src,
    name = /([^\\\/]*)\..*$/.exec(src)[1],
    amplification = 1,
    volume = 1,
    loop = false,
    autoplay = false
  } = {}) {
    this.name = name;

    sounds.add(this);
    if(this.name) {
      soundsMap.set(this.name, this);
    }

    this._audio = document.createElement("audio");
    this._audio.src = src;

    this.amplification = amplification;
    this.volume = volume;
    this.loop = loop;
    this.autoplay = autoplay;

    this.muted = muted;
  }

  get src() {
    return this._audio.src;
  }

  set src(value) {
    this._audio.src = value;
  }

  get muted() {
    return this._muted;
  }

  set muted(value) {
    this._muted = value;
    this._audio.muted = muted || loopMuted && this.loop ? true : value;
  }

  get paused() {
    return this._audio.paused;
  }

  get loop() {
    return this._audio.loop;
  }

  set loop(value) {
    this.muted = this.muted;
    this._audio.loop = value;
  }

  get currentTime() {
    return this._audio.currentTime;
  }

  set currentTime(value) {
    this._audio.currentTime = value;
  }

  get autoplay() {
    return this._audio.autoplay;
  }

  set autoplay(value) {
    this._audio.autoplay = value;
  }

  get duration() {
    return this._audio.duration;
  }

  set duration(value) {
    this._audio.duration = value;
  }

  get volume() {
    return this._volume;
  }

  set volume(value) {
    this._volume = value;
    this._audio.volume = this._volume * this.amplification;
  }

  play() {
    if(!initialized) {
      return;
    }
    this._audio.play();
  }

  stop() {
    this.currentTime = 0;
    this.pause();
  }

  pause() {
    this._audio.pause();
  }

  cloneNode() {
    let sound = new Sound(this.src, {
      name: null,
      volume: this.volume,
      amplification: this.amplification,
    });
    sound.muted = this.muted;
    sound.loop = this.loop;
    sound.currentTime = this.currentTime;

    return sound;
  }
}

Sound.muted = /\bmuted\b/.test(window.location.search);
Sound.loopMuted = /\bloopmuted\b/.test(window.location.search);
<|endoftext|>


<commit_before>define( ['dojo/_base/declare'],
        function(declare) {

return declare(null, {

defaultStarts: [
    'ATG',
    'CTG',
    'GTG',
],
defaultStops: [
    'TAA',
    'TAG',
    'TGA',
],
defaultCodonTable: {

    "TCA" : "S",
    "TCC" : "S",
    "TCG" : "S",
    "TCT" : "S",
    "TTC" : "F",
    "TTT" : "F",
    "TTA" : "L",
    "TTG" : "L",
    "TAC" : "Y",
    "TAT" : "Y",
    "TAA" : "*",
    "TAG" : "*",
    "TGC" : "C",
    "TGT" : "C",
    "TGA" : "*",
    "TGG" : "W",
    "CTA" : "L",
    "CTC" : "L",
    "CTG" : "L",
    "CTT" : "L",
    "CCA" : "P",
    "CCC" : "P",
    "CCG" : "P",
    "CCT" : "P",
    "CAC" : "H",
    "CAT" : "H",
    "CAA" : "Q",
    "CAG" : "Q",
    "CGA" : "R",
    "CGC" : "R",
    "CGG" : "R",
    "CGT" : "R",
    "ATA" : "I",
    "ATC" : "I",
    "ATT" : "I",
    "ATG" : "M",
    "ACA" : "T",
    "ACC" : "T",
    "ACG" : "T",
    "ACT" : "T",
    "AAC" : "N",
    "AAT" : "N",
    "AAA" : "K",
    "AAG" : "K",
    "AGC" : "S",
    "AGT" : "S",
    "AGA" : "R",
    "AGG" : "R",
    "GTA" : "V",
    "GTC" : "V",
    "GTG" : "V",
    "GTT" : "V",
    "GCA" : "A",
    "GCC" : "A",
    "GCG" : "A",
    "GCT" : "A",
    "GAC" : "D",
    "GAT" : "D",
    "GAA" : "E",
    "GAG" : "E",
    "GGA" : "G",
    "GGC" : "G",
    "GGG" : "G",
    "GGT" : "G"
},

generateCodonTable:function(table) {
    /**
    *  take CodonTable above and generate larger codon table that includes
    *  all permutations of upper and lower case nucleotides
    */
    var tempCodonTable = { };
    for (var codon in table) {
        // looping through codon table, make sure not hitting generic properties...
        if (table.hasOwnProperty(codon)) {
            var aa = table[codon];
            // console.log("Codon: ", codon, ", aa: ", aa);
            var nucs = [];
            for (var i=0; i<3; i++) {
                var nuc = codon.charAt(i);
                nucs[i] = [];
                nucs[i][0] = nuc.toUpperCase();
                nucs[i][1] = nuc.toLowerCase();
            }
            for (var i=0; i<2; i++) {
                var n0 = nucs[0][i];
                for (var j=0; j<2; j++) {
                    var n1 = nucs[1][j];
                    for (var k=0; k<2; k++) {
                        var n2 = nucs[2][k];
                        var triplet = n0 + n1 + n2;
                        tempCodonTable[triplet] = aa;
                    }
                }
            }
        }
    }
    return tempCodonTable;
}

});

});
<commit_msg>Remove trailing commas<commit_after>define( ['dojo/_base/declare'],
        function(declare) {

return declare(null, {

defaultStarts: [
    'ATG',
    'CTG',
    'GTG'
],
defaultStops: [
    'TAA',
    'TAG',
    'TGA'
],
defaultCodonTable: {

    "TCA" : "S",
    "TCC" : "S",
    "TCG" : "S",
    "TCT" : "S",
    "TTC" : "F",
    "TTT" : "F",
    "TTA" : "L",
    "TTG" : "L",
    "TAC" : "Y",
    "TAT" : "Y",
    "TAA" : "*",
    "TAG" : "*",
    "TGC" : "C",
    "TGT" : "C",
    "TGA" : "*",
    "TGG" : "W",
    "CTA" : "L",
    "CTC" : "L",
    "CTG" : "L",
    "CTT" : "L",
    "CCA" : "P",
    "CCC" : "P",
    "CCG" : "P",
    "CCT" : "P",
    "CAC" : "H",
    "CAT" : "H",
    "CAA" : "Q",
    "CAG" : "Q",
    "CGA" : "R",
    "CGC" : "R",
    "CGG" : "R",
    "CGT" : "R",
    "ATA" : "I",
    "ATC" : "I",
    "ATT" : "I",
    "ATG" : "M",
    "ACA" : "T",
    "ACC" : "T",
    "ACG" : "T",
    "ACT" : "T",
    "AAC" : "N",
    "AAT" : "N",
    "AAA" : "K",
    "AAG" : "K",
    "AGC" : "S",
    "AGT" : "S",
    "AGA" : "R",
    "AGG" : "R",
    "GTA" : "V",
    "GTC" : "V",
    "GTG" : "V",
    "GTT" : "V",
    "GCA" : "A",
    "GCC" : "A",
    "GCG" : "A",
    "GCT" : "A",
    "GAC" : "D",
    "GAT" : "D",
    "GAA" : "E",
    "GAG" : "E",
    "GGA" : "G",
    "GGC" : "G",
    "GGG" : "G",
    "GGT" : "G"
},

generateCodonTable:function(table) {
    /**
    *  take CodonTable above and generate larger codon table that includes
    *  all permutations of upper and lower case nucleotides
    */
    var tempCodonTable = { };
    for (var codon in table) {
        // looping through codon table, make sure not hitting generic properties...
        if (table.hasOwnProperty(codon)) {
            var aa = table[codon];
            // console.log("Codon: ", codon, ", aa: ", aa);
            var nucs = [];
            for (var i=0; i<3; i++) {
                var nuc = codon.charAt(i);
                nucs[i] = [];
                nucs[i][0] = nuc.toUpperCase();
                nucs[i][1] = nuc.toLowerCase();
            }
            for (var i=0; i<2; i++) {
                var n0 = nucs[0][i];
                for (var j=0; j<2; j++) {
                    var n1 = nucs[1][j];
                    for (var k=0; k<2; k++) {
                        var n2 = nucs[2][k];
                        var triplet = n0 + n1 + n2;
                        tempCodonTable[triplet] = aa;
                    }
                }
            }
        }
    }
    return tempCodonTable;
}

});

});
<|endoftext|>


<commit_before><commit_msg>reduce complexity (updated eslint rule 4.14.0)<commit_after><|endoftext|>


<commit_before><commit_msg>issue #92: Cache getting clients.<commit_after><|endoftext|>


<commit_before>/**
 * mediaPlayers is a collection of mediaPlayer objects supported by the client.
 *
 * @constructor
 */
( function( mw, $ ) { "use strict";

mw.MediaPlayers = function(){
	this.init();
};

mw.MediaPlayers.prototype = {
	// The list of players supported
	players : null,

	// Store per mime-type preferences for players
	preference : { },

	// Stores the default set of players for a given mime type
	defaultPlayers : { },

	/**
	 * Initialization function sets the default order for players for a given
	 * mime type
	 */
	init: function() {
		this.players = new Array();
		this.loadPreferences();

		// Set up default players order for each library type
		this.defaultPlayers['video/wvm'] = ['NativeComponent'];
		this.defaultPlayers['video/live'] = ['Kplayer'];
		this.defaultPlayers['video/kontiki'] = ['Kplayer'];
		this.defaultPlayers['video/x-flv'] = ['Kplayer', 'Vlc'];
		this.defaultPlayers['video/h264'] = ['NativeComponent', 'Native', 'Kplayer', 'Silverlight', 'Vlc'];
		this.defaultPlayers['video/mp4'] = ['NativeComponent', 'Native', 'Kplayer', 'Silverlight', 'Vlc'];
		this.defaultPlayers['application/vnd.apple.mpegurl'] = ['NativeComponent', 'Native'];
		this.defaultPlayers['application/x-shockwave-flash'] = ['Kplayer'];

		this.defaultPlayers['video/ogg'] = ['Native', 'Vlc', 'Java', 'Generic'];
		this.defaultPlayers['video/webm'] = ['Native', 'Vlc'];
		this.defaultPlayers['application/ogg'] = ['Native', 'Vlc', 'Java', 'Generic'];
		this.defaultPlayers['audio/ogg'] = ['Native', 'Vlc', 'Java' ];
		this.defaultPlayers['audio/mpeg']= ['Native', 'Kplayer'];
		this.defaultPlayers['audio/mp3']= ['Native', 'Kplayer'];
		this.defaultPlayers['video/mpeg'] = ['Vlc'];
		this.defaultPlayers['video/x-msvideo'] = ['Vlc'];
		this.defaultPlayers['video/multicast'] = ['Silverlight'];
		this.defaultPlayers['video/ism'] = ['Silverlight'];
		this.defaultPlayers['video/playreadySmooth'] = ['Silverlight'];
		// this.defaultPlayers['text/html'] = ['Html'];
		//this.defaultPlayers['image/svg'] = ['ImageOverlay'];

		this.defaultPlayers['image/jpeg'] = ['ImageOverlay'];
		this.defaultPlayers['image/png'] = ['ImageOverlay'];
		if ( mw.getConfig("LeadWithHLSOnFlash") ) {
			this.defaultPlayers['application/vnd.apple.mpegurl'].push('Kplayer');
		}

	},

	/**
	 * Adds a Player to the player list
	 *
	 * @param {Object}
	 *	  player Player object to be added
	 */
	addPlayer: function( player ) {
		for ( var i = 0; i < this.players.length; i++ ) {
			if ( this.players[i].id == player.id ) {
				// Player already found
				return ;
			}
		}
		// Add the player:
		this.players.push( player );
	},

	/**
	 * Checks if a player is supported by id
	 */
	isSupportedPlayer: function( playerId ){
		for( var i=0; i < this.players.length; i++ ){
			if( this.players[i].id == playerId ){
				return true;
			}
		}
		return false;
	},
	getPlayerById: function(playerId){
		for( var i=0; i < this.players.length; i++ ){
			if( this.players[i].id.toLowerCase() == playerId.toLowerCase() ){
				return this.players[i];
			}
		}
		return null;
	},
	/**
	 * get players that support a given mimeType
	 *
	 * @param {String}
	 *	  mimeType Mime type of player set
	 * @return {Array} Array of players that support a the requested mime type
	 */
	getMIMETypePlayers: function( mimeType ) {
		var mimePlayers = new Array();
		var _this = this;
		if ( this.defaultPlayers[mimeType] ) {
			$.each( this.defaultPlayers[ mimeType ], function( d, lib ) {
				var library = _this.defaultPlayers[ mimeType ][ d ];
				for ( var i = 0; i < _this.players.length; i++ ) {
					if ( _this.players[i].library == library && _this.players[i].supportsMIMEType( mimeType ) ) {
						mimePlayers.push( _this.players[i] );
					}
				}
			} );
		}
		return mimePlayers;
	},
	/**
	 * Deprecated method call lacked get prefix for getter.
	 */
	defaultPlayer: function( mimeType ){
		mw.log( "MediaPlayer:: defaultPlayer has been deprecated, use getDefaultPlayer method instead" );
		return getDefaultPlayer( mimeType );
	},
	/**
	 * Default player for a given mime type
	 *
	 * @param {String}
	 *	  mimeType Mime type of the requested player
	 * @return Player for mime type null if no player found
	 */
	getDefaultPlayer : function( mimeType ) {
		// mw.log( "get defaultPlayer for " + mimeType );
		var mimePlayers = this.getMIMETypePlayers( mimeType );
		if (mw.getConfig( 'chromecastReceiver')) {
			return this.getPlayerById('chromecastReceiver');
		}
		if ( mw.getConfig( 'EmbedPlayer.ForceNativeComponent' ) && this.isSupportedPlayer( 'nativeComponentPlayer' )) {
			var nativeComponentPlayer = mw.EmbedTypes.getNativeComponentPlayerVideo();
			var nativeComponentPlayerSupported = mimePlayers.filter(function(mimePlayer){return mimePlayer.id === nativeComponentPlayer.id}).length > 0;
			if (nativeComponentPlayerSupported) {
				mimePlayers = [nativeComponentPlayer];
			} else {
				mimePlayers = [];
			}
		}
		if ( (mw.getConfig( 'EmbedPlayer.ForceKPlayer' ) || ( mw.getConfig( 'ForceFlashOnDesktopSafari') && mw.isDesktopSafari() ) )
			&& this.isSupportedPlayer( 'kplayer' ) && mimeType !== "video/youtube" ) {
			mimePlayers = [mw.EmbedTypes.getKplayer()];
		}
		if (mw.getConfig( 'EmbedPlayer.ForceSPlayer') && this.isSupportedPlayer('splayer')) {
			mimePlayers = [mw.EmbedTypes.getSilverlightPlayer()];
		}

		// Check for prior preference for this mime type
		for ( var i = 0; i < mimePlayers.length; i++ ) {
			if ( mimePlayers[i].id == this.preference[mimeType] ){
				mimePlayers = [mimePlayers[i]];
				break;
			}
		}
		// Otherwise just return the first compatible player
		// (it will be chosen according to the defaultPlayers list
		if( mimePlayers[0] ){
			return mimePlayers[0];
		}
		// mw.log( 'No default player found for ' + mimeType );
		return null;
	},
	/**
	 * Returns only a native video tag player
	 * @param {String}
	 * 	mimeType for player selection criteria
	 */
	getNativePlayer: function( mimeType ){
		var mimePlayers = this.getMIMETypePlayers( mimeType );
		for ( var i = 0; i < mimePlayers.length; i++ ) {
			if( mimePlayers[i].library == 'Native' ){
				return mimePlayers[i];
			}
		}
		return null;
	},

	/**
	 * Sets the format preference.
	 *
	 * @param {String}
	 *	  mimeFormat Prefered format
	 */
	setFormatPreference : function ( mimeFormat ) {
		 this.preference['formatPreference'] = mimeFormat;
		 $.cookie( 'EmbedPlayer.Preference', JSON.stringify( this.preference) );
	},

	/**
	 * Loads the user preference settings from a cookie
	 */
	loadPreferences : function ( ) {
		this.preference = { };
		// See if we have a cookie set to a clientSupported type:
		if( $.cookie( 'EmbedPlayer.Preference' ) ) {
			this.preference = JSON.parse( $.cookie( 'EmbedPlayer.Preference' ) );
		}
	},

	/**
	 * Sets the player preference
	 *
	 * @param {String}
	 *	  playerId Prefered player id
	 * @param {String}
	 *	  mimeType Mime type for the associated player stream
	 */
	setPlayerPreference : function( playerId, mimeType ) {
		var selectedPlayer = null;
		for ( var i = 0; i < this.players.length; i++ ) {
			if ( this.players[i].id == playerId ) {
				selectedPlayer = this.players[i];
				mw.log( 'EmbedPlayer::setPlayerPreference: choosing ' + playerId + ' for ' + mimeType );
				this.preference[ mimeType ] = playerId;
				$.cookie( 'EmbedPlayer.Preference', JSON.stringify( this.preference ) );
				break;
			}
		}
		// Update All the player instances on the page
		if ( selectedPlayer ) {
			$('.mwEmbedPlayer').each(function(inx, playerTarget ){
				var embedPlayer = $( playerTarget ).get( 0 );
				if ( embedPlayer.mediaElement.selectedSource
						&& ( embedPlayer.mediaElement.selectedSource.mimeType == mimeType ) )
				{
					embedPlayer.selectPlayer( selectedPlayer );
				}
			});
		}
	}
};

} )( mediaWiki, jQuery );
<commit_msg>On force playback engine make sure flavours are supported on it<commit_after>/**
 * mediaPlayers is a collection of mediaPlayer objects supported by the client.
 *
 * @constructor
 */
( function( mw, $ ) { "use strict";

mw.MediaPlayers = function(){
	this.init();
};

mw.MediaPlayers.prototype = {
	// The list of players supported
	players : null,

	// Store per mime-type preferences for players
	preference : { },

	// Stores the default set of players for a given mime type
	defaultPlayers : { },

	/**
	 * Initialization function sets the default order for players for a given
	 * mime type
	 */
	init: function() {
		this.players = new Array();
		this.loadPreferences();

		// Set up default players order for each library type
		this.defaultPlayers['video/wvm'] = ['NativeComponent'];
		this.defaultPlayers['video/live'] = ['Kplayer'];
		this.defaultPlayers['video/kontiki'] = ['Kplayer'];
		this.defaultPlayers['video/x-flv'] = ['Kplayer', 'Vlc'];
		this.defaultPlayers['video/h264'] = ['NativeComponent', 'Native', 'Kplayer', 'Silverlight', 'Vlc'];
		this.defaultPlayers['video/mp4'] = ['NativeComponent', 'Native', 'Kplayer', 'Silverlight', 'Vlc'];
		this.defaultPlayers['application/vnd.apple.mpegurl'] = ['NativeComponent', 'Native'];
		this.defaultPlayers['application/x-shockwave-flash'] = ['Kplayer'];

		this.defaultPlayers['video/ogg'] = ['Native', 'Vlc', 'Java', 'Generic'];
		this.defaultPlayers['video/webm'] = ['Native', 'Vlc'];
		this.defaultPlayers['application/ogg'] = ['Native', 'Vlc', 'Java', 'Generic'];
		this.defaultPlayers['audio/ogg'] = ['Native', 'Vlc', 'Java' ];
		this.defaultPlayers['audio/mpeg']= ['Native', 'Kplayer'];
		this.defaultPlayers['audio/mp3']= ['Native', 'Kplayer'];
		this.defaultPlayers['video/mpeg'] = ['Vlc'];
		this.defaultPlayers['video/x-msvideo'] = ['Vlc'];
		this.defaultPlayers['video/multicast'] = ['Silverlight'];
		this.defaultPlayers['video/ism'] = ['Silverlight'];
		this.defaultPlayers['video/playreadySmooth'] = ['Silverlight'];
		// this.defaultPlayers['text/html'] = ['Html'];
		//this.defaultPlayers['image/svg'] = ['ImageOverlay'];

		this.defaultPlayers['image/jpeg'] = ['ImageOverlay'];
		this.defaultPlayers['image/png'] = ['ImageOverlay'];
		if ( mw.getConfig("LeadWithHLSOnFlash") ) {
			this.defaultPlayers['application/vnd.apple.mpegurl'].push('Kplayer');
		}

	},

	/**
	 * Adds a Player to the player list
	 *
	 * @param {Object}
	 *	  player Player object to be added
	 */
	addPlayer: function( player ) {
		for ( var i = 0; i < this.players.length; i++ ) {
			if ( this.players[i].id == player.id ) {
				// Player already found
				return ;
			}
		}
		// Add the player:
		this.players.push( player );
	},

	/**
	 * Checks if a player is supported by id
	 */
	isSupportedPlayer: function( playerId ){
		for( var i=0; i < this.players.length; i++ ){
			if( this.players[i].id == playerId ){
				return true;
			}
		}
		return false;
	},
	getPlayerById: function(playerId){
		for( var i=0; i < this.players.length; i++ ){
			if( this.players[i].id.toLowerCase() == playerId.toLowerCase() ){
				return this.players[i];
			}
		}
		return null;
	},
	/**
	 * get players that support a given mimeType
	 *
	 * @param {String}
	 *	  mimeType Mime type of player set
	 * @return {Array} Array of players that support a the requested mime type
	 */
	getMIMETypePlayers: function( mimeType ) {
		var mimePlayers = new Array();
		var _this = this;
		if ( this.defaultPlayers[mimeType] ) {
			$.each( this.defaultPlayers[ mimeType ], function( d, lib ) {
				var library = _this.defaultPlayers[ mimeType ][ d ];
				for ( var i = 0; i < _this.players.length; i++ ) {
					if ( _this.players[i].library == library && _this.players[i].supportsMIMEType( mimeType ) ) {
						mimePlayers.push( _this.players[i] );
					}
				}
			} );
		}
		return mimePlayers;
	},
	/**
	 * Deprecated method call lacked get prefix for getter.
	 */
	defaultPlayer: function( mimeType ){
		mw.log( "MediaPlayer:: defaultPlayer has been deprecated, use getDefaultPlayer method instead" );
		return getDefaultPlayer( mimeType );
	},
	/**
	 * Default player for a given mime type
	 *
	 * @param {String}
	 *	  mimeType Mime type of the requested player
	 * @return Player for mime type null if no player found
	 */
	getDefaultPlayer : function( mimeType ) {
		// mw.log( "get defaultPlayer for " + mimeType );
		var mimePlayers = this.getMIMETypePlayers( mimeType );
		if (mw.getConfig( 'chromecastReceiver')) {
			return this.getPlayerById('chromecastReceiver');
		}
		if ( mw.getConfig( 'EmbedPlayer.ForceNativeComponent' ) && this.isSupportedPlayer( 'nativeComponentPlayer' )) {
			var nativeComponentPlayer = mw.EmbedTypes.getNativeComponentPlayerVideo();
			if (this.isPlayerSupportMimeType(mimePlayers, nativeComponentPlayer)) {
				mimePlayers = [nativeComponentPlayer];
			} else {
				mimePlayers = [];
			}
		}
		if ( ( mw.getConfig( 'EmbedPlayer.ForceKPlayer' ) ||
			( mw.getConfig( 'ForceFlashOnDesktopSafari') && mw.isDesktopSafari() ) ) &&
			this.isSupportedPlayer( 'kplayer' ) && mimeType !== "video/youtube" ) {
			var kplayer = mw.EmbedTypes.getKplayer();
			if (this.isPlayerSupportMimeType(mimePlayers, kplayer)) {
				mimePlayers = [kplayer];
			} else {
				mimePlayers = [];
			}
		}
		if (mw.getConfig( 'EmbedPlayer.ForceSPlayer') && this.isSupportedPlayer('splayer')) {
			var silverlightPlayer = mw.EmbedTypes.getSilverlightPlayer();
			if (this.isPlayerSupportMimeType(mimePlayers, silverlightPlayer)) {
				mimePlayers = [silverlightPlayer];
			} else {
				mimePlayers = [];
			}
		}

		// Check for prior preference for this mime type
		for ( var i = 0; i < mimePlayers.length; i++ ) {
			if ( mimePlayers[i].id == this.preference[mimeType] ){
				mimePlayers = [mimePlayers[i]];
				break;
			}
		}
		// Otherwise just return the first compatible player
		// (it will be chosen according to the defaultPlayers list
		if( mimePlayers[0] ){
			return mimePlayers[0];
		}
		// mw.log( 'No default player found for ' + mimeType );
		return null;
	},
	isPlayerSupportMimeType: function(mimePlayers, player){
		var playerSupported = mimePlayers.filter(function(mimePlayer){
			return mimePlayer.id === player.id;
		});
		return (playerSupported.length > 0);
	},
	/**
	 * Returns only a native video tag player
	 * @param {String}
	 * 	mimeType for player selection criteria
	 */
	getNativePlayer: function( mimeType ){
		var mimePlayers = this.getMIMETypePlayers( mimeType );
		for ( var i = 0; i < mimePlayers.length; i++ ) {
			if( mimePlayers[i].library == 'Native' ){
				return mimePlayers[i];
			}
		}
		return null;
	},

	/**
	 * Sets the format preference.
	 *
	 * @param {String}
	 *	  mimeFormat Prefered format
	 */
	setFormatPreference : function ( mimeFormat ) {
		 this.preference['formatPreference'] = mimeFormat;
		 $.cookie( 'EmbedPlayer.Preference', JSON.stringify( this.preference) );
	},

	/**
	 * Loads the user preference settings from a cookie
	 */
	loadPreferences : function ( ) {
		this.preference = { };
		// See if we have a cookie set to a clientSupported type:
		if( $.cookie( 'EmbedPlayer.Preference' ) ) {
			this.preference = JSON.parse( $.cookie( 'EmbedPlayer.Preference' ) );
		}
	},

	/**
	 * Sets the player preference
	 *
	 * @param {String}
	 *	  playerId Prefered player id
	 * @param {String}
	 *	  mimeType Mime type for the associated player stream
	 */
	setPlayerPreference : function( playerId, mimeType ) {
		var selectedPlayer = null;
		for ( var i = 0; i < this.players.length; i++ ) {
			if ( this.players[i].id == playerId ) {
				selectedPlayer = this.players[i];
				mw.log( 'EmbedPlayer::setPlayerPreference: choosing ' + playerId + ' for ' + mimeType );
				this.preference[ mimeType ] = playerId;
				$.cookie( 'EmbedPlayer.Preference', JSON.stringify( this.preference ) );
				break;
			}
		}
		// Update All the player instances on the page
		if ( selectedPlayer ) {
			$('.mwEmbedPlayer').each(function(inx, playerTarget ){
				var embedPlayer = $( playerTarget ).get( 0 );
				if ( embedPlayer.mediaElement.selectedSource
						&& ( embedPlayer.mediaElement.selectedSource.mimeType == mimeType ) )
				{
					embedPlayer.selectPlayer( selectedPlayer );
				}
			});
		}
	}
};

} )( mediaWiki, jQuery );
<|endoftext|>


<commit_before>/**
 * TaskFeedController
 * @namespace crowdsource.task-feed.controllers
 * @author dmorina
 */
(function () {
    'use strict';

    angular
        .module('crowdsource.task-feed.controllers')
        .controller('TaskFeedController', TaskFeedController);

    TaskFeedController.$inject = ['$window', '$location', '$scope', '$mdToast', 'TaskFeed',
        '$filter', 'Authentication', 'TaskWorker', 'Project', '$rootScope', '$routeParams'];

    /**
     * @namespace TaskFeedController
     */
    function TaskFeedController($window, $location, $scope, $mdToast, TaskFeed,
                                $filter, Authentication, TaskWorker, Project, $rootScope, $routeParams) {
        var userAccount = Authentication.getAuthenticatedAccount();
        if (!userAccount) {
            $location.path('/login');
            return;
        }

        var self = this;
        self.projects = [];
        self.previewedProject = null;
        self.showPreview = showPreview;
        self.openTask = openTask;
        self.openComments = openComments;
        self.saveComment = saveComment;
        self.loading = true;
        self.getStatusName = getStatusName;
        self.getRatingPercentage = getRatingPercentage;
        activate();

        function activate() {
            if ($routeParams.projectId) {
                self.openTask($routeParams.projectId);
            }
            else {
                getProjects();
            }
        }

        function getProjects() {
            TaskFeed.getProjects().then(
                function success(data) {
                    self.projects = data[0].filter(function (project) {
                        return project.available_tasks > 0;
                    });
                    self.availableTasks = self.projects.length > 0;
                },
                function error(errData) {
                    self.error = errData[0].detail;
                    $mdToast.showSimple('Could projects.');
                }
            ).
                finally(function () {
                    self.loading = false;
                });
        }

        function showPreview(project) {
            if (project.template && project.show_preview) {
                project.show_preview = false;
            }
            else if (project.template && !project.show_preview) {
                project.show_preview = true;
            }
            else {
                project.show_preview = true;
                Project.getPreview(project.id).then(
                    function success(data) {
                        angular.extend(project, {'template': data[0].template});
                        project.show_preview = true;
                    },
                    function error(errData) {
                        var err = errData[0];
                        $mdToast.showSimple('Error fetching preview.');
                    }
                ).finally(function () {
                    });
            }
        }

        function openTask(project_id) {
            TaskWorker.attemptAllocateTask(project_id).then(
                function success(data, status) {
                    if (data[1] == 204) {
                        $mdToast.showSimple('Error: No more tasks left.');
                        $location.path('/task-feed');
                    }
                    else {
                        var task_id = data[0].task;
                        var taskWorkerId = data[0].id;
                        $location.path('/task/' + task_id);
                    }

                },
                function error(errData) {
                    var err = errData[0];
                    var message = null;
                    if (err.hasOwnProperty('detail')) {
                        message = err.detail;
                    }
                    else {
                        message = JSON.stringify(err);
                    }
                    $mdToast.showSimple('Error: ' + message);
                }
            ).finally(function () {
                });
        }

        function openComments(project) {
            if (project.comments && project.is_comment_expanded) {
                project.is_comment_expanded = false;
            }
            else if (project.comments && !project.is_comment_expanded) {
                project.is_comment_expanded = true;
            }
            else {
                Project.getProjectComments(project.id).then(
                    function success(data) {
                        angular.extend(project, {'comments': data[0].comments});
                        project.is_comment_expanded = true;
                    },
                    function error(errData) {
                        var err = errData[0];
                        $mdToast.showSimple('Error fetching comments - ' + JSON.stringify(err));
                    }
                ).finally(function () {
                    });
            }
        }

        function saveComment(project) {
            TaskFeed.saveComment(project.id, self.comment.body).then(
                function success(data) {
                    if (project.comments == undefined) {
                        angular.extend(project, {'comments': []});
                    }
                    project.comments.push(data[0]);
                    self.comment.body = null;
                },
                function error(errData) {
                    var err = errData[0];
                    $mdToast.showSimple('Error saving comment - ' + JSON.stringify(err));
                }
            ).finally(function () {
                });
        }

        function getStatusName(statusId) {
            if (statusId == 5) return 'Paused';
            else if (statusId == 4) return 'Completed';
            else return 'Running';
        }

        function getRatingPercentage(rating, raw_rating, circle) {
            if (raw_rating) rating = raw_rating;
            return rating >= circle ? 100 : rating >= circle - 1 ? (rating - circle + 1) * 100 : 0;
        }
    }

})
();
<commit_msg>task feed<commit_after>/**
 * TaskFeedController
 * @namespace crowdsource.task-feed.controllers
 * @author dmorina
 */
(function () {
    'use strict';

    angular
        .module('crowdsource.task-feed.controllers')
        .controller('TaskFeedController', TaskFeedController);

    TaskFeedController.$inject = ['$window', '$location', '$scope', '$mdToast', 'TaskFeed',
        '$filter', 'Authentication', 'TaskWorker', 'Project', '$rootScope', '$stateParams'];

    /**
     * @namespace TaskFeedController
     */
    function TaskFeedController($window, $location, $scope, $mdToast, TaskFeed,
                                $filter, Authentication, TaskWorker, Project, $rootScope, $stateParams) {

        var userAccount = Authentication.getAuthenticatedAccount();

        if (!userAccount) {
            $location.path('/login');
            return;
        }

        var self = this;
        self.projects = [];
        self.previewedProject = null;
        self.showPreview = showPreview;
        self.openTask = openTask;
        self.openComments = openComments;
        self.saveComment = saveComment;
        self.loading = true;
        self.getStatusName = getStatusName;
        self.getRatingPercentage = getRatingPercentage;
        activate();

        function activate() {
            if ($stateParams.projectId) {
                self.openTask($stateParams.projectId);
            }
            else {
                getProjects();
            }
        }

        function getProjects() {
            TaskFeed.getProjects().then(
                function success(data) {
                    self.projects = data[0].filter(function (project) {
                        return project.available_tasks > 0;
                    });
                    self.availableTasks = self.projects.length > 0;
                },
                function error(errData) {
                    self.error = errData[0].detail;
                    $mdToast.showSimple('Could projects.');
                }
            ).
                finally(function () {
                    self.loading = false;
                });
        }

        function showPreview(project) {
            if (project.template && project.show_preview) {
                project.show_preview = false;
            }
            else if (project.template && !project.show_preview) {
                project.show_preview = true;
            }
            else {
                project.show_preview = true;
                Project.getPreview(project.id).then(
                    function success(data) {
                        angular.extend(project, {'template': data[0].template});
                        project.show_preview = true;
                    },
                    function error(errData) {
                        var err = errData[0];
                        $mdToast.showSimple('Error fetching preview.');
                    }
                ).finally(function () {
                    });
            }
        }

        function openTask(project_id) {
            TaskWorker.attemptAllocateTask(project_id).then(
                function success(data, status) {
                    if (data[1] == 204) {
                        $mdToast.showSimple('Error: No more tasks left.');
                        $location.path('/task-feed');
                    }
                    else {
                        var task_id = data[0].task;
                        var taskWorkerId = data[0].id;
                        $location.path('/task/' + task_id);
                    }

                },
                function error(errData) {
                    var err = errData[0];
                    var message = null;
                    if (err.hasOwnProperty('detail')) {
                        message = err.detail;
                    }
                    else {
                        message = JSON.stringify(err);
                    }
                    $mdToast.showSimple('Error: ' + message);
                }
            ).finally(function () {
                });
        }

        function openComments(project) {
            if (project.comments && project.is_comment_expanded) {
                project.is_comment_expanded = false;
            }
            else if (project.comments && !project.is_comment_expanded) {
                project.is_comment_expanded = true;
            }
            else {
                Project.getProjectComments(project.id).then(
                    function success(data) {
                        angular.extend(project, {'comments': data[0].comments});
                        project.is_comment_expanded = true;
                    },
                    function error(errData) {
                        var err = errData[0];
                        $mdToast.showSimple('Error fetching comments - ' + JSON.stringify(err));
                    }
                ).finally(function () {
                    });
            }
        }

        function saveComment(project) {
            TaskFeed.saveComment(project.id, self.comment.body).then(
                function success(data) {
                    if (project.comments == undefined) {
                        angular.extend(project, {'comments': []});
                    }
                    project.comments.push(data[0]);
                    self.comment.body = null;
                },
                function error(errData) {
                    var err = errData[0];
                    $mdToast.showSimple('Error saving comment - ' + JSON.stringify(err));
                }
            ).finally(function () {
                });
        }

        function getStatusName(statusId) {
            if (statusId == 5) return 'Paused';
            else if (statusId == 4) return 'Completed';
            else return 'Running';
        }

        function getRatingPercentage(rating, raw_rating, circle) {
            if (raw_rating) rating = raw_rating;
            return rating >= circle ? 100 : rating >= circle - 1 ? (rating - circle + 1) * 100 : 0;
        }
    }

})
();
<|endoftext|>


<commit_before>!(function (d3) {

  let numofmonthback = $( "#numofmonthback option:selected" ).text();
  $("#downloadsdailyTabContainer").empty();
  // Set the dimensions of the canvas / graph
  var margin = {top: 30, right: 20, bottom: 70, left: 50},
      width = 1200 - margin.left - margin.right,
      height = 600 - margin.top - margin.bottom;

  // Parse the date / time
  //var parseDate = d3.timeParse("%Y%m%d");

  // Set the ranges
  //var x = d3.scaleTime().range([0, width]);

  var x = d3.scaleLinear().range([0, width]);
  var y = d3.scaleLinear().range([height, 0]);

  // Define the line
  var priceline = d3.line()
      .x(function(d) { return x(d.date); })
      .y(function(d) { return y(d.price); });

  // Adds the svg canvas

  var svg = d3.select("#downloadsdailyTabContainer")
      .append("svg")
          .attr("width", width + margin.left + margin.right)
          .attr("height", height + margin.top + margin.bottom)
      .append("g")
          .attr("transform",
                "translate(" + margin.left + "," + margin.top + ")");

  // Get the data

  d3.json("/backend/index/getdownloadsdaily?numofmonthback="+numofmonthback, function(error, data) {
      if (error) throw error;
      data = data.results;
      data.forEach(function(d) {
     //d.date = parseDate(d.date);
     d.date = +d.date;
      d.price = +d.price;
      });

      // Scale the range of the data
      //x.domain(d3.extent(data, function(d) { return d.date; }));

     x.domain([d3.min(data, function(d) { return d.date; }), d3.max(data, function(d) { return d.date; })]);
      y.domain([d3.min(data, function(d) { return d.price; }), d3.max(data, function(d) { return d.price; })]);

      // Nest the entries by symbol
      var dataNest = d3.nest()
          .key(function(d) {return d.symbol;})
          .entries(data);

      // set the colour scale
      var color = d3.scaleOrdinal(d3.schemeCategory10);

      legendSpace = width/dataNest.length; // spacing for the legend

      // Loop through each symbol / key
      dataNest.forEach(function(d,i) {

          svg.append("path")
              .attr("class", "line")
              .style("stroke", function() { // Add the colours dynamically
                  return d.color = color(d.key); })
              .attr("d", priceline(d.values));

          // Add the Legend
          svg.append("text")
              .attr("x", (legendSpace/2)+i*legendSpace)  // space legend
              .attr("y", height + (margin.bottom/2)+ 5)
              .attr("class", "legend")    // style the legend
              .style("fill", function() { // Add the colours dynamically
                  return d.color = color(d.key); })
              .text(d.key);

      });

    // Add the X Axis
    svg.append("g")
        .attr("class", "axis")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(x));

    // Add the Y Axis
    svg.append("g")
        .attr("class", "axis")
        .call(d3.axisLeft(y));

  });

  // new memeber project stati
  var parseTime = d3.timeParse("%Y%m%d");
  var svgLine = d3.select("#payoutyear")
      .append("svg")
      .attr("width", 500)
      .attr("height", 250);

  var marginLine = {top: 30, right: 50, bottom: 50, left: 30},
      widthLine = +svgLine.attr("width") - marginLine.left - marginLine.right,
      heightLine = +svgLine.attr("height") - marginLine.top - marginLine.bottom,
      labelPadding = 3;

  var xLine = d3.scaleTime().range([0, widthLine]);
  var g = svgLine.append("g")
      .attr("transform", "translate(" + marginLine.left + "," + marginLine.top + ")");

      d3.json("/backend/index/getdownloadsdaily", function(error, data) {
        if (error) throw error;
        data = data.results;

        // format the data
        data.forEach(function(d) {
            d.date = parseTime(d.yearmonth);
            d.amount = +d.amount;
        });

        data.columns=['date','amount'];
        var series = data.columns.slice(1).map(function(key) {
          return data.map(function(d) {
            return {
              key: key,
              date: d.date,
              value: d[key]
            };
          });
        });

        xLine.domain([data[0].date, data[data.length - 1].date]);

        var yLine = d3.scaleLinear()
            .domain([d3.min(series, function(s) { return d3.min(s, function(d) { return d.value; }); }), d3.max(series, function(s) { return d3.max(s, function(d) { return d.value; }); })])
            .range([heightLine, 0]);

        var zLine = d3.scaleOrdinal(d3.schemeCategory10);

        g.append("g")
            .attr("class", "axis axis--x")
            .attr("transform", "translate(0," + heightLine + ")")
            .call(d3.axisBottom(xLine).ticks(data.length).tickFormat(d3.timeFormat("%Y-%m")))
            .selectAll("text")
            .style("text-anchor", "end")
            .attr("dx", "-.8em")
            .attr("dy", ".15em")
            .attr("transform", "rotate(-65)");

        var serie = g.selectAll(".serie")
            .data(series)
          .enter().append("g")
            .attr("class", "serie");

        serie.append("path")
            .attr("class", "line")
            .style("stroke", function(d) { return zLine(d[0].key); })
            .attr("d", d3.line()
                .x(function(d) { return xLine(d.date); })
                .y(function(d) { return yLine(d.value); }));

        var label = serie.selectAll(".label")
            .data(function(d) { return d; })
          .enter().append("g")
            .attr("class", "label")
            .attr("transform", function(d, i) { return "translate(" + xLine(d.date) + "," + yLine(d.value) + ")"; });

            label.append("text")
                 .attr("dy", ".35em")
                 .text(function(d) { return d.value; })
               .filter(function(d, i) { return i === data.length - 1; })

       const newText = label.selectAll('text');
       const bbox = newText.node().getBBox();

       label.append('rect', 'text')
           .datum(() => bbox)
           .attr('x', d => (d.x - labelPadding))
           .attr('y', d => (d.y - labelPadding))
           .attr('width', d => (d.width + (2 * labelPadding)))
           .attr('height', d => (d.height + (2 * labelPadding)));

           label.append("text")
                .attr("dy", ".35em")
                .text(function(d) { return d.value; })
              .filter(function(d, i) { return i === data.length - 1; })
              .append("tspan")
                .attr("class", "label-key")
                .text(function(d) { return " " + d.key; });

      });

})(d3);<commit_msg>stati<commit_after>!(function (d3) {

  let numofmonthback = $( "#numofmonthback option:selected" ).text();
  $("#downloadsdailyTabContainer").empty();
  // Set the dimensions of the canvas / graph
  var margin = {top: 30, right: 20, bottom: 70, left: 50},
      width = 1200 - margin.left - margin.right,
      height = 600 - margin.top - margin.bottom;

  // Parse the date / time
  //var parseDate = d3.timeParse("%Y%m%d");

  // Set the ranges
  //var x = d3.scaleTime().range([0, width]);

  var x = d3.scaleLinear().range([0, width]);
  var y = d3.scaleLinear().range([height, 0]);

  // Define the line
  var priceline = d3.line()
      .x(function(d) { return x(d.date); })
      .y(function(d) { return y(d.price); });

  // Adds the svg canvas

  var svg = d3.select("#downloadsdailyTabContainer")
      .append("svg")
          .attr("width", width + margin.left + margin.right)
          .attr("height", height + margin.top + margin.bottom)
      .append("g")
          .attr("transform",
                "translate(" + margin.left + "," + margin.top + ")");

  // Get the data

  d3.json("/backend/index/getdownloadsdaily?numofmonthback="+numofmonthback, function(error, data) {
      if (error) throw error;
      data = data.results;
      data.forEach(function(d) {
     //d.date = parseDate(d.date);
     d.date = +d.date;
      d.price = +d.price;
      });

      // Scale the range of the data
      //x.domain(d3.extent(data, function(d) { return d.date; }));

     x.domain([d3.min(data, function(d) { return d.date; }), d3.max(data, function(d) { return d.date; })]);
      y.domain([0, d3.max(data, function(d) { return d.price; })]);

      // Nest the entries by symbol
      var dataNest = d3.nest()
          .key(function(d) {return d.symbol;})
          .entries(data);

      // set the colour scale
      var color = d3.scaleOrdinal(d3.schemeCategory10);

      legendSpace = width/dataNest.length; // spacing for the legend

      // Loop through each symbol / key
      dataNest.forEach(function(d,i) {

          svg.append("path")
              .attr("class", "line")
              .style("stroke", function() { // Add the colours dynamically
                  return d.color = color(d.key); })
              .attr("d", priceline(d.values));

          // Add the Legend
          svg.append("text")
              .attr("x", (legendSpace/2)+i*legendSpace)  // space legend
              .attr("y", height + (margin.bottom/2)+ 5)
              .attr("class", "legend")    // style the legend
              .style("fill", function() { // Add the colours dynamically
                  return d.color = color(d.key); })
              .text(d.key);

      });

    // Add the X Axis
    svg.append("g")
        .attr("class", "axis")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(x));

    // Add the Y Axis
    svg.append("g")
        .attr("class", "axis")
        .call(d3.axisLeft(y));

  });

  // new memeber project stati
  var parseTime = d3.timeParse("%Y%m%d");
  var svgLine = d3.select("#payoutyear")
      .append("svg")
      .attr("width", 500)
      .attr("height", 250);

  var marginLine = {top: 30, right: 50, bottom: 50, left: 30},
      widthLine = +svgLine.attr("width") - marginLine.left - marginLine.right,
      heightLine = +svgLine.attr("height") - marginLine.top - marginLine.bottom,
      labelPadding = 3;

  var xLine = d3.scaleTime().range([0, widthLine]);
  var g = svgLine.append("g")
      .attr("transform", "translate(" + marginLine.left + "," + marginLine.top + ")");

      d3.json("/backend/index/getdownloadsdaily", function(error, data) {
        if (error) throw error;
        data = data.results;

        // format the data
        data.forEach(function(d) {
            d.date = parseTime(d.yearmonth);
            d.amount = +d.amount;
        });

        data.columns=['date','amount'];
        var series = data.columns.slice(1).map(function(key) {
          return data.map(function(d) {
            return {
              key: key,
              date: d.date,
              value: d[key]
            };
          });
        });

        xLine.domain([data[0].date, data[data.length - 1].date]);

        var yLine = d3.scaleLinear()
            .domain([d3.min(series, function(s) { return d3.min(s, function(d) { return d.value; }); }), d3.max(series, function(s) { return d3.max(s, function(d) { return d.value; }); })])
            .range([heightLine, 0]);

        var zLine = d3.scaleOrdinal(d3.schemeCategory10);

        g.append("g")
            .attr("class", "axis axis--x")
            .attr("transform", "translate(0," + heightLine + ")")
            .call(d3.axisBottom(xLine).ticks(data.length).tickFormat(d3.timeFormat("%Y-%m")))
            .selectAll("text")
            .style("text-anchor", "end")
            .attr("dx", "-.8em")
            .attr("dy", ".15em")
            .attr("transform", "rotate(-65)");

        var serie = g.selectAll(".serie")
            .data(series)
          .enter().append("g")
            .attr("class", "serie");

        serie.append("path")
            .attr("class", "line")
            .style("stroke", function(d) { return zLine(d[0].key); })
            .attr("d", d3.line()
                .x(function(d) { return xLine(d.date); })
                .y(function(d) { return yLine(d.value); }));

        var label = serie.selectAll(".label")
            .data(function(d) { return d; })
          .enter().append("g")
            .attr("class", "label")
            .attr("transform", function(d, i) { return "translate(" + xLine(d.date) + "," + yLine(d.value) + ")"; });

            label.append("text")
                 .attr("dy", ".35em")
                 .text(function(d) { return d.value; })
               .filter(function(d, i) { return i === data.length - 1; })

       const newText = label.selectAll('text');
       const bbox = newText.node().getBBox();

       label.append('rect', 'text')
           .datum(() => bbox)
           .attr('x', d => (d.x - labelPadding))
           .attr('y', d => (d.y - labelPadding))
           .attr('width', d => (d.width + (2 * labelPadding)))
           .attr('height', d => (d.height + (2 * labelPadding)));

           label.append("text")
                .attr("dy", ".35em")
                .text(function(d) { return d.value; })
              .filter(function(d, i) { return i === data.length - 1; })
              .append("tspan")
                .attr("class", "label-key")
                .text(function(d) { return " " + d.key; });

      });

})(d3);<|endoftext|>