<commit_before>(function(window, document, undefined){

  var gKeys = function(){
    var Key = function(){
      this.d = false;
      this.u = false;
      this.p = 0;
    };
    var keys = {
                UP: new Key(),
                DOWN: new Key(),
                LEFT: new Key(),
                RIGHT: new Key(),
                SPACE: new Key()
               },
        mapKeys = {
                  37: 'LEFT',
                  38: 'UP',
                  39: 'RIGHT',
                  40: 'DOWN',
                  32: 'SPACE',
                  //virtual keys
                  'vkLeft': 'LEFT',
                  'vkUp': 'UP',
                  'vkRight': 'RIGHT',
                  'vkDown': 'DOWN',
                  'vkSpace': 'SPACE',
                },
        canvas = null,
        kdCallback = function( keys ){},
        kuCallback = function( keys ){},
        customThread = false,
        allowsHistory = true,
        history = [],
        maxHistory = 10,
        maxTime = 100;

    var mapping = function( key, down ){
      if(key in mapKeys){
        keys[mapKeys[key]].d = down;
        keys[mapKeys[key]].u = !down;
      }
    };

    var keyDowns = function( e ){
      var key = e.keyCode ? e.keyCode : e.which;
      mapping(key, true);
      e.preventDefault();
    };

    var keyUps = function( e ){
      var key = e.keyCode ? e.keyCode : e.which;
      mapping(key, false);
      e.preventDefault();
    };

    var scanKeys = function(){
      var callUp = false,
          callDown = false;

      if(!customThread && arguments.callee.caller.name !== 'gScanning'){
        customThread = true;
      }

      for(key in keys){
        if (!keys.hasOwnProperty(key)) continue;
        keys[key].p = keys[key].d ? keys[key].p+1 : keys[key].p;
        callDown = callDown || keys[key].d;
        callUp = callUp || keys[key].u;
      }

      if(callDown){
        kdCallback(keys);
      }

      if(callUp){
        var localKeys = {};
        kuCallback(keys);
        for(key in keys){
          if (!keys.hasOwnProperty(key)) continue;

          if(keys[key].u){
            keys[key].u = false;
            keys[key].p = 0;
            if(allowsHistory){
              localKeys[key] = maxTime;
            }
          }
        }

        if(allowsHistory){
          addHistoryRecord(localKeys);
        }
      }

      if(allowsHistory){
        cleanHistory();
      }
    };

    //history
    var addHistoryRecord = function(localKeys){
      history.splice(0, 0, localKeys);
      while(history.length > maxHistory){
        history.pop();
      }
    };
    var cleanHistory = function(){
      for(keysHistory in history){
        for(key in history[keysHistory]){
          if (!history[keysHistory].hasOwnProperty(key)) continue;

          history[keysHistory][key]--;
          if(history[keysHistory][key] < 0){
            history.pop();
            break;
          }
        }
      }
    };

    var isMobile = function(){
      var regexp1 = new RegExp('/(android|bb\d+|meego).+mobile|avantgo|bada\/'+
                '|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)'+
                '|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?'+
                '|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.'+
                '(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i');
      var regexp2 = new RegExp('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|'+
                'a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)'+
                '|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)'+
                '|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-'+
                '|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi'+
                '|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8'+
                '|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo'+
                '|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)'+
                '|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)'+
                '|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a'+
                '|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)'+
                '|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)'+
                '|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do'+
                '|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)'+
                '|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph'+
                '|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))'+
                '|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a'+
                '|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)'+
                '|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|'+
                '47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)'+
                '|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)'+
                '|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9'+
                '|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40'+
                '|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|'+
                'wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i');
      return regexp1.test(navigator.userAgent||navigator.vendor||window.opera)||
      regexp2.test(navigator.userAgent||navigator.vendor||window.opera.substr(0,4));
    };

    (function init(){
      canvas = document.getElementsByTagName('canvas')[0];
      canvas.setAttribute('tabIndex', 1);
      canvas.addEventListener('keydown',  keyDowns);
      canvas.addEventListener('keyup',  keyUps);
      canvas.focus();

      if(isMobile()||true){
        //load virtual keyboard
        var virtualKeyboard = document.createElement('div');
        virtualKeyboard.id='virtualKeys';
        virtualKeyboard.innerHTML = '<button class="vk" id="vkSpace"></button>'+
                               '<button class="vk" id="vkUp"></button>'+
                               '<button class="vk" id="vkDown"></button>'+
                               '<button class="vk" id="vkLeft"></button>'+
                               '<button class="vk" id="vkRight"></button>';
        document.body.appendChild(virtualKeyboard);

        //if virtualkeys
        var collection = document.getElementById('virtualKeys').children;
          for(var i = 0; i<collection.length; i++){
            var link = collection[i];
            link.onclick = function(event){
              return false;
            };
            link.onmousedown = function(event){
              mapping(this.id, true);

              return false;
            };
            link.onmouseup = function(event){
              mapping(this.id, false);
              canvas.focus();
              return false;
            };
            link.addEventListener('touchstart', function(e){
                mapping(this.id, true);
                e.preventDefault();
            }, false);
            link.addEventListener('touchend', function(e){
              mapping(this.id, false);
              e.preventDefault();
            }, false);

          }
        }
      })();

    (function gScanning(){
      if(!customThread){
        scanKeys();
        window.setTimeout(gScanning, 1000 / 60);
      }
    })();

    return {
      'keyDown': function( callback ){
        kdCallback = callback;
      },
      'keyUp': function( callback ){
        kuCallback = callback;
      },
      'scanKeys': scanKeys,
      'history': history
    };

  }();
  window.gKeys = gKeys;

})(window, document);<commit_msg>allows to register moves<commit_after>(function(window, document, undefined){

  var gKeys = function(){
    //the Key object
    var Key = function(){
      this.d = false; //down state
      this.u = false; //up state
      this.p = 0;     //pressed time
    };
    var keys = {                        //the avalaible keys
                UP: new Key(),
                DOWN: new Key(),
                LEFT: new Key(),
                RIGHT: new Key(),
                SPACE: new Key()
               },
        mapKeys = {                     //key codes for the keys
                  37: 'LEFT',
                  38: 'UP',
                  39: 'RIGHT',
                  40: 'DOWN',
                  32: 'SPACE',
                  //virtual keys
                  'vkLeft': 'LEFT',
                  'vkUp': 'UP',
                  'vkRight': 'RIGHT',
                  'vkDown': 'DOWN',
                  'vkSpace': 'SPACE',
                },
        canvas = null,                  //the canvas object
        kdCallback = function( keys ){},//key down callback function
        kuCallback = function( keys ){},//key up callback function
        customThread = false,           //true if the scanKeys function is managed by another tread
        allowsHistory = true,           //allows the history functions, required for the moves function
        history = [],                   //register of the last key ups
        maxHistory = 10,                //maximun keys allowed in the history array
        maxTime = 100,                  //time a key is in the history, in loop cycles
        moveList = [],                  //a list with the moves registered
        minimalList = maxHistory;       //minimal keys in the history neccesary to do a move inspection

    //inspect changes in the keys object
    //key: the key code
    //down: if the key is down or up
    var mapping = function( key, down ){
      if(key in mapKeys){
        keys[mapKeys[key]].d = down;
        keys[mapKeys[key]].u = !down;
      }
    };

    var keyDowns = function(e){
      var key = e.keyCode ? e.keyCode : e.which;
      mapping(key, true);
      e.preventDefault();
    };

    var keyUps = function(e){
      var key = e.keyCode ? e.keyCode : e.which;
      mapping(key, false);
      e.preventDefault();
    };

    var scanKeys = function(){
      var callUp = false,
          callDown = false;

      if(!customThread && arguments.callee.caller.name !== 'gScanning'){
        customThread = true;
      }

      for(key in keys){
        if (!keys.hasOwnProperty(key)) continue;
        keys[key].p = keys[key].d ? keys[key].p+1 : keys[key].p;
        callDown = callDown || keys[key].d;
        callUp = callUp || keys[key].u;
      }

      if(callDown){
        kdCallback(keys);
      }

      if(callUp){
        var localKeys = {};
        kuCallback(keys);
        for(key in keys){
          if (!keys.hasOwnProperty(key)) continue;

          if(keys[key].u){
            keys[key].u = false;
            keys[key].p = 0;
            if(allowsHistory){
              localKeys[key] = maxTime;
            }
          }
        }

        if(allowsHistory){
          addHistoryRecord(localKeys);
        }
      }

      if(allowsHistory){
        cleanHistory();
      }
    };

    //history
    var addHistoryRecord = function(localKeys){
      history.splice(0, 0, localKeys);
      validateMoves();
      while(history.length > maxHistory){
        history.pop();
      }
    };
    var cleanHistory = function(){
      for(keysHistory in history){
        for(key in history[keysHistory]){
          if (!history[keysHistory].hasOwnProperty(key)) continue;

          history[keysHistory][key]--;
          if(history[keysHistory][key] < 0){
            history.pop();
            break;
          }
        }
      }
    };

    //Moves
    var Move = function(){
      this.sequence = [],
      this.callback = function(){};
    };

    var registerMove = function(sequence, callback){
      var move = new Move(),
          added = false;
      move.sequence = sequence;
      move.callback = callback;

      for (var i = 0; i < moveList.length; i++) {
        if(move.sequence.length > moveList[i].sequence.length){
          moveList.splice(i, 0, move);
          added = true;
          break;
        }
      };
      if(!added){
        moveList.push(move);
      }
      if(sequence.length < minimalList){
        minimalList = sequence.length;
      }
    }

    var validateMoves = function(){
      var move, isMove, sequence, sequenceLength;
      if(history.length < minimalList) return;

      for(var i = 0; i < moveList.length; i++){
        move = moveList[i];
        isMove = true;
        sequence = move.sequence;
        sequenceLength = sequence.length-1;
        if(history.length <= sequenceLength) continue;

        for(var j = 0; j <= sequenceLength; j++){
          isMove = isMove && history[j][sequence[sequenceLength-j]];
        }
        if(isMove){
          move.callback();
          return;
        }
      }
    }

    //virtual keyBoard
    var isMobile = function(){
      var regexp1 = new RegExp('/(android|bb\d+|meego).+mobile|avantgo|bada\/'+
                '|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)'+
                '|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?'+
                '|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.'+
                '(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i');
      var regexp2 = new RegExp('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|'+
                'a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)'+
                '|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)'+
                '|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-'+
                '|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi'+
                '|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8'+
                '|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo'+
                '|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)'+
                '|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)'+
                '|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a'+
                '|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)'+
                '|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)'+
                '|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do'+
                '|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)'+
                '|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph'+
                '|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))'+
                '|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a'+
                '|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)'+
                '|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|'+
                '47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)'+
                '|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)'+
                '|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9'+
                '|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40'+
                '|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|'+
                'wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i');
      return regexp1.test(navigator.userAgent||navigator.vendor||window.opera)||
      regexp2.test(navigator.userAgent||navigator.vendor||window.opera.substr(0,4));
    };

    (function init(){
      canvas = document.getElementsByTagName('canvas')[0];
      canvas.setAttribute('tabIndex', 1);
      canvas.addEventListener('keydown',  keyDowns);
      canvas.addEventListener('keyup',  keyUps);
      canvas.focus();

      if(isMobile()||true){
        //load virtual keyboard
        var virtualKeyboard = document.createElement('div');
        virtualKeyboard.id='virtualKeys';
        virtualKeyboard.innerHTML = '<button class="vk" id="vkSpace"></button>'+
                               '<button class="vk" id="vkUp"></button>'+
                               '<button class="vk" id="vkDown"></button>'+
                               '<button class="vk" id="vkLeft"></button>'+
                               '<button class="vk" id="vkRight"></button>';
        document.body.appendChild(virtualKeyboard);

        //if virtualkeys
        var collection = document.getElementById('virtualKeys').children;
          for(var i = 0; i<collection.length; i++){
            var link = collection[i];
            link.onclick = function(event){
              return false;
            };
            link.onmousedown = function(event){
              mapping(this.id, true);

              return false;
            };
            link.onmouseup = function(event){
              mapping(this.id, false);
              canvas.focus();
              return false;
            };
            link.addEventListener('touchstart', function(e){
                mapping(this.id, true);
                e.preventDefault();
            }, false);
            link.addEventListener('touchend', function(e){
              mapping(this.id, false);
              e.preventDefault();
            }, false);

          }
        }
      })();

    (function gScanning(){
      if(!customThread){
        scanKeys();
        window.setTimeout(gScanning, 1000 / 60);
      }
    })();

    return {
      'keyDown': function( callback ){
        kdCallback = callback;
      },
      'keyUp': function( callback ){
        kuCallback = callback;
      },
      'registerMove': registerMove,
      'scanKeys': scanKeys,
      'history': history
    };

  }();
  window.gKeys = gKeys;

})(window, document);<|endoftext|>


<commit_before>exports.bitrv2 = function(n, ipBuffer, ipOffset, aBuffer) {
    // create some views on the raw buffers
    let ip = new Float32Array(ipBuffer).subarray(ipOffset);
    let a = new Float32Array(aBuffer);

    let j, j1, k, k1, l, m, m2;
    let xr, xi, yr, yi;

    ip[0] = 0;
    l = n;
    m = 1;
    while ((m << 3) < l) {
        l >>= 1;
        for (j = 0; j < m; j++) {
            ip[m + j] = ip[j] + l;
        }
        m <<= 1;
    }
    m2 = 2 * m;
    if ((m << 3) == l) {
        for (k = 0; k < m; k++) {
            for (j = 0; j < k; j++) {
                j1 = 2 * j + ip[k];
                k1 = 2 * k + ip[j];
                xr = a[j1];
                xi = a[j1 + 1];
                yr = a[k1];
                yi = a[k1 + 1];
                a[j1] = yr;
                a[j1 + 1] = yi;
                a[k1] = xr;
                a[k1 + 1] = xi;
                j1 += m2;
                k1 += 2 * m2;
                xr = a[j1];
                xi = a[j1 + 1];
                yr = a[k1];
                yi = a[k1 + 1];
                a[j1] = yr;
                a[j1 + 1] = yi;
                a[k1] = xr;
                a[k1 + 1] = xi;
                j1 += m2;
                k1 -= m2;
                xr = a[j1];
                xi = a[j1 + 1];
                yr = a[k1];
                yi = a[k1 + 1];
                a[j1] = yr;
                a[j1 + 1] = yi;
                a[k1] = xr;
                a[k1 + 1] = xi;
                j1 += m2;
                k1 += 2 * m2;
                xr = a[j1];
                xi = a[j1 + 1];
                yr = a[k1];
                yi = a[k1 + 1];
                a[j1] = yr;
                a[j1 + 1] = yi;
                a[k1] = xr;
                a[k1 + 1] = xi;
            }
            j1 = 2 * k + m2 + ip[k];
            k1 = j1 + m2;
            xr = a[j1];
            xi = a[j1 + 1];
            yr = a[k1];
            yi = a[k1 + 1];
            a[j1] = yr;
            a[j1 + 1] = yi;
            a[k1] = xr;
            a[k1 + 1] = xi;
        }
    } else {
        for (k = 1; k < m; k++) {
            for (j = 0; j < k; j++) {
                j1 = 2 * j + ip[k];
                k1 = 2 * k + ip[j];
                xr = a[j1];
                xi = a[j1 + 1];
                yr = a[k1];
                yi = a[k1 + 1];
                a[j1] = yr;
                a[j1 + 1] = yi;
                a[k1] = xr;
                a[k1 + 1] = xi;
                j1 += m2;
                k1 += m2;
                xr = a[j1];
                xi = a[j1 + 1];
                yr = a[k1];
                yi = a[k1 + 1];
                a[j1] = yr;
                a[j1 + 1] = yi;
                a[k1] = xr;
                a[k1 + 1] = xi;
            }
        }
    }
}
<commit_msg>added remaining child functions<commit_after>//TODO: Check exports and only do when necessary

exports.bitrv2 = function(n, ipBuffer, ipOffset, aBuffer) {
    let j, j1, k, k1, l, m, m2;
    let xr, xi, yr, yi;

    // create some views on the raw buffers
    let ip = new Int16Array(ipBuffer).subarray(ipOffset);
    let a = new Float32Array(aBuffer);

    ip[0] = 0;
    l = n;
    m = 1;
    while ((m << 3) < l) {
        l >>= 1;
        for (j = 0; j < m; j++) {
            ip[m + j] = ip[j] + l;
        }
        m <<= 1;
    }
    m2 = 2 * m;
    if ((m << 3) == l) {
        for (k = 0; k < m; k++) {
            for (j = 0; j < k; j++) {
                j1 = 2 * j + ip[k];
                k1 = 2 * k + ip[j];
                xr = a[j1];
                xi = a[j1 + 1];
                yr = a[k1];
                yi = a[k1 + 1];
                a[j1] = yr;
                a[j1 + 1] = yi;
                a[k1] = xr;
                a[k1 + 1] = xi;
                j1 += m2;
                k1 += 2 * m2;
                xr = a[j1];
                xi = a[j1 + 1];
                yr = a[k1];
                yi = a[k1 + 1];
                a[j1] = yr;
                a[j1 + 1] = yi;
                a[k1] = xr;
                a[k1 + 1] = xi;
                j1 += m2;
                k1 -= m2;
                xr = a[j1];
                xi = a[j1 + 1];
                yr = a[k1];
                yi = a[k1 + 1];
                a[j1] = yr;
                a[j1 + 1] = yi;
                a[k1] = xr;
                a[k1 + 1] = xi;
                j1 += m2;
                k1 += 2 * m2;
                xr = a[j1];
                xi = a[j1 + 1];
                yr = a[k1];
                yi = a[k1 + 1];
                a[j1] = yr;
                a[j1 + 1] = yi;
                a[k1] = xr;
                a[k1 + 1] = xi;
            }
            j1 = 2 * k + m2 + ip[k];
            k1 = j1 + m2;
            xr = a[j1];
            xi = a[j1 + 1];
            yr = a[k1];
            yi = a[k1 + 1];
            a[j1] = yr;
            a[j1 + 1] = yi;
            a[k1] = xr;
            a[k1 + 1] = xi;
        }
    } else {
        for (k = 1; k < m; k++) {
            for (j = 0; j < k; j++) {
                j1 = 2 * j + ip[k];
                k1 = 2 * k + ip[j];
                xr = a[j1];
                xi = a[j1 + 1];
                yr = a[k1];
                yi = a[k1 + 1];
                a[j1] = yr;
                a[j1 + 1] = yi;
                a[k1] = xr;
                a[k1 + 1] = xi;
                j1 += m2;
                k1 += m2;
                xr = a[j1];
                xi = a[j1 + 1];
                yr = a[k1];
                yi = a[k1 + 1];
                a[j1] = yr;
                a[j1 + 1] = yi;
                a[k1] = xr;
                a[k1 + 1] = xi;
            }
        }
    }
}

exports.cftfsub = function(n, aBuffer, wBuffer) {
    let j, j1, j2, j3, l;
    let x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i;

    // create some views on the raw buffers
    let a = new Float64Array(aBuffer);
    let w = new Float64Array(wBuffer);

    l = 2;
    if (n > 8) {
        cft1st(n, a, w);
        l = 8;
        while ((l << 2) < n) {
            cftmdl(n, l, a, w);
            l <<= 2;
        }
    }
    if ((l << 2) == n) {
        for (j = 0; j < l; j += 2) {
            j1 = j + l;
            j2 = j1 + l;
            j3 = j2 + l;
            x0r = a[j] + a[j1];
            x0i = a[j + 1] + a[j1 + 1];
            x1r = a[j] - a[j1];
            x1i = a[j + 1] - a[j1 + 1];
            x2r = a[j2] + a[j3];
            x2i = a[j2 + 1] + a[j3 + 1];
            x3r = a[j2] - a[j3];
            x3i = a[j2 + 1] - a[j3 + 1];
            a[j] = x0r + x2r;
            a[j + 1] = x0i + x2i;
            a[j2] = x0r - x2r;
            a[j2 + 1] = x0i - x2i;
            a[j1] = x1r - x3i;
            a[j1 + 1] = x1i + x3r;
            a[j3] = x1r + x3i;
            a[j3 + 1] = x1i - x3r;
        }
    } else {
        for (j = 0; j < l; j += 2) {
            j1 = j + l;
            x0r = a[j] - a[j1];
            x0i = a[j + 1] - a[j1 + 1];
            a[j] += a[j1];
            a[j + 1] += a[j1 + 1];
            a[j1] = x0r;
            a[j1 + 1] = x0i;
        }
    }
}

exports.cftbsub = function(n, aBuffer, wBuffer){
    let j, j1, j2, j3, l;
    let x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i;

    let a = new Float64Array(aBuffer);
    let w = new Float64Array(wBuffer);

    l = 2;
    if (n > 8) {
        cft1st(n, a, w);
        l = 8;
        while ((l << 2) < n) {
            cftmdl(n, l, a, w);
            l <<= 2;
        }
    }
    if ((l << 2) == n) {
        for (j = 0; j < l; j += 2) {
            j1 = j + l;
            j2 = j1 + l;
            j3 = j2 + l;
            x0r = a[j] + a[j1];
            x0i = -a[j + 1] - a[j1 + 1];
            x1r = a[j] - a[j1];
            x1i = -a[j + 1] + a[j1 + 1];
            x2r = a[j2] + a[j3];
            x2i = a[j2 + 1] + a[j3 + 1];
            x3r = a[j2] - a[j3];
            x3i = a[j2 + 1] - a[j3 + 1];
            a[j] = x0r + x2r;
            a[j + 1] = x0i - x2i;
            a[j2] = x0r - x2r;
            a[j2 + 1] = x0i + x2i;
            a[j1] = x1r - x3i;
            a[j1 + 1] = x1i - x3r;
            a[j3] = x1r + x3i;
            a[j3 + 1] = x1i + x3r;
        }
    } else {
        for (j = 0; j < l; j += 2) {
            j1 = j + l;
            x0r = a[j] - a[j1];
            x0i = -a[j + 1] + a[j1 + 1];
            a[j] += a[j1];
            a[j + 1] = -a[j + 1] - a[j1 + 1];
            a[j1] = x0r;
            a[j1 + 1] = x0i;
        }
    }
}

exports.cft1st = function(n, aBuffer, wBuffer)
{
    let j, k1, k2;
    let wk1r, wk1i, wk2r, wk2i, wk3r, wk3i;
    let x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i;

    let a = new Float64Array(aBuffer);
    let w = new Float64Array(wBuffer);

    x0r = a[0] + a[2];
    x0i = a[1] + a[3];
    x1r = a[0] - a[2];
    x1i = a[1] - a[3];
    x2r = a[4] + a[6];
    x2i = a[5] + a[7];
    x3r = a[4] - a[6];
    x3i = a[5] - a[7];
    a[0] = x0r + x2r;
    a[1] = x0i + x2i;
    a[4] = x0r - x2r;
    a[5] = x0i - x2i;
    a[2] = x1r - x3i;
    a[3] = x1i + x3r;
    a[6] = x1r + x3i;
    a[7] = x1i - x3r;
    wk1r = w[2];
    x0r = a[8] + a[10];
    x0i = a[9] + a[11];
    x1r = a[8] - a[10];
    x1i = a[9] - a[11];
    x2r = a[12] + a[14];
    x2i = a[13] + a[15];
    x3r = a[12] - a[14];
    x3i = a[13] - a[15];
    a[8] = x0r + x2r;
    a[9] = x0i + x2i;
    a[12] = x2i - x0i;
    a[13] = x0r - x2r;
    x0r = x1r - x3i;
    x0i = x1i + x3r;
    a[10] = wk1r * (x0r - x0i);
    a[11] = wk1r * (x0r + x0i);
    x0r = x3i + x1r;
    x0i = x3r - x1i;
    a[14] = wk1r * (x0i - x0r);
    a[15] = wk1r * (x0i + x0r);
    k1 = 0;
    for (j = 16; j < n; j += 16) {
        k1 += 2;
        k2 = 2 * k1;
        wk2r = w[k1];
        wk2i = w[k1 + 1];
        wk1r = w[k2];
        wk1i = w[k2 + 1];
        wk3r = wk1r - 2 * wk2i * wk1i;
        wk3i = 2 * wk2i * wk1r - wk1i;
        x0r = a[j] + a[j + 2];
        x0i = a[j + 1] + a[j + 3];
        x1r = a[j] - a[j + 2];
        x1i = a[j + 1] - a[j + 3];
        x2r = a[j + 4] + a[j + 6];
        x2i = a[j + 5] + a[j + 7];
        x3r = a[j + 4] - a[j + 6];
        x3i = a[j + 5] - a[j + 7];
        a[j] = x0r + x2r;
        a[j + 1] = x0i + x2i;
        x0r -= x2r;
        x0i -= x2i;
        a[j + 4] = wk2r * x0r - wk2i * x0i;
        a[j + 5] = wk2r * x0i + wk2i * x0r;
        x0r = x1r - x3i;
        x0i = x1i + x3r;
        a[j + 2] = wk1r * x0r - wk1i * x0i;
        a[j + 3] = wk1r * x0i + wk1i * x0r;
        x0r = x1r + x3i;
        x0i = x1i - x3r;
        a[j + 6] = wk3r * x0r - wk3i * x0i;
        a[j + 7] = wk3r * x0i + wk3i * x0r;
        wk1r = w[k2 + 2];
        wk1i = w[k2 + 3];
        wk3r = wk1r - 2 * wk2r * wk1i;
        wk3i = 2 * wk2r * wk1r - wk1i;
        x0r = a[j + 8] + a[j + 10];
        x0i = a[j + 9] + a[j + 11];
        x1r = a[j + 8] - a[j + 10];
        x1i = a[j + 9] - a[j + 11];
        x2r = a[j + 12] + a[j + 14];
        x2i = a[j + 13] + a[j + 15];
        x3r = a[j + 12] - a[j + 14];
        x3i = a[j + 13] - a[j + 15];
        a[j + 8] = x0r + x2r;
        a[j + 9] = x0i + x2i;
        x0r -= x2r;
        x0i -= x2i;
        a[j + 12] = -wk2i * x0r - wk2r * x0i;
        a[j + 13] = -wk2i * x0i + wk2r * x0r;
        x0r = x1r - x3i;
        x0i = x1i + x3r;
        a[j + 10] = wk1r * x0r - wk1i * x0i;
        a[j + 11] = wk1r * x0i + wk1i * x0r;
        x0r = x1r + x3i;
        x0i = x1i - x3r;
        a[j + 14] = wk3r * x0r - wk3i * x0i;
        a[j + 15] = wk3r * x0i + wk3i * x0r;
    }
}

exports.cftmdl = function(n, l, aBuffer, wBuffer)
{
    let j, j1, j2, j3, k, k1, k2, m, m2;
    let wk1r, wk1i, wk2r, wk2i, wk3r, wk3i;
    let x0r, x0i, x1r, x1i, x2r, x2i, x3r, x3i;

    let a = new Float64Array(aBuffer);
    let w = new Float64Array(wBuffer);

    m = l << 2;
    for (j = 0; j < l; j += 2) {
        j1 = j + l;
        j2 = j1 + l;
        j3 = j2 + l;
        x0r = a[j] + a[j1];
        x0i = a[j + 1] + a[j1 + 1];
        x1r = a[j] - a[j1];
        x1i = a[j + 1] - a[j1 + 1];
        x2r = a[j2] + a[j3];
        x2i = a[j2 + 1] + a[j3 + 1];
        x3r = a[j2] - a[j3];
        x3i = a[j2 + 1] - a[j3 + 1];
        a[j] = x0r + x2r;
        a[j + 1] = x0i + x2i;
        a[j2] = x0r - x2r;
        a[j2 + 1] = x0i - x2i;
        a[j1] = x1r - x3i;
        a[j1 + 1] = x1i + x3r;
        a[j3] = x1r + x3i;
        a[j3 + 1] = x1i - x3r;
    }
    wk1r = w[2];
    for (j = m; j < l + m; j += 2) {
        j1 = j + l;
        j2 = j1 + l;
        j3 = j2 + l;
        x0r = a[j] + a[j1];
        x0i = a[j + 1] + a[j1 + 1];
        x1r = a[j] - a[j1];
        x1i = a[j + 1] - a[j1 + 1];
        x2r = a[j2] + a[j3];
        x2i = a[j2 + 1] + a[j3 + 1];
        x3r = a[j2] - a[j3];
        x3i = a[j2 + 1] - a[j3 + 1];
        a[j] = x0r + x2r;
        a[j + 1] = x0i + x2i;
        a[j2] = x2i - x0i;
        a[j2 + 1] = x0r - x2r;
        x0r = x1r - x3i;
        x0i = x1i + x3r;
        a[j1] = wk1r * (x0r - x0i);
        a[j1 + 1] = wk1r * (x0r + x0i);
        x0r = x3i + x1r;
        x0i = x3r - x1i;
        a[j3] = wk1r * (x0i - x0r);
        a[j3 + 1] = wk1r * (x0i + x0r);
    }
    k1 = 0;
    m2 = 2 * m;
    for (k = m2; k < n; k += m2) {
        k1 += 2;
        k2 = 2 * k1;
        wk2r = w[k1];
        wk2i = w[k1 + 1];
        wk1r = w[k2];
        wk1i = w[k2 + 1];
        wk3r = wk1r - 2 * wk2i * wk1i;
        wk3i = 2 * wk2i * wk1r - wk1i;
        for (j = k; j < l + k; j += 2) {
            j1 = j + l;
            j2 = j1 + l;
            j3 = j2 + l;
            x0r = a[j] + a[j1];
            x0i = a[j + 1] + a[j1 + 1];
            x1r = a[j] - a[j1];
            x1i = a[j + 1] - a[j1 + 1];
            x2r = a[j2] + a[j3];
            x2i = a[j2 + 1] + a[j3 + 1];
            x3r = a[j2] - a[j3];
            x3i = a[j2 + 1] - a[j3 + 1];
            a[j] = x0r + x2r;
            a[j + 1] = x0i + x2i;
            x0r -= x2r;
            x0i -= x2i;
            a[j2] = wk2r * x0r - wk2i * x0i;
            a[j2 + 1] = wk2r * x0i + wk2i * x0r;
            x0r = x1r - x3i;
            x0i = x1i + x3r;
            a[j1] = wk1r * x0r - wk1i * x0i;
            a[j1 + 1] = wk1r * x0i + wk1i * x0r;
            x0r = x1r + x3i;
            x0i = x1i - x3r;
            a[j3] = wk3r * x0r - wk3i * x0i;
            a[j3 + 1] = wk3r * x0i + wk3i * x0r;
        }
        wk1r = w[k2 + 2];
        wk1i = w[k2 + 3];
        wk3r = wk1r - 2 * wk2r * wk1i;
        wk3i = 2 * wk2r * wk1r - wk1i;
        for (j = k + m; j < l + (k + m); j += 2) {
            j1 = j + l;
            j2 = j1 + l;
            j3 = j2 + l;
            x0r = a[j] + a[j1];
            x0i = a[j + 1] + a[j1 + 1];
            x1r = a[j] - a[j1];
            x1i = a[j + 1] - a[j1 + 1];
            x2r = a[j2] + a[j3];
            x2i = a[j2 + 1] + a[j3 + 1];
            x3r = a[j2] - a[j3];
            x3i = a[j2 + 1] - a[j3 + 1];
            a[j] = x0r + x2r;
            a[j + 1] = x0i + x2i;
            x0r -= x2r;
            x0i -= x2i;
            a[j2] = -wk2i * x0r - wk2r * x0i;
            a[j2 + 1] = -wk2i * x0i + wk2r * x0r;
            x0r = x1r - x3i;
            x0i = x1i + x3r;
            a[j1] = wk1r * x0r - wk1i * x0i;
            a[j1 + 1] = wk1r * x0i + wk1i * x0r;
            x0r = x1r + x3i;
            x0i = x1i - x3r;
            a[j3] = wk3r * x0r - wk3i * x0i;
            a[j3 + 1] = wk3r * x0i + wk3i * x0r;
        }
    }
}

exports.rftfsub = function(n, aBuffer, nc, cBuffer)
{
    let j, k, kk, ks, m;
    let wkr, wki, xr, xi, yr, yi;

    let a = new Float64Array(aBuffer);
    let c = new Float64Array(cBuffer);

    m = n >> 1;
    ks = 2 * nc / m;
    kk = 0;
    for (j = 2; j < m; j += 2) {
        k = n - j;
        kk += ks;
        wkr = 0.5 - c[nc - kk];
        wki = c[kk];
        xr = a[j] - a[k];
        xi = a[j + 1] + a[k + 1];
        yr = wkr * xr - wki * xi;
        yi = wkr * xi + wki * xr;
        a[j] -= yr;
        a[j + 1] -= yi;
        a[k] += yr;
        a[k + 1] -= yi;
    }
}

exports.rftbsub = function(n, aBuffer, nc, cBuffer)
{
    let j, k, kk, ks, m;
    let wkr, wki, xr, xi, yr, yi;

    let a = new Float64Array(aBuffer);
    let c = new Float64Array(cBuffer);

    a[1] = -a[1];
    m = n >> 1;
    ks = 2 * nc / m;
    kk = 0;
    for (j = 2; j < m; j += 2) {
        k = n - j;
        kk += ks;
        wkr = 0.5 - c[nc - kk];
        wki = c[kk];
        xr = a[j] - a[k];
        xi = a[j + 1] + a[k + 1];
        yr = wkr * xr + wki * xi;
        yi = wkr * xi - wki * xr;
        a[j] -= yr;
        a[j + 1] = yi - a[j + 1];
        a[k] += yr;
        a[k + 1] = yi - a[k + 1];
    }
    a[m + 1] = -a[m + 1];
}
<|endoftext|>


<commit_before>import React, {Component, PropTypes} from "react/addons"
import Dispatcher from "./Dispatcher"

/**
 * StoreReceiver is a component factory that wraps a component
 * and lets it get data from all the stores defined in its statics
 * as props instead of state.
 *
 * enables the wrapped (or composed) component to be stateless and
 * therefore, more easily testable.
 *
 * example:
 *
 * class Post extends Component {
 *   static stores = {
 *     // StoreDisplayName : "propName"
 *     PostStore : "post",
 *   }
 *   render() {
 *     return (
 *

 *
{this.props.post.title}

 *

 *     )
 *   }
 * }
 *
 * wraps the component
 * export default StoreReceiver(Post)
 */
export default (ComposedComponent) => {

  if(typeof ComposedComponent.stores !== "object") {
    const name = ComposedComponent.name
    throw new TypeError(
      `StoreReceiver Error : ` +
      `missing "stores" parameter in ${name} component class.`
    )
  }

  const stores = ComposedComponent.stores
  const initialState = Object.keys(stores).reduce((acc, key) => {
      acc[stores[key]] = null
      return acc
    },
    {}
  )

  return class StoreReceiver extends Component {

    static contextTypes = {
      dispatcher : PropTypes.instanceOf(Dispatcher),
    }

    state = initialState

    constructor() {
      this.updateStateFromStore = this.updateStateFromStore.bind(this)
    }

    getStore(name) {
      return this.context.dispatcher.getStore(name)
    }

    forEachStore(func) {
      Object.keys(stores)
        .forEach((key) => {
          func(
            this.getStore(key),
            key,
            stores[key]
          )
        })
    }

    // used to get the store's initial state before first render
    componentWillMount() {
      const nextState = {}
      this.forEachStore((store, key, propName) => {
        nextState[propName] = store.state
      })
      this.setState(nextState)
    }

    componentDidMount() {
      this.forEachStore((store) => {
        store.addChangeListener(this.updateStateFromStore)
      })
    }

    componentWillUnmount() {
      this.forEachStore((store) => {
        store.removeChangeListener(this.updateStateFromStore)
      })
    }

    updateStateFromStore(displayName) {
      const name = stores[displayName]
      this.setState({
        [name] : this.getStore(displayName).state,
      })
    }

    render() {
      return (
        <ComposedComponent {...this.props} {...this.state}/>
      )
    }
  }
}
<commit_msg>fixed syntax issue in StoreReceiver<commit_after>import React, {Component, PropTypes} from "react/addons"
import Dispatcher from "./Dispatcher"

/**
 * StoreReceiver is a component factory that wraps a component
 * and lets it get data from all the stores defined in its statics
 * as props instead of state.
 *
 * enables the wrapped (or composed) component to be stateless and
 * therefore, more easily testable.
 *
 * example:
 *
 * class Post extends Component {
 *   static stores = {
 *     // StoreDisplayName : "propName"
 *     PostStore : "post",
 *   }
 *   render() {
 *     return (
 *

 *
{this.props.post.title}

 *

 *     )
 *   }
 * }
 *
 * wraps the component
 * export default StoreReceiver(Post)
 */
export default (ComposedComponent) => {

  if(typeof ComposedComponent.stores !== "object") {
    const name = ComposedComponent.name
    throw new TypeError(
      `StoreReceiver Error : ` +
      `missing "stores" parameter in ${name} component class.`
    )
  }

  const stores = ComposedComponent.stores
  const initialState = Object.keys(stores).reduce(
    (acc, key) => {
      acc[stores[key]] = null
      return acc
    },
    {}
  )

  return class StoreReceiver extends Component {

    static contextTypes = {
      dispatcher : PropTypes.instanceOf(Dispatcher),
    }

    state = initialState

    constructor() {
      this.updateStateFromStore = this.updateStateFromStore.bind(this)
    }

    getStore(name) {
      return this.context.dispatcher.getStore(name)
    }

    forEachStore(func) {
      Object.keys(stores)
        .forEach((key) => {
          func(
            this.getStore(key),
            key,
            stores[key]
          )
        })
    }

    // used to get the store's initial state before first render
    componentWillMount() {
      const nextState = {}
      this.forEachStore((store, key, propName) => {
        nextState[propName] = store.state
      })
      this.setState(nextState)
    }

    componentDidMount() {
      this.forEachStore((store) => {
        store.addChangeListener(this.updateStateFromStore)
      })
    }

    componentWillUnmount() {
      this.forEachStore((store) => {
        store.removeChangeListener(this.updateStateFromStore)
      })
    }

    updateStateFromStore(displayName) {
      const name = stores[displayName]
      this.setState({
        [name] : this.getStore(displayName).state,
      })
    }

    render() {
      return (
        <ComposedComponent {...this.props} {...this.state}/>
      )
    }
  }
}
<|endoftext|>


<commit_before>#!/usr/local/bin/asteria-run

var s = require('system');

var rl, running = true;
var quit = function () { running = false; return "Goodbye!"; }

function repl() {
	while(running) {
		var line = rl.readline('> ');
		if(line.length > 0) {
			rl.add_history(line);
			try {
				print(eval(line), '\n');
			} catch(ex) {
				print(ex, '\n');
			}
		}
	}
}

s.system('clear');
print('-- Welcome to the asteria repl.', '\n');

// Check for the GNU readline module
// If not available, fall back to standard
// stdin functions.

if(checkModule('readline')) {
	rl = require('readline');
} else {
	print('-- GNU readline not available. Falling back to raw stdin.', '\n');
	rl = new Object();
	rl.readline = function(p) {
		s.stdout.write(p);
		s.stdout.flush();
		return s.stdin.readLine();
	}
	rl.add_history = function (x) { /* dummy */ }
}

print('-- Execute quit() to leave.', '\n\n');

// -- Enter the loop
repl();
<commit_msg>prompt as function<commit_after>#!/usr/local/bin/asteria-run

var s = require('system');

var rl, running = true;
var quit = function () { running = false; return "Goodbye!"; }

function prompt() {
	return '> ';
}

function repl() {
	while(running) {
		var line = rl.readline(prompt());
		if(line.length > 0) {
			rl.add_history(line);
			try {
				print(eval(line), '\n');
			} catch(ex) {
				print(ex, '\n');
			}
		}
	}
}

s.system('clear');
print('-- Welcome to the asteria repl.', '\n');

// Check for the GNU readline module
// If not available, fall back to standard
// stdin functions.

if(checkModule('readline')) {
	rl = require('readline');
} else {
	print('-- GNU readline not available. Falling back to raw stdin.', '\n');
	rl = new Object();
	rl.readline = function(p) {
		s.stdout.write(p);
		s.stdout.flush();
		return s.stdin.readLine();
	}
	rl.add_history = function (x) { /* dummy */ }
}

print('-- Execute quit() to leave.', '\n\n');

// -- Enter the loop
repl();
<|endoftext|>


<commit_before>function register() {
  window.location = 'https://api.twitch.tv/kraken/oauth2/authorize?response_type=token&client_id=cx94gjhz4ful945h0a3b4hbntiscia&redirect_uri=http://nico.kuro.ml/register&scope=chat_login';
}

function check() {
  var parser = document.createElement('a');
  parser.href = window.location.href;

  if (parser.hash.indexOf('#access_token=') > -1 && parser.hash.indexOf('&scope=chat_login') > -1) {
    //document.getElementById('url').style.visibility = 'visible';
    generate();
  } else {
    //document.getElementById('url').style.visibility = 'hidden';
  }
}

function generate() {
  //var chanName = document.getElementById('chanID');
  var chanName = 'creditsToKuromachii'
  var parser = document.createElement('a');
  parser.href = window.location.href;
  var hash = parser.hash.replace('#access_token=','')
  hash = hash.replace('&scope=chat_login','')

  window.location = 'http://nico.kuro.ml/chat?token='+hash+'&chan_name='+chanName;
}

function load() {
  var parser = document.createElement('a');
  parser.href = window.location.href;
  var token = parser.search.split("&chan_name=")[0].split("token=")[1];
  var channelName = parser.search.split('&chan_name=').pop();

  console.log(token);
  chat(token,channelName);
}

function chat(token,channelName) {
    var oauth = token;

    // You have to run .setup() before anything besides .listen()
    TAPIC.setup(oauth, function (username) {

      // By default, TAPIC refreshes API information every 5 seconds, which is the minimum.
      // Setting the refresh rate is optional.
      TAPIC.setRefreshRate(10);

      // This is also required for a lot of things to work
      TAPIC.joinChannel(username, function () {
            tests();
        });
    });

    // EventListeners
    TAPIC.listen('raw', function (e) {
      // You really don't NEED to see raw messages. But you can if you want.
      // You can also manually parse the raw messages if you don't trust TAPIC.js
      // writeChat( '* ' + e );
        console.info(e);
    });
    TAPIC.listen('message', function (e) {
      var output = (e.mod ? '' : '') +
        (e.sub  ?'' : '') +
        (e.turbo ? '' : '') +
        (e.streamer ? '' : '') +
        '' +
        e.from +
        '' +
        (e.action ? '' : ':  ') +
        e.text +
        (e.action ? '' : '' );
        // e.emotes is the emotes, e.g. '25:0-4,12-16/1902:6-10'
        // https://github.com/justintv/Twitch-API/blob/master/IRC.md#privmsg
        // e.badges is an array of badges: https://discuss.dev.twitch.tv/t/beta-badge-api/6388
      writeChat( output );
    });
    TAPIC.listen('echoChat', function (e) {
      var output = '' + TAPIC.getDisplayName() +
        ' : ' + e;
      writeChat( output );
    });
}

// This is for the webpage's chat, it doesn't have anything directly to do with TAPIC.js
function writeChat(msg) {
  document.getElementById('chat').innerHTML += msg + '
';
  document.getElementById('chat').scrollTop = Number.MAX_SAFE_INTEGER;
}
<commit_msg>Corrections<commit_after>function register() {
  window.location = 'https://api.twitch.tv/kraken/oauth2/authorize?response_type=token&client_id=cx94gjhz4ful945h0a3b4hbntiscia&redirect_uri=http://nico.kuro.ml/index.htm&scope=chat_login';
}

function check() {
  var parser = document.createElement('a');
  parser.href = window.location.href;

  if (parser.hash.indexOf('#access_token=') > -1 && parser.hash.indexOf('&scope=chat_login') > -1) {
    //document.getElementById('url').style.visibility = 'visible';
    generate();
  } else {
    //document.getElementById('url').style.visibility = 'hidden';
  }
}

function generate() {
  //var chanName = document.getElementById('chanID');
  var chanName = 'creditsToKuromachii'
  var parser = document.createElement('a');
  parser.href = window.location.href;
  var hash = parser.hash.replace('#access_token=','')
  hash = hash.replace('&scope=chat_login','')

  window.location = 'http://nico.kuro.ml/chat?token='+hash+'&chan_name='+chanName;
}

function load() {
  var parser = document.createElement('a');
  parser.href = window.location.href;
  var token = parser.search.split("&chan_name=")[0].split("token=")[1];
  var channelName = parser.search.split('&chan_name=').pop();

  console.log(token);
  chat(token,channelName);
}

function chat(token,channelName) {
    var oauth = token;

    // You have to run .setup() before anything besides .listen()
    TAPIC.setup(oauth, function (username) {

      // By default, TAPIC refreshes API information every 5 seconds, which is the minimum.
      // Setting the refresh rate is optional.
      TAPIC.setRefreshRate(10);

      // This is also required for a lot of things to work
      TAPIC.joinChannel(username, function () {
            tests();
        });
    });

    // EventListeners
    TAPIC.listen('raw', function (e) {
      // You really don't NEED to see raw messages. But you can if you want.
      // You can also manually parse the raw messages if you don't trust TAPIC.js
      // writeChat( '* ' + e );
        console.info(e);
    });
    TAPIC.listen('message', function (e) {
      var output = (e.mod ? '' : '') +
        (e.sub  ?'' : '') +
        (e.turbo ? '' : '') +
        (e.streamer ? '' : '') +
        '' +
        e.from +
        '' +
        (e.action ? '' : ':  ') +
        e.text +
        (e.action ? '' : '' );
        // e.emotes is the emotes, e.g. '25:0-4,12-16/1902:6-10'
        // https://github.com/justintv/Twitch-API/blob/master/IRC.md#privmsg
        // e.badges is an array of badges: https://discuss.dev.twitch.tv/t/beta-badge-api/6388
      writeChat( output );
    });
    TAPIC.listen('echoChat', function (e) {
      var output = '' + TAPIC.getDisplayName() +
        ' : ' + e;
      writeChat( output );
    });
}

// This is for the webpage's chat, it doesn't have anything directly to do with TAPIC.js
function writeChat(msg) {
  document.getElementById('chat').innerHTML += msg + '
';
  document.getElementById('chat').scrollTop = Number.MAX_SAFE_INTEGER;
}
<|endoftext|>


<commit_before>'use strict';

var d3 = require('d3');
var queries = require('../../helpers/queries');
var utils = require('../../helpers/utils');

exports.getData = {
	plugins: {
        'crumb': {
            skip: true
        }
    },
    handler: function(request, reply) {

        var sequelize = request.server.plugins.sequelize.db.sequelize;

        var userId = request.auth.credentials.id;

        var queryString = queries.cards(userId);

        // API CODE
		sequelize.query(queryString, {
		        type: sequelize.QueryTypes.SELECT
		    }).then(function(rows) {

	            var overviewResponse = utils.flatten(rows[0]);

	            var cardsResponse = utils.flatten(rows[1]);

	            var blockResponse = utils.flatten(rows[2]);

	            var panchayatResponse = utils.flatten(rows[3]);

	            var notificationsResponse = utils.flatten(rows[4]);

	            // Parse the overview response
	           	var current_total = overviewResponse[0].current_total;
	            var delayed_total = overviewResponse[0].delayed_total;
	            var days_to_payment = overviewResponse[0].time_to_payment;
	            var total_transactions = overviewResponse[0].total_transactions;
	            console.log(days_to_payment)
	            // Nest the cards response and include the overview stats
	            var cards = d3.nest()
	                .key(function(d) {
	                    return d.staff_id;
	                })
	                .rollup(function(v) {
	                    return {
	                        'name': v[0].name,
	                        'staff_id': v[0].staff_id,
	                        'designation': v[0].task_assign,
	                        'mobile':v[0].mobile_no,
	                        'block_name':v[0].block_name,
		        			'current_total':v[0].current_total,
		        			'delayed_total':v[0].delayed_total,
	                        'delayed_musters': v.filter(function(d) { return d.type==='delayed_musters'; }).map(function(d) {
	                            return [
	                                {
	                                	'msr_no':d.msr_no,
	                                	'panchayat_name':d.panchayat_name,
	                                	'work_name':d.work_name,
	                                	'work_code':d.work_code,
	                                	'closure_date':d.end_date,
	                                	'days_pending':d.days_pending
	                            	}
	                            ];
	                        }),
	                       	'current_musters': v.filter(function(d) { return d.type==='current_musters'; }).map(function(d) {
	                            return [
	                                {
	                                	'msr_no':d.msr_no,
	                                	'panchayat_name':d.panchayat_name,
	                                	'work_name':d.work_name,
	                                	'work_code':d.work_code,
	                                	'closure_date':d.end_date
	                            	}
	                            ];
	                        })
	                    };
	                })
	                .entries(cardsResponse)
	                .map(function(d) {
	                    return d.values;
	                });

	            // Nest the block response
	            var blockPerformance = d3.nest()
	                .key(function(d) {
	                    return d.block_code;
	                })
	                .rollup(function(v) {
	                    return {
	                        'block_code': v[0].block_code,
	                        'block_name': v[0].block_name,
	                        'data': v.map(function(d) {
	                            return [
	                                d.date.getFullYear() + '' + utils.padNum(d.date.getMonth() + 1) + '' + utils.padNum(d.date.getDate()),
	                                d.mrc_mre,
	                                d.mre_wlg,
	                                d.wlg_wls,
	                                d.wls_fto,
	                                d.fto_sn1,
	                                d.sn1_sn2,
	                                d.sn2_prc,
	                                d.tot_trn
	                            ];
	                        })
	                    };
	                })
	                .entries(blockResponse)
	                .map(function(d) {
	                    return d.values;
	                })
	                .sort(function(a, b) {
	                    var aTarget = a.data[a.data.length - 1];
	                    var bTarget = b.data[b.data.length - 1];
	                    var aSum = aTarget[1] + aTarget[2] + aTarget[3] + aTarget[4] + aTarget[5] + aTarget[6] + aTarget[7];
	                    var bSum = bTarget[1] + bTarget[2] + bTarget[3] + bTarget[4] + bTarget[5] + bTarget[6] + bTarget[7];
	                    return bSum - aSum;
	                });

	            // Nest the panchayat response
	            var panchayatPerformance = d3.nest()
	                .key(function(d) {
	                    return d.panchayat_code;
	                })
	                .rollup(function(v) {
	                    return {
	                    	'block_code': v[0].block_code,
	                        'panchayat_code': v[0].panchayat_code,
	                        'panchayat_name': v[0].panchayat_name,
	                        'data': v.map(function(d) {
	                            return [
	                                d.date.getFullYear() + '' + utils.padNum(d.date.getMonth() + 1) + '' + utils.padNum(d.date.getDate()),
	                                d.mrc_mre,
	                                d.mre_wlg,
	                                d.wlg_wls,
	                                d.wls_fto,
	                                d.fto_sn1,
	                                d.sn1_sn2,
	                                d.sn2_prc,
	                                d.tot_trn
	                            ];
	                        })
	                    };
	                })
	                .entries(panchayatResponse)
	                .map(function(d) {
	                    return d.values;
	                })
	                .sort(function(a, b) {
	                    var aTarget = a.data[a.data.length - 1];
	                    var bTarget = b.data[b.data.length - 1];
	                    var aSum = aTarget[1] + aTarget[2] + aTarget[3] + aTarget[4] + aTarget[5] + aTarget[6] + aTarget[7];
	                    var bSum = bTarget[1] + bTarget[2] + bTarget[3] + bTarget[4] + bTarget[5] + bTarget[6] + bTarget[7];
	                    return bSum - aSum;
	                });

            	var headers = ['date', 'mrc_mre', 'mre_wlg', 'wlg_wls', 'wls_fto', 'fto_sn1', 'sn1_sn2', 'sn2_prc', 'tot_trn'];

	            var data = {
		        	'overview': {
		        		'current_total':current_total,
		        		'delayed_total':delayed_total,
		        		'days_to_payment':days_to_payment,
		        		'total_transactions':total_transactions,
		        		'cards_total': cards.length
		        	},
		        	'cards': cards,
		        	'block_performance': blockPerformance,
		        	'panchayat_performance': panchayatPerformance,
		        	'notifications': notificationsResponse,
		        	'config': {
		        		'headers': headers,
		        		labels: [
		        			'Date',
		        		    'Muster roll closure to muster roll entry',
		        		    'Muster roll entry to wage list generation',
		        		    'Wage list generation to wage list signing',
		        		    'Wage list signing to FTO generation',
		        		    'FTO generation to first signature',
		        		    'First signature to second signature',
		        		    'Second signature to processed by bank',
		        		    'Total Transactions'
		        		],
		        	}
		        };
		        console.log(cards)
	            reply(data);
		    });
    }
};
<commit_msg>Remove console message<commit_after>'use strict';

var d3 = require('d3');
var queries = require('../../helpers/queries');
var utils = require('../../helpers/utils');

exports.getData = {
	plugins: {
        'crumb': {
            skip: true
        }
    },
    handler: function(request, reply) {

        var sequelize = request.server.plugins.sequelize.db.sequelize;

        var userId = request.auth.credentials.id;

        var queryString = queries.cards(userId);

        // API CODE
		sequelize.query(queryString, {
		        type: sequelize.QueryTypes.SELECT
		    }).then(function(rows) {

	            var overviewResponse = utils.flatten(rows[0]);

	            var cardsResponse = utils.flatten(rows[1]);

	            var blockResponse = utils.flatten(rows[2]);

	            var panchayatResponse = utils.flatten(rows[3]);

	            var notificationsResponse = utils.flatten(rows[4]);

	            // Parse the overview response
	           	var current_total = overviewResponse[0].current_total;
	            var delayed_total = overviewResponse[0].delayed_total;
	            var days_to_payment = overviewResponse[0].time_to_payment;
	            var total_transactions = overviewResponse[0].total_transactions;
	            console.log(days_to_payment)
	            // Nest the cards response and include the overview stats
	            var cards = d3.nest()
	                .key(function(d) {
	                    return d.staff_id;
	                })
	                .rollup(function(v) {
	                    return {
	                        'name': v[0].name,
	                        'staff_id': v[0].staff_id,
	                        'designation': v[0].task_assign,
	                        'mobile':v[0].mobile_no,
	                        'block_name':v[0].block_name,
		        			'current_total':v[0].current_total,
		        			'delayed_total':v[0].delayed_total,
	                        'delayed_musters': v.filter(function(d) { return d.type==='delayed_musters'; }).map(function(d) {
	                            return [
	                                {
	                                	'msr_no':d.msr_no,
	                                	'panchayat_name':d.panchayat_name,
	                                	'work_name':d.work_name,
	                                	'work_code':d.work_code,
	                                	'closure_date':d.end_date,
	                                	'days_pending':d.days_pending
	                            	}
	                            ];
	                        }),
	                       	'current_musters': v.filter(function(d) { return d.type==='current_musters'; }).map(function(d) {
	                            return [
	                                {
	                                	'msr_no':d.msr_no,
	                                	'panchayat_name':d.panchayat_name,
	                                	'work_name':d.work_name,
	                                	'work_code':d.work_code,
	                                	'closure_date':d.end_date
	                            	}
	                            ];
	                        })
	                    };
	                })
	                .entries(cardsResponse)
	                .map(function(d) {
	                    return d.values;
	                });

	            // Nest the block response
	            var blockPerformance = d3.nest()
	                .key(function(d) {
	                    return d.block_code;
	                })
	                .rollup(function(v) {
	                    return {
	                        'block_code': v[0].block_code,
	                        'block_name': v[0].block_name,
	                        'data': v.map(function(d) {
	                            return [
	                                d.date.getFullYear() + '' + utils.padNum(d.date.getMonth() + 1) + '' + utils.padNum(d.date.getDate()),
	                                d.mrc_mre,
	                                d.mre_wlg,
	                                d.wlg_wls,
	                                d.wls_fto,
	                                d.fto_sn1,
	                                d.sn1_sn2,
	                                d.sn2_prc,
	                                d.tot_trn
	                            ];
	                        })
	                    };
	                })
	                .entries(blockResponse)
	                .map(function(d) {
	                    return d.values;
	                })
	                .sort(function(a, b) {
	                    var aTarget = a.data[a.data.length - 1];
	                    var bTarget = b.data[b.data.length - 1];
	                    var aSum = aTarget[1] + aTarget[2] + aTarget[3] + aTarget[4] + aTarget[5] + aTarget[6] + aTarget[7];
	                    var bSum = bTarget[1] + bTarget[2] + bTarget[3] + bTarget[4] + bTarget[5] + bTarget[6] + bTarget[7];
	                    return bSum - aSum;
	                });

	            // Nest the panchayat response
	            var panchayatPerformance = d3.nest()
	                .key(function(d) {
	                    return d.panchayat_code;
	                })
	                .rollup(function(v) {
	                    return {
	                    	'block_code': v[0].block_code,
	                        'panchayat_code': v[0].panchayat_code,
	                        'panchayat_name': v[0].panchayat_name,
	                        'data': v.map(function(d) {
	                            return [
	                                d.date.getFullYear() + '' + utils.padNum(d.date.getMonth() + 1) + '' + utils.padNum(d.date.getDate()),
	                                d.mrc_mre,
	                                d.mre_wlg,
	                                d.wlg_wls,
	                                d.wls_fto,
	                                d.fto_sn1,
	                                d.sn1_sn2,
	                                d.sn2_prc,
	                                d.tot_trn
	                            ];
	                        })
	                    };
	                })
	                .entries(panchayatResponse)
	                .map(function(d) {
	                    return d.values;
	                })
	                .sort(function(a, b) {
	                    var aTarget = a.data[a.data.length - 1];
	                    var bTarget = b.data[b.data.length - 1];
	                    var aSum = aTarget[1] + aTarget[2] + aTarget[3] + aTarget[4] + aTarget[5] + aTarget[6] + aTarget[7];
	                    var bSum = bTarget[1] + bTarget[2] + bTarget[3] + bTarget[4] + bTarget[5] + bTarget[6] + bTarget[7];
	                    return bSum - aSum;
	                });

            	var headers = ['date', 'mrc_mre', 'mre_wlg', 'wlg_wls', 'wls_fto', 'fto_sn1', 'sn1_sn2', 'sn2_prc', 'tot_trn'];

	            var data = {
		        	'overview': {
		        		'current_total':current_total,
		        		'delayed_total':delayed_total,
		        		'days_to_payment':days_to_payment,
		        		'total_transactions':total_transactions,
		        		'cards_total': cards.length
		        	},
		        	'cards': cards,
		        	'block_performance': blockPerformance,
		        	'panchayat_performance': panchayatPerformance,
		        	'notifications': notificationsResponse,
		        	'config': {
		        		'headers': headers,
		        		labels: [
		        			'Date',
		        		    'Muster roll closure to muster roll entry',
		        		    'Muster roll entry to wage list generation',
		        		    'Wage list generation to wage list signing',
		        		    'Wage list signing to FTO generation',
		        		    'FTO generation to first signature',
		        		    'First signature to second signature',
		        		    'Second signature to processed by bank',
		        		    'Total Transactions'
		        		],
		        	}
		        };

	            reply(data);
		    });
    }
};
<|endoftext|>


<commit_before>/* eslint-env jest */

const mockGoogleDisplayAd = jest.fn()
const mockMockDisplayAd = jest.fn()
jest.mock('../google/googleDisplayAd', () => mockGoogleDisplayAd)
jest.mock('../mockDisplayAd', () => mockMockDisplayAd)

beforeEach(() => {
  jest.clearAllMocks()
  jest.resetModules()
})

describe('displayAd', function () {
  it('calls mockDisplayAd when ads are not enabled', () => {
    jest.mock('../adsEnabledStatus', () => false)
    const displayAd = require('../displayAd').default
    displayAd('my-ad')
    expect(mockGoogleDisplayAd).not.toHaveBeenCalled()
    expect(mockMockDisplayAd).toHaveBeenCalledWith('my-ad')
  })

  it('calls googleDisplayAd when ads are enabled', () => {
    jest.mock('../adsEnabledStatus', () => true)
    const displayAd = require('../displayAd').default
    displayAd('some-ad')
    expect(mockGoogleDisplayAd).toHaveBeenCalledWith('some-ad')
    expect(mockMockDisplayAd).not.toHaveBeenCalled()
  })
})
<commit_msg>Fix broken tests<commit_after>/* eslint-env jest */

const mockGoogleDisplayAd = jest.fn()
const mockMockDisplayAd = jest.fn()
jest.mock('../google/googleDisplayAd', () => mockGoogleDisplayAd)
jest.mock('../mockDisplayAd', () => mockMockDisplayAd)

beforeEach(() => {
  jest.clearAllMocks()
  jest.resetModules()
})

describe('displayAd', function () {
  it('calls mockDisplayAd when ads are not enabled', () => {
    jest.mock('../adsEnabledStatus', () => () => false)
    const displayAd = require('../displayAd').default
    displayAd('my-ad')
    expect(mockGoogleDisplayAd).not.toHaveBeenCalled()
    expect(mockMockDisplayAd).toHaveBeenCalledWith('my-ad')
  })

  it('calls googleDisplayAd when ads are enabled', () => {
    jest.mock('../adsEnabledStatus', () => () => true)
    const displayAd = require('../displayAd').default
    displayAd('some-ad')
    expect(mockGoogleDisplayAd).toHaveBeenCalledWith('some-ad')
    expect(mockMockDisplayAd).not.toHaveBeenCalled()
  })
})
<|endoftext|>


<commit_before>/**
 * Created by hen on 3/8/14.
 */

var margin = {
    top: 50,
    right: 50,
    bottom: 50,
    left: 50
};

var width = 1060 - margin.left - margin.right;
var height = 800 - margin.bottom - margin.top;
var centered;

var bbVis = {
    x: 100,
    y: 10,
    w: width - 100,
    h: 300
};

var detailVis = d3.select("#detailVis").append("svg").attr({
    width:350,
    height:200
})

var canvas = d3.select("#vis").append("svg").attr({
    width: width + margin.left + margin.right,
    height: height + margin.top + margin.bottom
    })

var svg = canvas.append("g").attr({
        transform: "translate(" + margin.left + "," + margin.top + ")"
    });

// for bar chart detail Vis
var x = d3.scale.ordinal().rangeRoundBands([0, width], .05);

var y = d3.scale.linear().range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .tickFormat(d3.time.format("%Y-%m"));

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .ticks(10);

var projection = d3.geo.albersUsa().translate([width / 2, height / 2]);//.precision(.1);
var path = d3.geo.path().projection(projection);
var dataSet = {};

function clicked(d) {
  var x, y, k;

  if (d && centered !== d) {
    var centroid = path.centroid(d);
    x = centroid[0];
    y = centroid[1];
    k = 4;
    centered = d;
  } else {
    x = width / 2;
    y = height / 2;
    k = 1;
    centered = null;
  }

  svg.selectAll("path")
      .classed("active", centered && function(d) { return d === centered; });

  svg.transition()
      .duration(750)
      .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + k + ")translate(" + -x + "," + -y + ")")
      .style("stroke-width", 1.5 / k + "px");
}

function zoom() {
  svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}

function loadStations(complete) {
    d3.csv("../data/NSRDB_StationsMeta.csv",function(error,data){
        console.log(complete);
        //tooltip function created

        //summed
        summation = function(d){
            result = 0;
            arrayOfMonths = new Array(12);
            arrayOfMonths[0] =  complete["Jan"][d.USAF]
            arrayOfMonths[1] =  complete["Feb"][d.USAF]
            arrayOfMonths[2] =  complete["Mar"][d.USAF]
            arrayOfMonths[3] =  complete["Apr"][d.USAF]
            arrayOfMonths[4] =  complete["May"][d.USAF]
            arrayOfMonths[5] =  complete["Jun"][d.USAF]
            arrayOfMonths[6] =  complete["Jul"][d.USAF]
            arrayOfMonths[7] =  complete["Aug"][d.USAF]
            arrayOfMonths[8] =  complete["Sep"][d.USAF]
            arrayOfMonths[9] =  complete["Oct"][d.USAF]
            arrayOfMonths[10] =  complete["Nov"][d.USAF]
            arrayOfMonths[11] =  complete["Dec"][d.USAF]

            for (t=0; t<arrayOfMonths.length; t++){
               if (arrayOfMonths[t] != undefined){
                result += arrayOfMonths[t].sum;
                }
            }

            return result;

        }

        console.log(summation(data[0]), data[0]);

        var tip = d3.tip()

        .attr('class', 'd3-tip')
        .offset([-10, 0])
        .html(function(d) {
            return d.STATION + '
' + "sum = " + summation(d);
        })

        svg.call(tip);

        // add circles
        var circle = svg.selectAll(".circles")
        .data(data).enter()
        .append("circle")
        .attr("r", 2 ) //function(d,i){return d}
        .attr("transform", function(d){return "translate(" + projection([d.NSRDB_LON,d.NSRDB_LAT]) + ")";})
        .on("mouseover",tip.show)
        .on("mouseout",tip.hide)
        .on("click",clicked);

        // circle.append("g")
        // .call(d3.behavior.zoom().scaleExtent([1, 8]).on("zoom", zoom))
        // .append("g");

        // svg.append("rect")
        // .attr("class", "overlay")
        // .attr("width", width)
        // .attr("height", height);

        // svg.attr("transform", function(d) { return "translate(" + d + ")"; });
        //console.log(data.station);//....map every station to a circle on the map
    });
}

function loadStats() {

     d3.json("../data/reducedMonthStationHour2003_2004.json", function(error,data){
        completeDataSet= data;
        console.log(completeDataSet);

        loadStations(completeDataSet);
     })

}

d3.json("../data/us-named.json", function(error, data) {
    //creates map
    var usMap = topojson.feature(data,data.objects.states).features
    //console.log(usMap);

    //var screencoord = projection([-71.060168, 42.360024]);
    //console.log(screencoord);

    svg.selectAll(".country").data(usMap).enter()
    .append("path")
    .attr("d",path)
    .attr("fill","purple")
    .on("click",clicked);

    loadStats();

    //zoomToBB();
});

//creates bar chart
var createDetailVis = function(){

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

//     //var chart = d3.select("body")

  //   svg.append("g")
  //     .attr("class", "x axis")
  //     .attr("transform", "translate(0," + height + ")")
  //     .call(xAxis)
  //   .selectAll("text")
  //     .style("text-anchor", "end")
  //     .attr("dx", "-.8em")
  //     .attr("dy", "-.55em")
  //     .attr("transform", "rotate(-90)" );

  // svg.append("g")
  //     .attr("class", "y axis")
  //     .call(yAxis)
  //   .append("text")
  //     .attr("transform", "rotate(-90)")
  //     .attr("y", 6)
  //     .attr("dy", ".71em")
  //     .style("text-anchor", "end")
  //     .text("Value ($)");

  // svg.selectAll("bar")
  //     .data(data)
  //   .enter().append("rect")
  //     .style("fill", "steelblue")
  //     .attr("x", function(d) { return x(d.date); })
  //     .attr("width", x.rangeBand())
  //     .attr("y", function(d) { return y(d.value); })
  //     .attr("height", function(d) { return height - y(d.value); });

}

var updateDetailVis = function(data, name){

}

// ZOOMING
function zoomToBB() {

}

function resetZoom() {

}

<commit_msg>Update GeoUSA.js<commit_after>/**
 * Created by hen on 3/8/14.
 */

var margin = {
    top: 50,
    right: 50,
    bottom: 50,
    left: 50
};

var width = 1060 - margin.left - margin.right;
var height = 800 - margin.bottom - margin.top;
var centered;
var barHeight = 20;

var bbVis = {
    x: 100,
    y: 10,
    w: width - 100,
    h: 300
};

var bbDetail = {
    x: 100,
    y: 10,
    w: width - 100,
    h: 100
};

var detailVis = d3.select("#detailVis").append("svg").attr({
    width:350,
    height:200
})

var canvas = d3.select("#vis").append("svg").attr({
    width: width + margin.left + margin.right,
    height: height + margin.top + margin.bottom
    })

var svg = canvas.append("g").attr({
        transform: "translate(" + margin.left + "," + margin.top + ")"
    });

var projection = d3.geo.albersUsa().translate([width / 2, height / 2]);//.precision(.1);
var path = d3.geo.path().projection(projection);
var dataSet = {};

function clicked(d) {
  var x, y, k;

  if (d && centered !== d) {
    var centroid = path.centroid(d);
    x = centroid[0];
    y = centroid[1];
    k = 4;
    centered = d;
  } else {
    x = width / 2;
    y = height / 2;
    k = 1;
    centered = null;
  }

  svg.selectAll("path")
      .classed("active", centered && function(d) { return d === centered; });

  svg.transition()
      .duration(750)
      .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + k + ")translate(" + -x + "," + -y + ")")
      .style("stroke-width", 1.5 / k + "px");
}

function zoom() {
  svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}

function loadStations(complete) {
    d3.csv("../data/NSRDB_StationsMeta.csv",function(error,data){

        //console.log(data);
        // aggregated values for each station
        summation = function(d){
            result = 0;
            arrayOfMonths = new Array(12);
            arrayOfMonths[0] =  complete["Jan"][d.USAF]
            arrayOfMonths[1] =  complete["Feb"][d.USAF]
            arrayOfMonths[2] =  complete["Mar"][d.USAF]
            arrayOfMonths[3] =  complete["Apr"][d.USAF]
            arrayOfMonths[4] =  complete["May"][d.USAF]
            arrayOfMonths[5] =  complete["Jun"][d.USAF]
            arrayOfMonths[6] =  complete["Jul"][d.USAF]
            arrayOfMonths[7] =  complete["Aug"][d.USAF]
            arrayOfMonths[8] =  complete["Sep"][d.USAF]
            arrayOfMonths[9] =  complete["Oct"][d.USAF]
            arrayOfMonths[10] =  complete["Nov"][d.USAF]
            arrayOfMonths[11] =  complete["Dec"][d.USAF]

            for (t=0; t<arrayOfMonths.length; t++){
               if (arrayOfMonths[t] != undefined){
                result += arrayOfMonths[t].sum;
                }
            }

            return result;

        }

        //console.log(summation(data[0]), data[0]);

        //tooltip function created
        var tip = d3.tip()
        .attr('class', 'd3-tip')
        .offset([-10, 0])
        .html(function(d) {
            return d.STATION + '
' + "sum = " + summation(d);
        })

        svg.call(tip);

        // add circles
        var circle = svg.selectAll(".circles")
        .data(data).enter()
        .append("circle")
        .attr("r", 2 ) //function(d,i){return d}
        .attr("transform", function(d){return "translate(" + projection([d.NSRDB_LON,d.NSRDB_LAT]) + ")";})
        .on("mouseover",tip.show)
        .on("mouseout",tip.hide)
        .on("click",createDetailVis());

        //createDetailVis();

        // circle.append("g")
        // .call(d3.behavior.zoom().scaleExtent([1, 8]).on("zoom", zoom))
        // .append("g");

        // svg.append("rect")
        // .attr("class", "overlay")
        // .attr("width", width)
        // .attr("height", height);

        // svg.attr("transform", function(d) { return "translate(" + d + ")"; });
        //console.log(data.station);//....map every station to a circle on the map
    });
}

function loadStats() {

     d3.json("../data/reducedMonthStationHour2003_2004.json", function(error,data){
        completeDataSet= data;
        createDetailVis(completeDataSet);

        loadStations(completeDataSet);

     })

}

d3.json("../data/us-named.json", function(error, data) {
    //creates map
    var usMap = topojson.feature(data,data.objects.states).features

    //add click to zoom
    svg.selectAll(".country").data(usMap).enter()
    .append("path")
    .attr("d",path)
    .attr("fill","purple")
    .on("click",clicked);

    loadStats();

});

//creates bar chart
var createDetailVis = function(fulldata){
  d3.csv("../data/NSRDB_StationsMeta.csv",function(error,data){

        console.log(fulldata);

    //finds maximum of hourly data per station
    var max_hourly = function(d){
            console.log(fulldata);
            max = 0;
            array = new Array(12);
            array[0] =  fulldata["Jan"][d.USAF]
            array[1] =  fulldata["Feb"][d.USAF]
            array[2] =  fulldata["Mar"][d.USAF]
            array[3] =  fulldata["Apr"][d.USAF]
            array[4] =  fulldata["May"][d.USAF]
            array[5] =  fulldata["Jun"][d.USAF]
            array[6] =  fulldata["Jul"][d.USAF]
            array[7] =  fulldata["Aug"][d.USAF]
            array[8] =  fulldata["Sep"][d.USAF]
            array[9] =  fulldata["Oct"][d.USAF]
            array[10] =  fulldata["Nov"][d.USAF]
            array[11] =  fulldata["Dec"][d.USAF]

            //console.log(arrayOfMonths);
            //iterate through each month
            //console.log(arrayOfMonths[3].hourly[6]);
            for (t=0; t<array.length; t++){

              //iterate through each hour
               if (array[t] != undefined){
                console.log(array[t], array[t].hourly[1]);

                  for (u = 0; u<24; u++){
                     result = array[t].hourly[u];
                     console.log(result);
                     if (result>max)
                        max = result;
                  }

                }
            }

            return max;

        }

    console.log(max_hourly(completeDataSet));
    // sets x and y scale

// NEED HELP GETTING HOUR
    var x = d3.scale.linear().domain([0,23]).range([bbDetail.x,bbDetail.w]);

    var y = d3.scale.linear().domain([0,15]).range([height, 0]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");
        //.tickFormat(d3.time.format("%Y-%m"));

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left")
        .ticks(10);

     detailVis.append("g")
      .attr("class", "x axis")
      //.attr("transform", "translate(0," + bbDetail.height + ")")
      .call(xAxis)
    .selectAll("text")
      .style("text-anchor", "end")
      .attr("dx", "-.8em")
      .attr("dy", "-.55em")
      .attr("transform", "rotate(-90)" )
    .append("text")
    .text("Hours");

   detailVis.append("g")
      .attr("class", "y axis")
       .attr("transform", "translate(0," + bbDetail.height + ")")
      .call(yAxis)
    .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end")
      .text("Aggregated Hourly Values");

    //create bar graph

    var bar = detailVis.selectAll("g")
    .data(dataSet)
    .enter().append("g")
    .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

    // bar.append("rect")
    //     //.attr("width", x)
    //     .attr("height", barHeight - 1)
    //     .style("fill","steelblue")
    //     // .attr("x", function(d){})
    //     // .attr("y", function(d){});

    bar.append("text")
        .attr("x", function(d) { return x(d) - 3; })
        .attr("y", barHeight / 2)
        .attr("dy", ".35em")
        .text(function(d) { return d; });

  // svg.selectAll("bar")
  //     .data(data)
  //   .enter().append("rect")
  //     .style("fill", "steelblue")
  //     .attr("x", function(d) { return x(d.date); })
  //     .attr("width", x.rangeBand())
  //     .attr("y", function(d) { return y(d.value); })
  //     .attr("height", function(d) { return height - y(d.value); });

})
}

// var updateDetailVis = function(data, name){

// }

// // ZOOMING
// function zoomToBB() {

// }

// function resetZoom() {

// }

<|endoftext|>