<commit_before>//     keymaster.js
//     (c) 2011-2013 Thomas Fuchs
//     keymaster.js may be freely distributed under the MIT license.

;(function(global){
  var k,
    _handlers = {},
    _mods = { 16: false, 18: false, 17: false, 91: false },
    _scope = 'all',
    // modifier keys
    _MODIFIERS = {
      '⇧': 16, shift: 16,
      '⌥': 18, alt: 18, option: 18,
      '⌃': 17, ctrl: 17, control: 17,
      '⌘': 91, command: 91
    },
    // special keys
    _MAP = {
      backspace: 8, tab: 9, clear: 12,
      enter: 13, 'return': 13,
      esc: 27, escape: 27, space: 32,
      left: 37, up: 38,
      right: 39, down: 40,
      del: 46, 'delete': 46,
      home: 36, end: 35,
      pageup: 33, pagedown: 34,
      ',': 188, '.': 190, '/': 191,
      '`': 192, '-': 189, '=': 187,
      ';': 186, '\'': 222,
      '[': 219, ']': 221, '\\': 220
    },
    code = function(x){
      return _MAP[x] || x.toUpperCase().charCodeAt(0);
    },
    _downKeys = [];

  for(k=1;k<20;k++) _MAP['f'+k] = 111+k;

  // IE doesn't support Array#indexOf, so have a simple replacement
  function index(array, item){
    var i = array.length;
    while(i--) if(array[i]===item) return i;
    return -1;
  }

  // for comparing mods before unassignment
  function compareArray(a1, a2) {
    if (a1.length != a2.length) return false;
    for (var i = 0; i < a1.length; i++) {
        if (a1[i] !== a2[i]) return false;
    }
    return true;
  }

  var modifierMap = {
      16:'shiftKey',
      18:'altKey',
      17:'ctrlKey',
      91:'metaKey'
  };
  function updateModifierKey(event) {
      for(k in _mods) _mods[k] = event[modifierMap[k]];
  };

  // handle keydown event
  function dispatch(event) {
    var key, handler, k, i, modifiersMatch, scope;
    key = event.keyCode;

    if (index(_downKeys, key) == -1) {
        _downKeys.push(key);
    }

    // if a modifier key, set the key.<modifierkeyname> property to true and return
    if(key == 93 || key == 224) key = 91; // right command on webkit, command on Gecko
    if(key in _mods) {
      _mods[key] = true;
      // 'assignKey' from inside this closure is exported to window.key
      for(k in _MODIFIERS) if(_MODIFIERS[k] == key) assignKey[k] = true;
      return;
    }
    updateModifierKey(event);

    // see if we need to ignore the keypress (filter() can can be overridden)
    // by default ignore key presses if a select, textarea, or input is focused
    if(!assignKey.filter.call(this, event)) return;

    // abort if no potentially matching shortcuts found
    if (!(key in _handlers)) return;

    scope = getScope();

    // for each potential shortcut
    for (i = 0; i < _handlers[key].length; i++) {
      handler = _handlers[key][i];

      // see if it's in the current scope
      if(handler.scope == scope || handler.scope == 'all'){
        // check if modifiers match if any
        modifiersMatch = handler.mods.length > 0;
        for(k in _mods)
          if((!_mods[k] && index(handler.mods, +k) > -1) ||
            (_mods[k] && index(handler.mods, +k) == -1)) modifiersMatch = false;
        // call the handler and stop the event if neccessary
        if((handler.mods.length == 0 && !_mods[16] && !_mods[18] && !_mods[17] && !_mods[91]) || modifiersMatch){
          if(handler.method(event, handler)===false){
            if(event.preventDefault) event.preventDefault();
              else event.returnValue = false;
            if(event.stopPropagation) event.stopPropagation();
            if(event.cancelBubble) event.cancelBubble = true;
          }
        }
      }
    }
  };

  // unset modifier keys on keyup
  function clearModifier(event){
    var key = event.keyCode, k,
        i = index(_downKeys, key);

    // remove key from _downKeys
    if (i >= 0) {
        _downKeys.splice(i, 1);
    }

    if(key == 93 || key == 224) key = 91;
    if(key in _mods) {
      _mods[key] = false;
      for(k in _MODIFIERS) if(_MODIFIERS[k] == key) assignKey[k] = false;
    }
  };

  function resetModifiers() {
    for(k in _mods) _mods[k] = false;
    for(k in _MODIFIERS) assignKey[k] = false;
  };

  // parse and assign shortcut
  function assignKey(key, scope, method){
    var keys, mods;
    keys = getKeys(key);
    if (method === undefined) {
      method = scope;
      scope = 'all';
    }

    // for each shortcut
    for (var i = 0; i < keys.length; i++) {
      // set modifier keys if any
      mods = [];
      key = keys[i].split('+');
      if (key.length > 1){
        mods = getMods(key);
        key = [key[key.length-1]];
      }
      // convert to keycode and...
      key = key[0]
      key = code(key);
      // ...store handler
      if (!(key in _handlers)) _handlers[key] = [];
      _handlers[key].push({ shortcut: keys[i], scope: scope, method: method, key: keys[i], mods: mods });
    }
  };

  // unbind all handlers for given key in current scope
  function unbindKey(key, scope) {
    var multipleKeys, keys,
      mods = [],
      i, j, obj;

    multipleKeys = getKeys(key);

    for (j = 0; j < multipleKeys.length; j++) {
      keys = multipleKeys[j].split('+');

      if (keys.length > 1) {
        mods = getMods(keys);
      }

      key = keys[keys.length - 1];
      key = code(key);

      if (scope === undefined) {
        scope = getScope();
      }
      if (!_handlers[key]) {
        return;
      }
      for (i = 0; i < _handlers[key].length; i++) {
        obj = _handlers[key][i];
        // only clear handlers if correct scope and mods match
        if (obj.scope === scope && compareArray(obj.mods, mods)) {
          _handlers[key][i] = {};
        }
      }
    }
  };

  // Returns true if the key with code 'keyCode' is currently down
  // Converts strings into key codes.
  function isPressed(keyCode) {
      if (typeof(keyCode)=='string') {
        keyCode = code(keyCode);
      }
      return index(_downKeys, keyCode) != -1;
  }

  function getPressedKeyCodes() {
      return _downKeys.slice(0);
  }

  function filter(event){
    var tagName = (event.target || event.srcElement).tagName;
    // ignore keypressed in any elements that support keyboard data input
    return !(tagName == 'INPUT' || tagName == 'SELECT' || tagName == 'TEXTAREA');
  }

  // initialize key.<modifier> to false
  for(k in _MODIFIERS) assignKey[k] = false;

  // set current scope (default 'all')
  function setScope(scope){ _scope = scope || 'all' };
  function getScope(){ return _scope || 'all' };

  // delete all handlers for a given scope
  function deleteScope(scope){
    var key, handlers, i;

    for (key in _handlers) {
      handlers = _handlers[key];
      for (i = 0; i < handlers.length; ) {
        if (handlers[i].scope === scope) handlers.splice(i, 1);
        else i++;
      }
    }
  };

  // abstract key logic for assign and unassign
  function getKeys(key) {
    var keys;
    key = key.replace(/\s/g, '');
    keys = key.split(',');
    if ((keys[keys.length - 1]) == '') {
      keys[keys.length - 2] += ',';
    }
    return keys;
  }

  // abstract mods logic for assign and unassign
  function getMods(key) {
    var mods = key.slice(0, key.length - 1);
    for (var mi = 0; mi < mods.length; mi++)
    mods[mi] = _MODIFIERS[mods[mi]];
    return mods;
  }

  // cross-browser events
  function addEvent(object, event, method) {
    if (object.addEventListener)
      object.addEventListener(event, method, false);
    else if(object.attachEvent)
      object.attachEvent('on'+event, function(){ method(window.event) });
  };

  // set the handlers globally on document
  addEvent(document, 'keydown', function(event) { dispatch(event) }); // Passing _scope to a callback to ensure it remains the same by execution. Fixes #48
  addEvent(document, 'keyup', clearModifier);

  // reset modifiers to false whenever the window is (re)focused.
  addEvent(window, 'focus', resetModifiers);

  // store previously defined key
  var previousKey = global.key;

  // restore previously defined key and return reference to our key object
  function noConflict() {
    var k = global.key;
    global.key = previousKey;
    return k;
  }

  // set window.key and window.key.set/get/deleteScope, and the default filter
  global.key = assignKey;
  global.key.setScope = setScope;
  global.key.getScope = getScope;
  global.key.deleteScope = deleteScope;
  global.key.filter = filter;
  global.key.isPressed = isPressed;
  global.key.getPressedKeyCodes = getPressedKeyCodes;
  global.key.noConflict = noConflict;
  global.key.unbind = unbindKey;

  if(typeof module !== 'undefined') module.exports = assignKey;

})(this);
<commit_msg>modernize keymaster<commit_after>// keymaster.js
// (c) 2011-2013 Thomas Fuchs
// License MIT
// Modified by Nicolas CARPi

;(function(global){
  let k;
  const _handlers = {};
  const _mods = { 16: false, 18: false, 17: false, 91: false };
  let _scope = 'all';
  // modifier keys
  const _MODIFIERS = {
    '⇧': 16, shift: 16,
    '⌥': 18, alt: 18, option: 18,
    '⌃': 17, ctrl: 17, control: 17,
    '⌘': 91, command: 91,
  };
    // special keys
  const _MAP = {
    backspace: 8, tab: 9, clear: 12,
    enter: 13, 'return': 13,
    esc: 27, escape: 27, space: 32,
    left: 37, up: 38,
    right: 39, down: 40,
    del: 46, 'delete': 46,
    home: 36, end: 35,
    pageup: 33, pagedown: 34,
    ',': 188, '.': 190, '/': 191,
    '`': 192, '-': 189, '=': 187,
    ';': 186, '\'': 222,
    '[': 219, ']': 221, '\\': 220,
  };

  const code = function(x) {
    return _MAP[x] || x.toUpperCase().charCodeAt(0);
  };
  const _downKeys = [];

  for(k=1;k<20;k++) _MAP['f'+k] = 111+k;

  // abstract key logic for assign and unassign
  function getKeys(key) {
    // remove all whitespaces
    key = key.replace(/\s/g, '');
    const keys = key.split(',');
    if ((keys[keys.length - 1]) == '') {
      keys[keys.length - 2] += ',';
    }
    return keys;
  }

  // abstract mods logic for assign and unassign
  function getMods(key) {
    const mods = key.slice(0, key.length - 1);
    for (let mi = 0; mi < mods.length; mi++)
      mods[mi] = _MODIFIERS[mods[mi]];
    return mods;
  }

  // parse and assign shortcut
  function assignKey(key, scope, method){
    let mods;
    const keys = getKeys(key);
    if (typeof method === 'undefined') {
      method = scope;
      scope = 'all';
    }

    // for each shortcut
    for (let i = 0; i < keys.length; i++) {
      // set modifier keys if any
      mods = [];
      key = keys[i].split('+');
      if (key.length > 1){
        mods = getMods(key);
        key = [key[key.length-1]];
      }
      // convert to keycode and...
      key = key[0];
      key = code(key);
      // ...store handler
      if (!(key in _handlers)) _handlers[key] = [];
      _handlers[key].push({ shortcut: keys[i], scope: scope, method: method, key: keys[i], mods: mods });
    }
  };

  // set current scope (default 'all')
  function setScope(scope){ _scope = scope || 'all'; };
  function getScope(){ return _scope || 'all'; };

  // IE doesn't support Array#indexOf, so have a simple replacement
  function index(array, item){
    let i = array.length;
    while(i--) if(array[i]===item) return i;
    return -1;
  }

  // for comparing mods before unassignment
  function compareArray(a1, a2) {
    if (a1.length != a2.length) return false;
    for (let i = 0; i < a1.length; i++) {
      if (a1[i] !== a2[i]) return false;
    }
    return true;
  }

  const modifierMap = {
    16:'shiftKey',
    18:'altKey',
    17:'ctrlKey',
    91:'metaKey',
  };
  function updateModifierKey(event) {
    for(k in _mods) _mods[k] = event[modifierMap[k]];
  };

  // handle keydown event
  function dispatch(event) {
    let key, handler, k, i, modifiersMatch;
    key = event.keyCode;
    const scope = getScope();

    if (index(_downKeys, key) == -1) {
      _downKeys.push(key);
    }

    // if a modifier key, set the key.<modifierkeyname> property to true and return
    if(key == 93 || key == 224) key = 91; // right command on webkit, command on Gecko
    if(key in _mods) {
      _mods[key] = true;
      // 'assignKey' from inside this closure is exported to window.key
      for(k in _MODIFIERS) if(_MODIFIERS[k] == key) assignKey[k] = true;
      return;
    }
    updateModifierKey(event);

    // see if we need to ignore the keypress (filter() can can be overridden)
    // by default ignore key presses if a select, textarea, or input is focused
    if(!assignKey.filter.call(this, event)) return;

    // abort if no potentially matching shortcuts found
    if (!(key in _handlers)) return;

    // for each potential shortcut
    for (i = 0; i < _handlers[key].length; i++) {
      handler = _handlers[key][i];

      // see if it's in the current scope
      if(handler.scope == scope || handler.scope == 'all'){
        // check if modifiers match if any
        modifiersMatch = handler.mods.length > 0;
        for(k in _mods)
          if((!_mods[k] && index(handler.mods, +k) > -1) ||
            (_mods[k] && index(handler.mods, +k) == -1)) modifiersMatch = false;
        // call the handler and stop the event if neccessary
        if((handler.mods.length == 0 && !_mods[16] && !_mods[18] && !_mods[17] && !_mods[91]) || modifiersMatch){
          if(handler.method(event, handler)===false){
            if(event.preventDefault) event.preventDefault();
            else event.returnValue = false;
            if(event.stopPropagation) event.stopPropagation();
            if(event.cancelBubble) event.cancelBubble = true;
          }
        }
      }
    }
  };

  // unset modifier keys on keyup
  function clearModifier(event){
    let key = event.keyCode;
    let k;
    const i = index(_downKeys, key);

    // remove key from _downKeys
    if (i >= 0) {
      _downKeys.splice(i, 1);
    }

    if(key == 93 || key == 224) key = 91;
    if(key in _mods) {
      _mods[key] = false;
      for(k in _MODIFIERS) if(_MODIFIERS[k] == key) assignKey[k] = false;
    }
  };

  function resetModifiers() {
    for(k in _mods) _mods[k] = false;
    for(k in _MODIFIERS) assignKey[k] = false;
  };

  // unbind all handlers for given key in current scope
  function unbindKey(key, scope) {
    let keys,
      mods = [],
      i, j, obj;

    const multipleKeys = getKeys(key);

    for (j = 0; j < multipleKeys.length; j++) {
      keys = multipleKeys[j].split('+');

      if (keys.length > 1) {
        mods = getMods(keys);
      }

      key = keys[keys.length - 1];
      key = code(key);

      if (scope === undefined) {
        scope = getScope();
      }
      if (!_handlers[key]) {
        return;
      }
      for (i = 0; i < _handlers[key].length; i++) {
        obj = _handlers[key][i];
        // only clear handlers if correct scope and mods match
        if (obj.scope === scope && compareArray(obj.mods, mods)) {
          _handlers[key][i] = {};
        }
      }
    }
  };

  // Returns true if the key with code 'keyCode' is currently down
  // Converts strings into key codes.
  function isPressed(keyCode) {
    if (typeof(keyCode)=='string') {
      keyCode = code(keyCode);
    }
    return index(_downKeys, keyCode) != -1;
  }

  function getPressedKeyCodes() {
    return _downKeys.slice(0);
  }

  function filter(event){
    const tagName = (event.target || event.srcElement).tagName;
    // ignore keypressed in any elements that support keyboard data input
    return !(tagName == 'INPUT' || tagName == 'SELECT' || tagName == 'TEXTAREA');
  }

  // initialize key.<modifier> to false
  for(k in _MODIFIERS) assignKey[k] = false;

  // delete all handlers for a given scope
  function deleteScope(scope){
    let key, handlers, i;

    for (key in _handlers) {
      handlers = _handlers[key];
      for (i = 0; i < handlers.length; ) {
        if (handlers[i].scope === scope) handlers.splice(i, 1);
        else i++;
      }
    }
  };

  // set the handlers globally on document
  document.addEventListener('keydown', event => dispatch(event));
  document.addEventListener('keyup', event => clearModifier(event));

  // reset modifiers to false whenever the window is (re)focused.
  window.addEventListener('focus', () => resetModifiers());

  // store previously defined key
  const previousKey = global.key;

  // restore previously defined key and return reference to our key object
  function noConflict() {
    const k = global.key;
    global.key = previousKey;
    return k;
  }

  // set window.key and window.key.set/get/deleteScope, and the default filter
  global.key = assignKey;
  global.key.setScope = setScope;
  global.key.getScope = getScope;
  global.key.deleteScope = deleteScope;
  global.key.filter = filter;
  global.key.isPressed = isPressed;
  global.key.getPressedKeyCodes = getPressedKeyCodes;
  global.key.noConflict = noConflict;
  global.key.unbind = unbindKey;

  if (typeof module !== 'undefined') {
    module.exports = assignKey;
  }

})(this);
<|endoftext|>


<commit_before>/* jshint esnext: true */
'use strict';

import Map from "../node_modules/carbide/map";
import View from "./view";

import * as QString from "query-string";
function Client(){
  var $view = new View(document);
  window.$view = $view;
  var queryString = location.search;
  var query = QString.parse(queryString);

  var state = Map({
    menu: Map({
      open: location.pathname == "/menu",
    }),
    accelerometer: Map({
      reading: Map({
        x: 0,
        y: 0,
        z: 0
      }),
    }),
    theme: query.theme || "APPLE"
  });
  Object.defineProperty(this, "url", {
    get: function(){
      var url = "";
      if (state.menu.open) { url = url + "/menu"; }
      var query = {theme: state.theme.toLowerCase()};
      queryString = QString.stringify(query);
      return url + "?" + queryString;
    }
  });
  this.location = new Location(this);
}

function Location(projection){
  history.replaceState({}, "", projection.url);
  function update(){
    history.pushState({}, "", projection.url);
  }
  this.update = update;
}

new Client();
<commit_msg>open close interactions<commit_after>/* jshint esnext: true */
'use strict';

import Map from "../node_modules/carbide/map";
import View from "./view";

import * as QString from "query-string";
function Client(){
  var $view = new View(document);
  window.$view = $view;
  var queryString = location.search;
  var query = QString.parse(queryString);

  var state = Map({
    menu: Map({
      open: location.pathname == "/menu",
    }),
    accelerometer: Map({
      reading: Map({
        x: 0,
        y: 0,
        z: 0
      }),
    }),
    theme: query.theme || "APPLE"
  });
  Object.defineProperty(this, "url", {
    get: function(){
      var url = "/";
      if (state.menu.open) { url = url + "menu"; }
      var query = {theme: state.theme.toLowerCase()};
      queryString = QString.stringify(query);
      return url + "?" + queryString;
    }
  });
  this.location = new Location(this);

  this.openMenu = function(){
    if (state.menu.open) { return; }
    // DEBT replaces menu map will fail with new keys
    state = state.set("menu", Map({open: true}));
    this.location.update();
  };
  this.closeMenu = function(){
    if (!state.menu.open) { return; }
    // DEBT replaces menu map will fail with new keys
    state = state.set("menu", Map({open: false}));
    this.location.update();
  };
}

function Location(projection){
  history.replaceState({}, "", projection.url);
  function update(){
    history.pushState({}, "", projection.url);
  }
  this.update = update;
}

export default new Client();
<|endoftext|>


<commit_before>import React from "react";
import * as helpers from "../../helpers.js";

//Import card styles
import "@siimple/css/scss/components/card.scss";

//Card base component
export const Card = function (props) {
    return helpers.createMergedElement("div", props, {
        "className": "siimple-card"
    });
};

//Card header component
export const CardHeader = function (props) {
    return helpers.createMergedElement("div", props, {
        "className": "siimple-card-header"
    });
};

//Card body component
export const CardBody = function (props) {
    return helpers.createMergedElement("div", props, {
        "className": "siimple-card-body"
    });
};

//Card footer component
export const CardFooter = function (props) {
    return helpers.createMergedElement("div", props, {
        "className": "siimple-card-footer"
    });
};

//Card link component
export const CardLink = function (props) {
    return helpers.createMergedElement("div", props, {
        "className": "siimple-card-link"
    });
};

//Card title component
export const CardTitle = function (props) {
    return helpers.createMergedElement("div", props, {
        "className": "siimple-card-title"
    });
};

//Card subtitle component
export const CardSubtitle = function (props) {
    return helpers.createMergedElement("div", props, {
        "className": "siimple-card-subtitle"
    });
};

<commit_msg>neutrine: updated card components for new css@4.0.0<commit_after>import React from "react";
import * as helpers from "../../helpers.js";
import "@siimple/css/scss/components/card.scss";

//Card base component
export const Card = function (props) {
    let newProps = helpers.filterProps(props, ["className", "theme"]);
    Object.assign(newProps, {
        "className": helpers.classNames({
            "siimple-card": true,
            ["siimple-card--" + props.theme]: props.theme === "light" || props.theme === "dark"
        })
    });
    return React.createElement("div", newProps, props.children);
};

Card.defaultProps = {
    "theme": "light"
};

//Card content component
export const CardContent = function (props) {
    return helpers.createMergedElement("div", props, {
        "className": "siimple-card-content"
    });
};

//Card image component
export const CardImage = function (props) {
    return helpers.createMergedElement("div", props, {
        "className": "siimple-card-image"
    });
};

//Card link component
export const CardLink = function (props) {
    return helpers.createMergedElement("div", props, {
        "className": "siimple-card-link"
    });
};

<|endoftext|>


<commit_before>var SETDEX_XY = {};

var components = [
	SETDEX_SMOGVGC
];

for (var i=0; i<components.length; i++) {
	var sourceDex = components[i];
	if (sourceDex) {
		for (var p in sourceDex) {
			if (sourceDex.hasOwnProperty(p)) {
				SETDEX_XY[p] = $.extend(SETDEX_XY[p], sourceDex[p])
			}
		}
	}
}<commit_msg>Missed one "smog" reference; works now<commit_after>var SETDEX_XY = {};

var components = [
	SETDEX_SHOWDOWN
];

for (var i=0; i<components.length; i++) {
	var sourceDex = components[i];
	if (sourceDex) {
		for (var p in sourceDex) {
			if (sourceDex.hasOwnProperty(p)) {
				SETDEX_XY[p] = $.extend(SETDEX_XY[p], sourceDex[p])
			}
		}
	}
}<|endoftext|>


<commit_before>// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Bootstrap support for Dart scripts on the page as this script.
if (navigator.webkitStartDart) {
  if (!navigator.webkitStartDart()) {
    document.body.innerHTML = 'This build has expired.  Please download a new Dartium at http://www.dartlang.org/dartium/index.html';
  }
} else {
  // TODO:
  // - Support in-browser compilation.
  // - Handle inline Dart scripts.
  window.addEventListener("DOMContentLoaded", function (e) {
    // Fall back to compiled JS. Run through all the scripts and
    // replace them if they have a type that indicate that they source
    // in Dart code.
    //
    //   <script type="application/dart" src="..."></script>
    //
    var scripts = document.getElementsByTagName("script");
    var length = scripts.length;
    for (var i = 0; i < length; ++i) {
      if (scripts[i].type == "application/dart") {
        // Remap foo.dart to foo.dart.js.
        if (scripts[i].src && scripts[i].src != '') {
          var script = document.createElement('script');
          script.src = scripts[i].src + '.js';
          var parent = scripts[i].parentNode;
          parent.replaceChild(script, scripts[i]);
        }
      }
    }
  }, false);
}

// ---------------------------------------------------------------------------
// Experimental support for JS interoperability
// ---------------------------------------------------------------------------
function SendPortSync() {
}

function ReceivePortSync() {
  this.id = ReceivePortSync.id++;
  ReceivePortSync.map[this.id] = this;
}

(function() {
  function serialize(message) {
    if (message == null) {
      return null;  // Convert undefined to null.
    } else if (typeof(message) == 'string' ||
               typeof(message) == 'number' ||
               typeof(message) == 'boolean') {
      return message;
    } else if (message instanceof Array) {
      var values = new Array(message.length);
      for (var i = 0; i < message.length; i++) {
        values[i] = serialize(message[i]);
      }
      return [ 'list', message.length, values ];
    } else if (message instanceof LocalSendPortSync) {
      return [ 'sendport', 'nativejs', message.receivePort.id ];
    } else if (message instanceof DartSendPortSync) {
      return [ 'sendport', 'dart', message.receivePort.isolateId,
               message.receivePort.portId ];
    } else {
      var id = 0;
      var keys = Object.getOwnPropertyNames(message);
      var values = new Array(keys.length);
      for (var i = 0; i < keys.length; i++) {
        values[i] = serialize(message[keys[i]]);
      }
      return [ 'map', id, keys, values ];
    }
  }

  function deserialize(message) {
    return deserializeHelper(message);
  }

  function deserializeHelper(x) {
    if (x == null ||
        typeof(x) == 'string' ||
        typeof(x) == 'number' ||
        typeof(x) == 'boolean') {
      return x;
    }
    switch (x[0]) {
      case 'map': return deserializeMap(x);
      case 'sendport': return deserializeSendPort(x);
      case 'list': return deserializeList(x);
      default: throw 'unimplemented';
    }
  }

  function deserializeMap(x) {
    var result = { };
    var id = x[1];
    var keys = x[2];
    var values = x[3];
    for (var i = 0, length = keys.length; i < length; i++) {
      var key = deserializeHelper(keys[i]);
      var value = deserializeHelper(values[i]);
      result[key] = value;
    }
    return result;
  }

  function deserializeSendPort(x) {
    var tag = x[1];
    switch (tag) {
      case 'nativejs':
        var id = x[2];
        return new LocalSendPortSync(ReceivePortSync.map[id]);
      case 'dart':
        var isolateId = x[2];
        var portId = x[3];
        return new DartSendPortSync(isolateId, portId);
      default:
        throw 'Illegal SendPortSync type: $tag';
    }
  }

  function deserializeList(x) {
    var values = x[2];
    var length = values.length;
    var result = new Array(length);
    for (var i = 0; i < length; i++) {
      result[i] = deserializeHelper(values[i]);
    }
    return result;
  }

  window.registerPort = function(name, port) {
    var stringified = JSON.stringify(serialize(port));
    window.localStorage['dart-port:' + name] = stringified;
  };

  window.lookupPort = function(name) {
    var stringified = window.localStorage['dart-port:' + name];
    return deserialize(JSON.parse(stringified));
  };

  ReceivePortSync.id = 0;
  ReceivePortSync.map = {};

  ReceivePortSync.dispatchCall = function(id, message) {
    // TODO(vsm): Handle and propagate exceptions.
    var deserialized = deserialize(message);
    var result = ReceivePortSync.map[id].callback(deserialized);
    return serialize(result);
  };

  ReceivePortSync.prototype.receive = function(callback) {
    this.callback = callback;
  };

  ReceivePortSync.prototype.toSendPort = function() {
    return new LocalSendPortSync(this);
  };

  ReceivePortSync.prototype.close = function() {
    delete ReceivePortSync.map[this.id];
  };

  if (navigator.webkitStartDart) {
    window.addEventListener('js-sync-message', function(event) {
      var data = JSON.parse(event.data);
      var deserialized = deserialize(data.message);
      var result = ReceivePortSync.map[data.id].callback(deserialized);
      // TODO(vsm): Handle and propagate exceptions.
      dispatchEvent('js-result', serialize(result));
    }, false);
  }

  function LocalSendPortSync(receivePort) {
    this.receivePort = receivePort;
  }

  LocalSendPortSync.prototype = new SendPortSync();

  LocalSendPortSync.prototype.callSync = function(message) {
    // TODO(vsm): Do a direct deepcopy.
    message = deserialize(serialize(message));
    return this.receivePort.callback(message);
  }

  function DartSendPortSync(isolateId, portId) {
    this.isolateId = isolateId;
    this.portId = portId;
  }

  DartSendPortSync.prototype = new SendPortSync();

  function dispatchEvent(receiver, message) {
    var string = JSON.stringify(message);
    var event = document.createEvent('TextEvent');
    event.initTextEvent(receiver, false, false, window, string);
    window.dispatchEvent(event);
  }

  DartSendPortSync.prototype.callSync = function(message) {
    var serialized = serialize(message);
    var target = 'dart-port-' + this.isolateId + '-' + this.portId;
    // TODO(vsm): Make this re-entrant.
    // TODO(vsm): Set this up set once, on the first call.
    var source = target + '-result';
    var result = null;
    var listener = function (e) {
      result = JSON.parse(e.data);
    };
    window.addEventListener(source, listener, false);
    dispatchEvent(target, [source, serialized]);
    window.removeEventListener(source, listener, false);
    return deserialize(result);
  }
})();
<commit_msg>Fix bug in SendPortSync serialization Review URL: https://chromiumcodereview.appspot.com//10698150<commit_after>// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Bootstrap support for Dart scripts on the page as this script.
if (navigator.webkitStartDart) {
  if (!navigator.webkitStartDart()) {
    document.body.innerHTML = 'This build has expired.  Please download a new Dartium at http://www.dartlang.org/dartium/index.html';
  }
} else {
  // TODO:
  // - Support in-browser compilation.
  // - Handle inline Dart scripts.
  window.addEventListener("DOMContentLoaded", function (e) {
    // Fall back to compiled JS. Run through all the scripts and
    // replace them if they have a type that indicate that they source
    // in Dart code.
    //
    //   <script type="application/dart" src="..."></script>
    //
    var scripts = document.getElementsByTagName("script");
    var length = scripts.length;
    for (var i = 0; i < length; ++i) {
      if (scripts[i].type == "application/dart") {
        // Remap foo.dart to foo.dart.js.
        if (scripts[i].src && scripts[i].src != '') {
          var script = document.createElement('script');
          script.src = scripts[i].src + '.js';
          var parent = scripts[i].parentNode;
          parent.replaceChild(script, scripts[i]);
        }
      }
    }
  }, false);
}

// ---------------------------------------------------------------------------
// Experimental support for JS interoperability
// ---------------------------------------------------------------------------
function SendPortSync() {
}

function ReceivePortSync() {
  this.id = ReceivePortSync.id++;
  ReceivePortSync.map[this.id] = this;
}

(function() {
  function serialize(message) {
    if (message == null) {
      return null;  // Convert undefined to null.
    } else if (typeof(message) == 'string' ||
               typeof(message) == 'number' ||
               typeof(message) == 'boolean') {
      return message;
    } else if (message instanceof Array) {
      var values = new Array(message.length);
      for (var i = 0; i < message.length; i++) {
        values[i] = serialize(message[i]);
      }
      return [ 'list', message.length, values ];
    } else if (message instanceof LocalSendPortSync) {
      return [ 'sendport', 'nativejs', message.receivePort.id ];
    } else if (message instanceof DartSendPortSync) {
      return [ 'sendport', 'dart', message.isolateId, message.portId ];
    } else {
      var id = 0;
      var keys = Object.getOwnPropertyNames(message);
      var values = new Array(keys.length);
      for (var i = 0; i < keys.length; i++) {
        values[i] = serialize(message[keys[i]]);
      }
      return [ 'map', id, keys, values ];
    }
  }

  function deserialize(message) {
    return deserializeHelper(message);
  }

  function deserializeHelper(x) {
    if (x == null ||
        typeof(x) == 'string' ||
        typeof(x) == 'number' ||
        typeof(x) == 'boolean') {
      return x;
    }
    switch (x[0]) {
      case 'map': return deserializeMap(x);
      case 'sendport': return deserializeSendPort(x);
      case 'list': return deserializeList(x);
      default: throw 'unimplemented';
    }
  }

  function deserializeMap(x) {
    var result = { };
    var id = x[1];
    var keys = x[2];
    var values = x[3];
    for (var i = 0, length = keys.length; i < length; i++) {
      var key = deserializeHelper(keys[i]);
      var value = deserializeHelper(values[i]);
      result[key] = value;
    }
    return result;
  }

  function deserializeSendPort(x) {
    var tag = x[1];
    switch (tag) {
      case 'nativejs':
        var id = x[2];
        return new LocalSendPortSync(ReceivePortSync.map[id]);
      case 'dart':
        var isolateId = x[2];
        var portId = x[3];
        return new DartSendPortSync(isolateId, portId);
      default:
        throw 'Illegal SendPortSync type: $tag';
    }
  }

  function deserializeList(x) {
    var values = x[2];
    var length = values.length;
    var result = new Array(length);
    for (var i = 0; i < length; i++) {
      result[i] = deserializeHelper(values[i]);
    }
    return result;
  }

  window.registerPort = function(name, port) {
    var stringified = JSON.stringify(serialize(port));
    window.localStorage['dart-port:' + name] = stringified;
  };

  window.lookupPort = function(name) {
    var stringified = window.localStorage['dart-port:' + name];
    return deserialize(JSON.parse(stringified));
  };

  ReceivePortSync.id = 0;
  ReceivePortSync.map = {};

  ReceivePortSync.dispatchCall = function(id, message) {
    // TODO(vsm): Handle and propagate exceptions.
    var deserialized = deserialize(message);
    var result = ReceivePortSync.map[id].callback(deserialized);
    return serialize(result);
  };

  ReceivePortSync.prototype.receive = function(callback) {
    this.callback = callback;
  };

  ReceivePortSync.prototype.toSendPort = function() {
    return new LocalSendPortSync(this);
  };

  ReceivePortSync.prototype.close = function() {
    delete ReceivePortSync.map[this.id];
  };

  if (navigator.webkitStartDart) {
    window.addEventListener('js-sync-message', function(event) {
      var data = JSON.parse(event.data);
      var deserialized = deserialize(data.message);
      var result = ReceivePortSync.map[data.id].callback(deserialized);
      // TODO(vsm): Handle and propagate exceptions.
      dispatchEvent('js-result', serialize(result));
    }, false);
  }

  function LocalSendPortSync(receivePort) {
    this.receivePort = receivePort;
  }

  LocalSendPortSync.prototype = new SendPortSync();

  LocalSendPortSync.prototype.callSync = function(message) {
    // TODO(vsm): Do a direct deepcopy.
    message = deserialize(serialize(message));
    return this.receivePort.callback(message);
  }

  function DartSendPortSync(isolateId, portId) {
    this.isolateId = isolateId;
    this.portId = portId;
  }

  DartSendPortSync.prototype = new SendPortSync();

  function dispatchEvent(receiver, message) {
    var string = JSON.stringify(message);
    var event = document.createEvent('TextEvent');
    event.initTextEvent(receiver, false, false, window, string);
    window.dispatchEvent(event);
  }

  DartSendPortSync.prototype.callSync = function(message) {
    var serialized = serialize(message);
    var target = 'dart-port-' + this.isolateId + '-' + this.portId;
    // TODO(vsm): Make this re-entrant.
    // TODO(vsm): Set this up set once, on the first call.
    var source = target + '-result';
    var result = null;
    var listener = function (e) {
      result = JSON.parse(e.data);
    };
    window.addEventListener(source, listener, false);
    dispatchEvent(target, [source, serialized]);
    window.removeEventListener(source, listener, false);
    return deserialize(result);
  }
})();
<|endoftext|>


<commit_before>define(["helper/Basic", "Tone/source/Player", "helper/Offline", "helper/SourceTests", "Tone/core/Buffer"],
	function (BasicTests, Player, Offline, SourceTests, Buffer) {

	describe("Player", function(){

		var buffer = new Buffer();

		beforeEach(function(done){
			buffer.load("./audio/sine.wav", function(){
				done();
			});
		});

		//run the common tests
		BasicTests(Player, buffer);
		SourceTests(Player, buffer);

		context("Loading", function(){

			it("loads a url which was passed in", function(done){
				var player = new Player("./audio/sine.wav", function(){
					player.dispose();
					done();
				});
			});

			it("loads a url using the load method", function(done){
				var player = new Player();
				player.load("./audio/sine.wav", function(){
					expect(player._buffer).to.be.instanceof(Buffer);
					done();
				});
			});

			it("can be created with an options object", function(){
				var player = new Player({
					"url" : "./audio/sine.wav",
					"loop" : true
				});
				player.dispose();
			});

			it("can autostart after loading", function(done){
				var player = new Player({
					"url" : "./audio/sine.wav",
					"autostart" : true,
					"onload" : function(){
						setTimeout(function(){
							expect(player.state).to.be.equal("started");
							done();
						}, 10);
					}
				});
			});

		});

		context("Reverse", function(){

			it("can be played in reverse", function(done){
				var player;
				var offline = new Offline();
				var audioBuffer = buffer.get().getChannelData(0);
				var lastSample = audioBuffer[audioBuffer.length - 1];
				offline.before(function(dest){
					player = new Player(buffer.get()).connect(dest);
					player.reverse = true;
					player.start(0);
				});
				offline.test(function(sample, time){
					if (time === 0){
						expect(sample).to.equal(lastSample);
					}
				});
				offline.after(function(){
					player.dispose();
					buffer.reverse = false;
					done();
				});
				offline.run();
			});

		});

		context("Looping", function(){

			it("can be set to loop", function(){
				var player = new Player();
				player.loop = true;
				expect(player.loop).to.be.true;
				player.dispose();
			});

			it("can set the loop points", function(){
				var player = new Player();
				player.loopStart = 0.4;
				expect(player.loopStart).to.equal(0.4);
				player.loopEnd = 0.5;
				expect(player.loopEnd).to.equal(0.5);
				player.setLoopPoints(0, 0.2);
				expect(player.loopStart).to.equal(0);
				expect(player.loopEnd).to.equal(0.2);
				player.dispose();
			});

		});

		context("Get/Set", function(){

			it("can be set with an options object", function(){
				var player = new Player();
				expect(player.loop).to.be.false;
				player.set({
					"loop" : true,
					"loopStart" : 0.4
				});
				expect(player.loop).to.be.true;
				expect(player.loopStart).to.equal(0.4);
				player.dispose();
			});

			it("can get an options object", function(){
				var player = new Player({
					"url" : "./audio/sine.wav",
					"loopStart" : 0.2,
					"loopEnd" : 0.3,
					"loop" : true,
					"reverse" : true
				});
				expect(player.get().loopStart).to.equal(0.2);
				expect(player.get().loopEnd).to.equal(0.3);
				expect(player.get().loop).to.be.true;
				expect(player.get().reverse).to.be.true;
				player.dispose();
			});

			it("can get/set the playbackRate", function(){
				var player = new Player();
				player.playbackRate = 0.5;
				expect(player.playbackRate).to.equal(0.5);
				player.dispose();
			});

		});

		context("Start Scheduling", function(){

			it("can be start with an offset", function(done){
				var player;
				var offline = new Offline(0.4, 1, true);
				var audioBuffer = buffer.get().getChannelData(0);
				var testSample = audioBuffer[buffer.secondsToSamples(0.1)];
				offline.before(function(dest){
					player = new Player(buffer.get());
					player.connect(dest);
					player.start(0, 0.1);
				});
				offline.test(function(sample, time){
					if (time === 0){
						expect(sample).to.equal(testSample);
					}
				});
				offline.after(function(){
					player.dispose();
					done();
				});
				offline.run();
			});

			it("can be play for a specific duration", function(done){
				var player;
				var offline = new Offline(0.4, 1, true);
				offline.before(function(dest){
					player = new Player(buffer);
					player.connect(dest);
					player.start(0).stop(0.1);
				});
				offline.test(function(sample, time){
					if (sample < 0.001 && time > 0.02){
						expect(time).to.at.least(0.1);
					}
				});
				offline.after(function(){
					player.dispose();
					done();
				});
				offline.run();
			});

		});

		context("Synchronization", function(){
			/*it("can sync the frequency to Transport", function(done){
				var player;
				Test.offlineTest(0.1, function(dest){
					Transport.bpm.value = 120;
					player = new Player(2);
					player.frequency.connect(dest);
					player.syncFrequency();
					Transport.bpm.value = 240;
				}, function(freq){
					expect(freq).to.be.closeTo(4, 0.001);
				}, function(){
					player.dispose();
					done();
				});
			});*/

			/*it("can unsync the frequency to Transport", function(done){
				var player;
				Test.offlineTest(0.1, function(dest){
					Transport.bpm.value = 120;
					player = new Player(2);
					player.frequency.connect(dest);
					player.syncFrequency();
					Transport.bpm.value = 240;
					player.unsyncFrequency();
				}, function(freq){
					expect(freq).to.be.closeTo(2, 0.001);
				}, function(){
					player.dispose();
					done();
				});
			});*/
		});

	});
});<commit_msg>using Meter to test Player<commit_after>define(["helper/Basic", "Tone/source/Player", "helper/Offline", "helper/SourceTests", "Tone/core/Buffer", "helper/Meter"],
	function (BasicTests, Player, Offline, SourceTests, Buffer, Meter) {

	describe("Player", function(){

		var buffer = new Buffer();

		beforeEach(function(done){
			buffer.load("./audio/sine.wav", function(){
				done();
			});
		});

		//run the common tests
		BasicTests(Player, buffer);
		SourceTests(Player, buffer);

		context("Loading", function(){

			it("loads a url which was passed in", function(done){
				var player = new Player("./audio/sine.wav", function(){
					player.dispose();
					done();
				});
			});

			it("loads a url using the load method", function(done){
				var player = new Player();
				player.load("./audio/sine.wav", function(){
					expect(player._buffer).to.be.instanceof(Buffer);
					done();
				});
			});

			it("can be created with an options object", function(){
				var player = new Player({
					"url" : "./audio/sine.wav",
					"loop" : true
				});
				player.dispose();
			});

			it("can autostart after loading", function(done){
				var player = new Player({
					"url" : "./audio/sine.wav",
					"autostart" : true,
					"onload" : function(){
						setTimeout(function(){
							expect(player.state).to.be.equal("started");
							done();
						}, 10);
					}
				});
			});

		});

		context("Reverse", function(){

			it("can be played in reverse", function(done){
				var player;
				var offline = new Offline();
				var audioBuffer = buffer.get().getChannelData(0);
				var lastSample = audioBuffer[audioBuffer.length - 1];
				offline.before(function(dest){
					player = new Player(buffer.get()).connect(dest);
					player.reverse = true;
					player.start(0);
				});
				offline.test(function(sample, time){
					if (time === 0){
						expect(sample).to.equal(lastSample);
					}
				});
				offline.after(function(){
					player.dispose();
					buffer.reverse = false;
					done();
				});
				offline.run();
			});

		});

		context("Looping", function(){

			it("can be set to loop", function(){
				var player = new Player();
				player.loop = true;
				expect(player.loop).to.be.true;
				player.dispose();
			});

			it("can set the loop points", function(){
				var player = new Player();
				player.loopStart = 0.4;
				expect(player.loopStart).to.equal(0.4);
				player.loopEnd = 0.5;
				expect(player.loopEnd).to.equal(0.5);
				player.setLoopPoints(0, 0.2);
				expect(player.loopStart).to.equal(0);
				expect(player.loopEnd).to.equal(0.2);
				player.dispose();
			});

		});

		context("Get/Set", function(){

			it("can be set with an options object", function(){
				var player = new Player();
				expect(player.loop).to.be.false;
				player.set({
					"loop" : true,
					"loopStart" : 0.4
				});
				expect(player.loop).to.be.true;
				expect(player.loopStart).to.equal(0.4);
				player.dispose();
			});

			it("can get an options object", function(){
				var player = new Player({
					"url" : "./audio/sine.wav",
					"loopStart" : 0.2,
					"loopEnd" : 0.3,
					"loop" : true,
					"reverse" : true
				});
				expect(player.get().loopStart).to.equal(0.2);
				expect(player.get().loopEnd).to.equal(0.3);
				expect(player.get().loop).to.be.true;
				expect(player.get().reverse).to.be.true;
				player.dispose();
			});

			it("can get/set the playbackRate", function(){
				var player = new Player();
				player.playbackRate = 0.5;
				expect(player.playbackRate).to.equal(0.5);
				player.dispose();
			});

		});

		context("Start Scheduling", function(){

			it("can be start with an offset", function(done){
				var player;
				var offline = new Offline(0.4, 1);
				var audioBuffer = buffer.get().getChannelData(0);
				var testSample = audioBuffer[buffer.secondsToSamples(0.1)];
				offline.before(function(dest){
					player = new Player(buffer.get());
					player.connect(dest);
					player.start(0, 0.1);
				});
				offline.test(function(sample, time){
					if (time === 0){
						expect(sample).to.equal(testSample);
					}
				});
				offline.after(function(){
					player.dispose();
					done();
				});
				offline.run();
			});

			it("can be play for a specific duration", function(done){
				var player;
				var meter = new Meter(0.4);
				meter.before(function(dest){
					player = new Player(buffer);
					player.connect(dest);
					player.start(0).stop(0.1);
				});
				meter.test(function(sample, time){
					if (sample < 0.001){
						expect(time).to.at.least(0.1);
					}
				});
				meter.after(function(){
					player.dispose();
					done();
				});
				meter.run();
			});

		});

		context("Synchronization", function(){

		});

	});
});<|endoftext|>


<commit_before>var StatTable = {

  getIndex:  function($row, category) {
    var selector = "th:contains(" + category + ")";
    var $table = $row.parent().parent();
    var idx = $table.find('thead tr:not(.over_header)').first().find(selector).index();
    console.log(category + ': ' + idx);
    return idx;
  },

  getValue: function($row, category) {
    return Number($row.find('td').eq(this.getIndex($row, category)).text());
  }

};

function median(values) {
  values.sort( function(a,b) { return a - b; });
  var half = Math.floor(values.length/2);

  if(values.length % 2)
    return values[half];
  else
    return (Number(values[half - 1]) + Number(values[half]))/2.0;
}

var checkDouble = function (stat) {
  if ( stat >= 10 ) {
    return 1;
  } else {
    return 0;
  }
}

var checkBonus = function (x) {
  if ( x == 2 ) {
    return 1.5;
  }
  if (x >= 3 ) {
    return 3;
  }
  else {
    return 0;
  }
}
$(document).ready(function() {
  $('#per_minute thead tr, #per_game thead tr, #pgl_basic thead tr, #stats thead tr').append('FD	DS	DK	SS	');
  $('#per_minute tbody tr, #per_minute tfoot tr, #per_game tbody tr, #per_game tfoot tr').each(function(index){
    var $row = $(this);
    var pts = StatTable.getValue($row, 'PTS');
    var ast = StatTable.getValue($row, 'AST');
    var stl = StatTable.getValue($row, 'STL');
    var blk = StatTable.getValue($row, 'BLK');
    var tov = StatTable.getValue($row, 'TOV');
    var reb = StatTable.getValue($row, 'TRB');
    var fga = StatTable.getValue($row, 'FGA');
    var fgm = StatTable.getValue($row, 'FG');
    var fta = StatTable.getValue($row, 'FTA');
    var ftm = StatTable.getValue($row, 'FT');
    var tpt = StatTable.getValue($row, '3P');
    var fd = (pts + (1.5*ast) + (2*stl) + (2*blk) - tov + (1.2*reb)).toFixed(2);
    var ds = (pts + (1.5*ast) + (2*stl) + (2*blk) - tov + (1.25*reb) - (.5*(fga-fgm)) - (.5*(fta-ftm))).toFixed(2);
    var stats = [pts, ast, stl, blk, reb];
    var doubles = stats.map(checkDouble);
    var doublesSum = doubles.reduce(function (a,b) { return a + b });
    var dkBonus = checkBonus(doublesSum);
    var dk = (pts + (1.5*ast) + (2*stl) + (2*blk) - (.5*tov) + (1.25*reb) + (.5*tpt) + dkBonus).toFixed(2);
    var ss = (pts + (1.5*ast) + (1.25*reb) + (2*blk) + (2* stl) - tov).toFixed(2);
    $(this).append("" + fd + "	" + "" + ds + "	" + "" + dk + "	" + "" + ss + "	");
  });

  var tableHeading = $('.table_heading h2').text();

  $('#stats tbody tr').each(function(index){
      var $row = $(this);
      var pts = StatTable.getValue($row, 'PTS');
      var ast = StatTable.getValue($row, 'AST');
      var stl = StatTable.getValue($row, 'STL');
      var blk = StatTable.getValue($row, 'BLK');
      var tov = StatTable.getValue($row, 'TOV');
      var reb = StatTable.getValue($row, 'TRB');
      var fga = StatTable.getValue($row, 'FGA');
      var fgm = StatTable.getValue($row, 'FG');
      var fta = StatTable.getValue($row, 'FTA');
      var ftm = StatTable.getValue($row, 'FT');
      var tpt = StatTable.getValue($row, '3P');
      var games = StatTable.getValue($row, 'G');
    var fd = ((pts + (1.5*ast) + (2*stl) + (2*blk) - tov + (1.2*reb))/games).toFixed(2);
    var ds = ((pts + (1.5*ast) + (2*stl) + (2*blk) - tov + (1.25*reb) - (.5*(fga-fgm)) - (.5*(fta-ftm)))/games).toFixed(2);
    var stats = [pts/games, ast/games, stl/games, blk/games, reb/games];
    var doubles = stats.map(checkDouble);
    var doublesSum = doubles.reduce(function (a,b) { return a + b });
    var dkBonus = checkBonus(doublesSum);
    var dk = ((pts + (1.5*ast) + (2*stl) + (2*blk) - (.5*tov) + (1.25*reb) + (.5*tpt) + dkBonus)/games).toFixed(2);
    var ss = ((pts + (1.5*ast) + (1.25*reb) + (2*blk) + (2* stl) - tov)/games).toFixed(2);
    $(this).append("" + fd + "	" + "" + ds + "	" + "" + dk + "	" + "" + ss + "	");
  });
  var fd_vals = [];
  var ds_vals = [];
  var dk_vals = [];
  var ss_vals = [];
  $("#pgl_basic tbody tr").not(".thead").each(function(index){
      var $row = $(this);
      var pts = StatTable.getValue($row, 'PTS');
      var ast = StatTable.getValue($row, 'AST');
      var stl = StatTable.getValue($row, 'STL');
      var blk = StatTable.getValue($row, 'BLK');
      var tov = StatTable.getValue($row, 'TOV');
      var reb = StatTable.getValue($row, 'TRB');
      var fga = StatTable.getValue($row, 'FGA');
      var fgm = StatTable.getValue($row, 'FG');
      var fta = StatTable.getValue($row, 'FTA');
      var ftm = StatTable.getValue($row, 'FT');
      var tpt = StatTable.getValue($row, '3P');
      var fd = (pts + (1.5*ast) + (2*stl) + (2*blk) - tov + (1.2*reb)).toFixed(2);
      fd_vals.push(fd);
      var ds = (pts + (1.5*ast) + (2*stl) + (2*blk) - tov + (1.25*reb) - (.5*(fga-fgm)) - (.5*(fta-ftm))).toFixed(2);
      ds_vals.push(ds);
      var stats = [pts, ast, stl, blk, reb];
      var doubles = stats.map(checkDouble);
      var doublesSum = doubles.reduce(function (a,b) { return a + b });
      var dkBonus = checkBonus(doublesSum);
      var dk = (pts + (1.5*ast) + (2*stl) + (2*blk) - (.5*tov) + (1.25*reb) + (.5*tpt) + dkBonus).toFixed(2);
      dk_vals.push(dk);
      var ss = (pts + (1.5*ast) + (1.25*reb) + (2*blk) + (2* stl) - tov).toFixed(2);
      ss_vals.push(ss);
      $(this).append("" + fd + "	" + "" + ds + "	" + "" + dk + "	" + "" + ss + "	");
  });
  $("#pgl_basic tbody").append("
FD	 Median	" + median(fd_vals) + "		Min	" + Math.min.apply(Math,fd_vals) + "		Max	" + Math.max.apply(Math,fd_vals) + "
");
  $("#pgl_basic tbody").append("
DS	 Median	" + median(ds_vals) + "		Min	" + Math.min.apply(Math,ds_vals) + "		Max	" + Math.max.apply(Math,ds_vals) + "
");
  $("#pgl_basic tbody").append("
DK	 Median	" + median(dk_vals) + "		Min	" + Math.min.apply(Math,dk_vals) + "		Max	" + Math.max.apply(Math,dk_vals) + "
");
  $("#pgl_basic tbody").append("
SS	 Median	" + median(ss_vals) + "		Min	" + Math.min.apply(Math,ss_vals) + "		Max	" + Math.max.apply(Math,ss_vals) + "
");
  var url = document.URL;
  if ( url.split('/')[3] == "boxscores" ) {
    $('table').each(function() {
      if ( $(this).attr('id') != undefined && $(this).attr('id').split('_')[1] == "basic" ) {
        $(this).find('thead tr').not('.over_header').append('FD	DS	DK	SS	');
        $(this).find('tbody tr, tfoot tr').not('.thead').each(function(index){
          var $row = $(this);
          var pts = StatTable.getValue($row, 'PTS');
          var ast = StatTable.getValue($row, 'AST');
          var stl = StatTable.getValue($row, 'STL');
          var blk = StatTable.getValue($row, 'BLK');
          var tov = StatTable.getValue($row, 'TOV');
          var reb = StatTable.getValue($row, 'TRB');
          var fga = StatTable.getValue($row, 'FGA');
          var fgm = StatTable.getValue($row, 'FG');
          var fta = StatTable.getValue($row, 'FTA');
          var ftm = StatTable.getValue($row, 'FT');
          var tpt = StatTable.getValue($row, '3P');
          var fd = (pts + (1.5*ast) + (2*stl) + (2*blk) - tov + (1.2*reb)).toFixed(2);
          var ds = (pts + (1.5*ast) + (2*stl) + (2*blk) - tov + (1.25*reb) - (.5*(fga-fgm)) - (.5*(fta-ftm))).toFixed(2);
          var stats = [pts, ast, stl, blk, reb];
          var doubles = stats.map(checkDouble);
          var doublesSum = doubles.reduce(function (a,b) { return a + b });
          var dkBonus = checkBonus(doublesSum);
          var dk = (pts + (1.5*ast) + (2*stl) + (2*blk) - (.5*tov) + (1.25*reb) + (.5*tpt) + dkBonus).toFixed(2);
          var ss = (pts + (1.5*ast) + (1.25*reb) + (2*blk) + (2* stl) - tov).toFixed(2);
    $(this).append("" + fd + "	" + "" + ds + "	" + "" + dk + "	" + "" + ss + "	");
      });
    }
  });
  }
});

<commit_msg>refactor calculations into StatRow object<commit_after>var StatRow = {
  initialize: function($row) {
    this.row = $row;
    return this;
  },

  calculateFD: function(perGame) {
      var games = 1;
      if (perGame) {
        var games = this.getGames();
      }
      return ((this.getValue('PTS') + (1.5*this.getValue('AST')) + (2*this.getValue('STL')) + (2*this.getValue('BLK')) - this.getValue('TOV') + (1.2*this.getValue('TRB')))/games).toFixed(2);
  },

  calculateDK: function(perGame) {
    var games = 1;
    if (perGame) {
      var games = this.getGames();
    }
    var stats = [this.getValue('PTS')/games, this.getValue('AST')/games, this.getValue('STL')/games, this.getValue('BLK')/games, this.getValue('TRB')/games];
    var doubles = stats.map(this.checkDouble);
    var doublesSum = doubles.reduce(function (a,b) { return a + b });
    var dkBonus = this.checkBonus(doublesSum);
    return ((this.getValue('PTS') + (1.5*this.getValue('AST')) + (2*this.getValue('STL')) + (2*this.getValue('BLK')) - (.5*this.getValue('TOV')) + (1.25*this.getValue('TRB')) + (.5*this.getValue('3P')) + dkBonus)/games).toFixed(2);
  },

  getGames: function() {
    return this.getValue('G');
  },

  median: function (values) {
    values.sort( function(a,b) { return a - b; });
    var half = Math.floor(values.length/2);

    if(values.length % 2)
      return values[half];
    else
      return (Number(values[half - 1]) + Number(values[half]))/2.0;
  },

  checkDouble: function (stat) {
    if ( stat >= 10 ) {
      return 1;
    } else {
      return 0;
    }
  },

  checkBonus: function (x) {
    if ( x == 2 ) {
      return 1.5;
    }
    if (x >= 3 ) {
      return 3;
    }
    else {
      return 0;
    }
  },

  getIndex: function(category) {
    var selector = "th:contains(" + category + ")";
    var $table = this.row.parent().parent();
    var idx = $table.find('thead tr:not(.over_header)').first().find(selector).index();
    return idx;
  },

  getValue: function(category) {
    return Number(this.row.find('td').eq(this.getIndex(category)).text());
  }

};

$(document).ready(function() {
  $('#per_minute thead tr, #per_game thead tr, #pgl_basic thead tr, #stats thead tr').append('FD	DK	');
  $('#per_minute tbody tr, #per_minute tfoot tr, #per_game tbody tr, #per_game tfoot tr').each(function(index){
    var $row = $(this);
    var statRow = Object.create(StatRow).initialize($row);
    var fd = statRow.calculateFD();
    var dk = statRow.calculateDK();
    $(this).append("" + fd + "	" + "" + dk + "	");
  });

  var tableHeading = $('.table_heading h2').text();

  $('#stats tbody tr').each(function(index){
    var $row = $(this);
    var perGame = true;
    var statRow = Object.create(StatRow).initialize($row);
    var fd = statRow.calculateFD(perGame);
    var dk = statRow.calculateDK(perGame);
    $(this).append("" + fd + "	" + "" + dk + "	");
  });
  var fd_vals = [];
  var dk_vals = [];
  $("#pgl_basic tbody tr").not(".thead").each(function(index){
    var $row = $(this);
    var statRow = Object.create(StatRow).initialize($row);
    var fd = statRow.calculateFD();
    var dk = statRow.calculateDK();
    fd_vals.push(fd);
    dk_vals.push(dk);
    $(this).append("" + fd + "	" + "" + dk + "	");
  });
  $("#pgl_basic tbody").append("
FD	 Median	" + StatRow.median(fd_vals) + "		Min	" + Math.min.apply(Math,fd_vals) + "		Max	" + Math.max.apply(Math,fd_vals) + "
");
  $("#pgl_basic tbody").append("
DK	 Median	" + StatRow.median(dk_vals) + "		Min	" + Math.min.apply(Math,dk_vals) + "		Max	" + Math.max.apply(Math,dk_vals) + "
");
  var url = document.URL;
  if ( url.split('/')[3] == "boxscores" ) {
    $('table').each(function() {
      if ( $(this).attr('id') != undefined && $(this).attr('id').split('_')[1] == "basic" ) {
        $(this).find('thead tr').not('.over_header').append('FD	DS	');
        $(this).find('tbody tr, tfoot tr').not('.thead').each(function(index){
          var $row = $(this);
          var statRow = Object.create(StatRow).initialize($row);
          var fd = statRow.calculateFD();
          var dk = statRow.calculateDK();
          $(this).append("" + fd + "	" + "" + dk + "	");
      });
    }
  });
  }
});

<|endoftext|>


<commit_before>import React from 'react';
import { Image, SimpleImageEdit } from 'olymp-cloudinary';

export default {
  key: 'Pages.Media.ImageBlock.Image',
  label: 'Bild',
  category: 'Medien',
  component: ({ getData, setActive, className }) =>
    (<Image
      className={className}
      onClick={setActive}
      width={getData('float', 'none') === 'none' ? '100%' : '25%'}
      value={getData('value', {
        url: 'https://lorempixel.com/1000/300/cats/',
        width: 1000,
        height: 300,
      })}
    />),
  styles: ({ getData }) => ({
    float: getData('float', 'none'),
  }),
  actions: [
    {
      component: ({ setData, getData, ...p }) =>
        (<SimpleImageEdit
          {...p}
          onChange={value => setData({ value })}
          value={getData('value', {})}
          multi={false}
        />),
      toggle: () => {},
    },
    {
      label: 'Links',
      active: ({ getData }) => getData('float', 'none') === 'left',
      toggle: ({ setData, getData }) =>
        setData({
          float: getData('float', 'none') === 'left' ? 'none' : 'left',
        }),
    },
    {
      label: 'Rechts',
      active: ({ getData }) => getData('float', 'none') === 'right',
      toggle: ({ setData, getData }) =>
        setData({
          float: getData('float', 'none') === 'right' ? 'none' : 'right',
        }),
    },
  ],
};
<commit_msg>size and alignment in images<commit_after>import React from 'react';
import { Image, SimpleImageEdit } from 'olymp-cloudinary';
import { FaAlignLeft, FaAlignRight, FaPlus, FaMinus } from 'olymp-icons';

export default {
  key: 'Pages.Media.ImageBlock.Image',
  label: 'Bild',
  category: 'Medien',
  component: ({ getData, setActive, className }) =>
    (<Image
      className={className}
      onClick={setActive}
      width={`${100 / getData('size', 4)}%`}
      value={getData('value', {
        url: 'https://lorempixel.com/400/300/cats/',
        width: 400,
        height: 300,
      })}
    />),
  styles: ({ theme, getData }) => ({
    float: getData('float', 'none'),
    margin: getData('float', 'none') === 'none' && '0 auto',
    marginTop: getData('float', 'none') === 'none' && theme.space3,
    marginBottom: theme.space3,
    marginLeft: getData('float', 'none') !== 'left' && theme.space3,
    marginRight: getData('float', 'none') !== 'right' && theme.space3,
    zIndex: 1,
  }),
  actions: [
    {
      component: ({ setData, getData, ...p }) =>
        (<SimpleImageEdit
          {...p}
          onChange={value => setData({ value })}
          value={getData('value', {})}
          multi={false}
        />),
      toggle: () => {},
    },
    {
      label: <FaAlignLeft />,
      active: ({ getData }) => getData('float', 'none') === 'left',
      toggle: ({ setData, getData }) =>
        setData({
          float: getData('float', 'none') === 'left' ? 'none' : 'left',
        }),
    },
    {
      label: <FaAlignRight />,
      active: ({ getData }) => getData('float', 'none') === 'right',
      toggle: ({ setData, getData }) =>
        setData({
          float: getData('float', 'none') === 'right' ? 'none' : 'right',
        }),
    },
    {
      label: <FaPlus />,
      toggle: ({ setData, getData }) => {
        const size = getData('size', 4);
        setData({
          size: size > 1 ? size - 1 : 1,
        });
      },
    },
    {
      label: <FaMinus />,
      toggle: ({ setData, getData }) => {
        const size = getData('size', 4);
        setData({
          size: size < 8 ? size + 1 : 8,
        });
      },
    },
  ],
};
<|endoftext|>


<commit_before>import * as firebase from 'firebase/app';

import { COLLECTION_TRIPS } from '../../constants/database.js';
import { getCurUserEmail, getUidFromUserEmail } from './temp-auth-utils.js'

/**
 * Return a string containing the trip name given the trip name entered in the
 * add trip form.
 *
 * @param {string} rawName String containing trip name entered in add trip form.
 * @return {string} Cleaned trip name.
 */
export function getTripName(rawName) {
  return rawName === '' ? 'Untitled Trip' : rawName;
}

/**
 * Return a string containing the trip destination given the trip destination
 * entered in the add trip form.
 *
 * @param {string} rawName String containing trip description entered in the
 *     add trip form.
 * @return {string} Cleaned trip description.
 */
export function getTripDestination(rawDestination) {
  return rawDestination === '' ? 'No Destination' : rawDestination;
}

/**
 * Return a Firestore Timestamp corresponding to the date in `dateStr`.
 *
 * @param {string} dateStr String containing a date in the form 'yyyy-mm-dd'.
 * @return {firebase.firestore.Timestamp} Firestore timestamp object created.
 */
export function getTimestampFromDateString(dateStr) {
  const dateParts = dateStr.split('-').map(str => +str);
  if (dateParts.length === 1 && dateParts[0] === 0) {
    return firebase.firestore.Timestamp.now();
  }

  const date = new Date(dateParts[0], dateParts[1] - 1, dateParts[2]);
  return firebase.firestore.Timestamp.fromDate(date);
}

/**
 * Return an array of collaborator uids given the emails provided in the
 * add trip form.
 *
 * @param {!Array{string}} collaboratorEmailsArr Array of emails corresponding
 *     to the  collaborators of the trip (not including the trip creator email).
 * @return {!Array{string}} Array of all collaborator uids (including trip
 *     creator uid).
 */
export function getCollaboratorUidArray(collaboratorEmailArr) {
  collaboratorEmailArr = [getCurUserEmail()].concat(collaboratorEmailArr);
  while (collaboratorEmailArr.includes('')) {
    const emptyStrIdx = collaboratorEmailArr.indexOf('');
    collaboratorEmailArr.splice(emptyStrIdx, 1);
  }
  return collaboratorEmailArr.map(userEmail => getUidFromUserEmail(userEmail));
}

/**
 * Returns a formatted and cleaned trip object that will be used as the data
 * for the created Trip document.
 *
 * We know that rawTripObj will contain all of the necessary fields because each
 * key-value pair is explicitly included. This means, only the value
 * corresponding to each key needs to be checked.
 * For text element inputs, React has built in protections against injection/XSS
 * attacks. Thus, no sanitization is needed for text inputs besides providing a
 * default value in a Trip field where applicable.
 *
 * @param {Object} rawTripObj A JS Object containing the raw form data from the
 *     add trip form.
 * @return {Object} Formatted/cleaned version of `rawTripObj` holding the data
 *     for the new Trip document that is to be created.
 */
function formatTripData(rawTripObj) {
  const formattedTripObj =
  {
    trip_creation_time: firebase.firestore.Timestamp.now(),
    name:               getTripName(rawTripObj.name),
    description:        getTripDestination(rawTripObj.destination),
    destination:        rawTripObj.description,
    start_date:         getTimestampFromDateString(rawTripObj.startDate),
    end_date:           getTimestampFromDateString(rawTripObj.endDate),
    collaborators:      getCollaboratorUidArray(rawTripObj.collaboratorEmails)
  };

  return formattedTripObj;
}

/**
 * Adds a new Trip document to firestore with data in `tripObj` and returns a
 * Promise containing a reference to the newly created document.
 *
 * @param {firebase.firestore.Firestore} db The Firestore database instance.
 * @param {Object} tripObj A JS Object containing the Trip document fields.
 */
export function addTripToFirestore(db, tripObj) {
  return db.collection(COLLECTION_TRIPS)
    .add(tripObj)
}

/**
 * Formats/cleans form data and creates new Trip document in firestore.
 *
 * @param {firebase.firestore.Firestore} db The Firestore database instance.
 * @param {Object} rawTripObj A JS Object containing the raw form data from the
 *    add trip form.
 */
function createTrip(db, rawTripObj) {
  const formattedTripObj = formatTripData(rawTripObj);

  addTripToFirestore(db, formattedTripObj)
      .then(docRef => {
        console.log("Document written with ID: ", docRef.id);
      })
      .catch(error => {
        console.error("Error adding document: ", error);
      });
}

export default createTrip;
<commit_msg>Integrated tripId and added case for when trip is being editted/overwritten.<commit_after>import * as firebase from 'firebase/app';

import { COLLECTION_TRIPS } from '../../constants/database.js';
import { getCurUserEmail, getUidFromUserEmail } from './temp-auth-utils.js'

/**
 * Return a string containing the trip name given the trip name entered in the
 * add trip form.
 *
 * @param {string} rawName String containing trip name entered in add trip form.
 * @return {string} Cleaned trip name.
 */
export function getTripName(rawName) {
  return rawName === '' ? 'Untitled Trip' : rawName;
}

/**
 * Return a string containing the trip destination given the trip destination
 * entered in the add trip form.
 *
 * @param {string} rawName String containing trip description entered in the
 *     add trip form.
 * @return {string} Cleaned trip description.
 */
export function getTripDestination(rawDestination) {
  return rawDestination === '' ? 'No Destination' : rawDestination;
}

/**
 * Return a Firestore Timestamp corresponding to the date in `dateStr`.
 *
 * @param {string} dateStr String containing a date in the form 'yyyy-mm-dd'.
 * @return {firebase.firestore.Timestamp} Firestore timestamp object created.
 */
export function getTimestampFromDateString(dateStr) {
  const dateParts = dateStr.split('-').map(str => +str);
  if (dateParts.length === 1 && dateParts[0] === 0) {
    return firebase.firestore.Timestamp.now();
  }

  const date = new Date(dateParts[0], dateParts[1] - 1, dateParts[2]);
  return firebase.firestore.Timestamp.fromDate(date);
}

/**
 * Return an array of collaborator uids given the emails provided in the
 * add trip form.
 *
 * @param {!Array{string}} collaboratorEmailsArr Array of emails corresponding
 *     to the  collaborators of the trip (not including the trip creator email).
 * @return {!Array{string}} Array of all collaborator uids (including trip
 *     creator uid).
 */
export function getCollaboratorUidArray(collaboratorEmailArr) {
  collaboratorEmailArr = [getCurUserEmail()].concat(collaboratorEmailArr);
  while (collaboratorEmailArr.includes('')) {
    const emptyStrIdx = collaboratorEmailArr.indexOf('');
    collaboratorEmailArr.splice(emptyStrIdx, 1);
  }
  return collaboratorEmailArr.map(userEmail => getUidFromUserEmail(userEmail));
}

/**
 * Returns a formatted and cleaned trip object that will be used as the data
 * for the created Trip document.
 *
 * We know that rawTripObj will contain all of the necessary fields because each
 * key-value pair is explicitly included. This means, only the value
 * corresponding to each key needs to be checked.
 * For text element inputs, React has built in protections against injection/XSS
 * attacks. Thus, no sanitization is needed for text inputs besides providing a
 * default value in a Trip field where applicable.
 *
 * @param {Object} rawTripObj A JS Object containing the raw form data from the
 *     add trip form.
 * @return {Object} Formatted/cleaned version of `rawTripObj` holding the data
 *     for the new Trip document that is to be created.
 */
function formatTripData(rawTripObj) {
  const formattedTripObj =
  {
    trip_creation_time: firebase.firestore.Timestamp.now(),
    name:               getTripName(rawTripObj.name),
    description:        getTripDestination(rawTripObj.destination),
    destination:        rawTripObj.description,
    start_date:         getTimestampFromDateString(rawTripObj.startDate),
    end_date:           getTimestampFromDateString(rawTripObj.endDate),
    collaborators:      getCollaboratorUidArray(rawTripObj.collaboratorEmails)
  };

  return formattedTripObj;
}

/**
 * Adds a new Trip document to firestore with data in `tripObj` and returns a
 * Promise containing a reference to the newly created document.
 *
 * @param {firebase.firestore.Firestore} db The Firestore database instance.
 * @param {?string} tripId Document id associated with trip to overwrite.
 *     Null if adding a new trip.
 * @param {Object} tripObj A JS Object containing the Trip document fields.
 */
export function addTripToFirestore(db, tripId, tripObj) {
  if (tripId === null) {
    return db.collection(COLLECTION_TRIPS).add(tripObj);
  }
  return db.collection(COLLECTION_TRIPS).doc(tripId).set(tripObj);
}

/**
 * Formats/cleans form data and creates new Trip document in firestore.
 *
 * @param {firebase.firestore.Firestore} db The Firestore database instance.
 * @param {?string} tripId Document id associated with trip to overwrite.
 *     Null if adding a new trip.
 * @param {Object} rawTripObj A JS Object containing the raw form data from the
 *    add trip form.
 */
function createTrip(db, tripId, rawTripObj) {
  const formattedTripObj = formatTripData(rawTripObj);

  addTripToFirestore(db, tripId, formattedTripObj)
      .then(docRef => {
        console.log("Document written with ID: ", docRef.id);
      })
      .catch(error => {
        console.error("Error adding document: ", error);
      });
}

export default createTrip;
<|endoftext|>


<commit_before>define(["helper/Basic", "Tone/source/Player", "helper/Offline",
	"helper/SourceTests", "Tone/core/Buffer", "helper/Meter", "Test", "Tone/core/Tone"],
	function (BasicTests, Player, Offline, SourceTests, Buffer, Meter, Test, Tone) {

	if (window.__karma__){
		Buffer.baseUrl = "/base/test/";
	}

	describe("Player", function(){

		var buffer = new Buffer();

		beforeEach(function(done){
			buffer.load("./audio/sine.wav", function(){
				done();
			});
		});

		//run the common tests
		BasicTests(Player, buffer);
		SourceTests(Player, buffer);

		context("Constructor", function(){

			it ("can be constructed with a Tone.Buffer", function(done){
				var player = new Player(buffer);
				expect(player.buffer.get()).to.equal(buffer.get());
				player.dispose();
				done();
			});

			it ("can be constructed with an AudioBuffer", function(done){
				var player = new Player(buffer.get());
				expect(player.buffer.get()).to.equal(buffer.get());
				player.dispose();
				done();
			});
		});

		context("Loading", function(){

			it("loads a url which was passed in", function(done){
				var player = new Player("./audio/sine.wav", function(){
					expect(player.loaded).to.be.true;
					player.dispose();
					done();
				});
			});

			it("loads a url using the load method", function(done){
				var player = new Player();
				player.load("./audio/sine.wav", function(){
					expect(player._buffer).to.be.instanceof(Buffer);
					done();
				});
			});

			it("returns a promise", function(done){
				var player = new Player();
				var promise = player.load("./audio/sine.wav");
				expect(promise).to.be.instanceof(Promise);
				promise.then(function(){
					done();
				});
			});

			it("can be created with an options object", function(){
				var player = new Player({
					"url" : "./audio/sine.wav",
					"loop" : true
				});
				player.dispose();
			});

			it("can autostart after loading", function(done){
				var player = new Player({
					"url" : "./audio/sine.wav",
					"autostart" : true,
					"onload" : function(){
						setTimeout(function(){
							expect(player.state).to.be.equal("started");
							done();
						}, 10);
					}
				});
			});

		});

		context("Reverse", function(){

			it("can be played in reverse", function(){
				var audioBuffer = buffer.get().getChannelData(0);
				var lastSample = audioBuffer[audioBuffer.length - 1];
				return Offline(function(){
					var player = new Player(buffer.get()).toMaster();
					player.reverse = true;
					player.start(0);
				}).then(function(buffer){
					var firstSample = buffer.toArray()[0];
					expect(firstSample).to.equal(lastSample);
				});
			});

		});

		context("Looping", function(){

			beforeEach(function(done){
				buffer.load("./audio/short_sine.wav", function(){
					done();
				});
			});

			it("can be set to loop", function(){
				var player = new Player();
				player.loop = true;
				expect(player.loop).to.be.true;
				player.dispose();
			});

			it("can set the loop points", function(){
				var player = new Player();
				player.loopStart = 0.4;
				expect(player.loopStart).to.equal(0.4);
				player.loopEnd = 0.5;
				expect(player.loopEnd).to.equal(0.5);
				player.setLoopPoints(0, 0.2);
				expect(player.loopStart).to.equal(0);
				expect(player.loopEnd).to.equal(0.2);
				player.dispose();
			});

			it("loops the audio", function(){
				return Meter(function(){
					var player = new Player(buffer);
					player.loop = true;
					player.toMaster();
					player.start(0);
				}, buffer.duration * 1.5).then(function(rms){
					rms.forEach(function(level){
						expect(level).to.be.above(0);
					});
				});
			});

			it("offset is the loopStart when set to loop", function(){
				var testSample = buffer.toArray()[Math.floor(0.1 * buffer.context.sampleRate)];
				return Offline(function(){
					var player = new Player(buffer);
					player.loopStart = 0.1;
					player.loop = true;
					player.toMaster();
					player.start(0);
				}, 0.05).then(function(buffer){
					expect(buffer.toArray()[0]).to.equal(testSample);
				});
			});

			it ("correctly compensates if the offset is greater than the loopEnd", function(){
				return Offline(function(){
					//make a ramp between 0-1
					var ramp = new Float32Array(Math.floor(Tone.context.sampleRate * 0.3));
					for (var i = 0; i < ramp.length; i++){
						ramp[i] = (i / (ramp.length)) * 0.3;
					}
					var buff = Buffer.fromArray(ramp);
					var player = new Player(buff).toMaster();
					player.loopStart = 0.1;
					player.loopEnd = 0.2;
					player.loop = true;
					player.start(0, 0.35);
				}, 0.05).then(function(buffer){
					buffer.forEach(function(sample, time){
						if (time < 0.04){
							expect(sample).to.be.within(0.15, 0.2);
						} else if (time > 0.05 && time < 0.09){
							expect(sample).to.be.within(0.1, 0.15);
						}
					});
				});
			});

		});

		context("Get/Set", function(){

			it("can be set with an options object", function(){
				var player = new Player();
				expect(player.loop).to.be.false;
				player.set({
					"loop" : true,
					"loopStart" : 0.4
				});
				expect(player.loop).to.be.true;
				expect(player.loopStart).to.equal(0.4);
				player.dispose();
			});

			it("can set attributes after player is started", function(){
				var player = new Player(buffer);
				expect(player.loop).to.be.false;
				player.start()
				player.set({
					"loopStart" : 0.2,
					"loopEnd" : 0.3,
					"loop" : true,
					"playbackRate" : 0.9
				});
				expect(player.loop).to.be.true;
				expect(player.loopStart).to.equal(0.2);
				expect(player.loopEnd).to.equal(0.3);
				expect(player.playbackRate).to.equal(0.9);
				player.dispose();
			});

			it("can get an options object", function(){
				var player = new Player({
					"url" : "./audio/sine.wav",
					"loopStart" : 0.2,
					"loopEnd" : 0.3,
					"loop" : true,
					"reverse" : true
				});
				expect(player.get().loopStart).to.equal(0.2);
				expect(player.get().loopEnd).to.equal(0.3);
				expect(player.get().loop).to.be.true;
				expect(player.get().reverse).to.be.true;
				player.dispose();
			});

			it("can get/set the playbackRate", function(){
				var player = new Player();
				player.playbackRate = 0.5;
				expect(player.playbackRate).to.equal(0.5);
				player.dispose();
			});

		});

		context("Start Scheduling", function(){

			it("can be start with an offset", function(){
				var testSample = buffer.toArray()[Math.floor(0.1 * buffer.context.sampleRate)];
				return Offline(function(){
					var player = new Player(buffer.get());
					player.toMaster();
					player.start(0, 0.1);
				}).then(function(buffer){
					expect(buffer.toArray()[0]).to.equal(testSample);
				});
			});

			it("is stopped and restarted if retrigger=false", function(){
				return Offline(function(){
					//make a ramp between 0-1
					var ramp = new Float32Array(Math.floor(Tone.context.sampleRate * 0.3));
					for (var i = 0; i < ramp.length; i++){
						ramp[i] = (i / (ramp.length-1));
					}
					var buff = new Buffer().fromArray(ramp);
					var player = new Player(buff).toMaster();
					player.retrigger = false;
					player.start(0);
					player.start(0.1);
				}, 0.31).then(function(buffer){
					expect(buffer.max()).to.be.lessThan(1);
				});
			});

			it("can be retriggered", function(){
				return Offline(function(){
					//make a ramp between 0-1
					var ramp = new Float32Array(Math.floor(Tone.context.sampleRate * 0.3));
					for (var i = 0; i < ramp.length; i++){
						ramp[i] = (i / (ramp.length-1));
					}
					var buff = new Buffer().fromArray(ramp);
					var player = new Player(buff).toMaster();
					player.retrigger = true;
					player.start(0);
					player.start(0.1);
				}, 0.31).then(function(buffer){
					expect(buffer.max()).to.be.greaterThan(1);
				});
			});

			it("only seeks if player is started", function(){
				return Offline(function(){
					player.seek(0.2, 0.01).toMaster();
				}, 0.05).then(function(buffer){
					expect(buffer.isSilent()).to.be.true;
				});
			});

			it("can seek to a position at the given time", function(){
				return Offline(function(){
					var ramp = new Float32Array(Math.floor(Tone.context.sampleRate * 0.3));
					for (var i = 0; i < ramp.length; i++){
						ramp[i] = (i / (ramp.length)) * 0.3;
					}
					var buff = new Buffer().fromArray(ramp);
					var player = new Player(buff).toMaster();
					player.start(0);
					player.seek(0.2, 0.1);
				}, 0.3).then(function(buffer){
					buffer.forEach(function(sample, time){
						if (time < 0.09){
							expect(sample).to.be.within(0, 0.1);
						} else if (time > 0.1 && time < 0.19){
							expect(sample).to.be.within(0.2, 0.3);
						}
					});
				});
			});

			it("can be play for a specific duration", function(){
				return Offline(function(){
					var player = new Player(buffer);
					player.toMaster();
					player.start(0).stop(0.1);
					return function(time){
						Test.whenBetween(time, 0.1, Infinity, function(){
							expect(player.state).to.equal("stopped");
						});
						Test.whenBetween(time, 0, 0.1, function(){
							expect(player.state).to.equal("started");
						});
					};
				}, 0.3).then(function(buffer){
					buffer.forEach(function(sample){
						expect(sample).to.equal(0);
					}, 0.11, 0.15);
				});
			});

			it("stops playing if invoked with 'stop' at a sooner time", function(){
				return Offline(function(){
					var player = new Player(buffer);
					player.toMaster();
					player.start(0).stop(0.1).stop(0.05);
				}, 0.3).then(function(buffer){
					expect(buffer.getLastSoundTime()).to.be.closeTo(0.05, 0.02);
				});
			});

			it("can be play for a specific duration passed in the 'start' method", function(){
				return Offline(function(){
					var player = new Player(buffer);
					player.toMaster();
					player.start(0, 0, 0.1);
					return function(time){
						Test.whenBetween(time, 0.1, Infinity, function(){
							expect(player.state).to.equal("stopped");
						});
						Test.whenBetween(time, 0, 0.1, function(){
							expect(player.state).to.equal("started");
						});
					};
				}, 0.3).then(function(buffer){
					expect(buffer.getLastSoundTime()).to.be.closeTo(0.1, 0.02);
				});
			});

			it("reports itself as stopped after a single iterations of the buffer", function(){
				return Offline(function(){
					var player = new Player(buffer).toMaster();
					player.start();

					return function(time){
						Test.whenBetween(time, buffer.duration, Infinity, function(){
							expect(player.state).to.equal("stopped");
						});
						Test.whenBetween(time, 0, buffer.duration, function(){
							expect(player.state).to.equal("started");
						});
					};
				}, buffer.duration * 1.1);
			});

			it("offsets correctly when started by the Transport", function(){
				var testSample = buffer.toArray()[Math.floor(0.13125 * buffer.context.sampleRate)];
				return Offline(function(Transport){
					var player = new Player(buffer).sync().start(0, 0.1).toMaster();
					Transport.start(0, 0.03125);
				}, 0.05).then(function(buffer){
					expect(buffer.toArray()[0]).to.equal(testSample);
				});
			});
		});
	});
});<commit_msg>player was undefined<commit_after>define(["helper/Basic", "Tone/source/Player", "helper/Offline",
	"helper/SourceTests", "Tone/core/Buffer", "helper/Meter", "Test", "Tone/core/Tone"],
	function (BasicTests, Player, Offline, SourceTests, Buffer, Meter, Test, Tone) {

	if (window.__karma__){
		Buffer.baseUrl = "/base/test/";
	}

	describe("Player", function(){

		var buffer = new Buffer();

		beforeEach(function(done){
			buffer.load("./audio/sine.wav", function(){
				done();
			});
		});

		//run the common tests
		BasicTests(Player, buffer);
		SourceTests(Player, buffer);

		context("Constructor", function(){

			it ("can be constructed with a Tone.Buffer", function(done){
				var player = new Player(buffer);
				expect(player.buffer.get()).to.equal(buffer.get());
				player.dispose();
				done();
			});

			it ("can be constructed with an AudioBuffer", function(done){
				var player = new Player(buffer.get());
				expect(player.buffer.get()).to.equal(buffer.get());
				player.dispose();
				done();
			});
		});

		context("Loading", function(){

			it("loads a url which was passed in", function(done){
				var player = new Player("./audio/sine.wav", function(){
					expect(player.loaded).to.be.true;
					player.dispose();
					done();
				});
			});

			it("loads a url using the load method", function(done){
				var player = new Player();
				player.load("./audio/sine.wav", function(){
					expect(player._buffer).to.be.instanceof(Buffer);
					done();
				});
			});

			it("returns a promise", function(done){
				var player = new Player();
				var promise = player.load("./audio/sine.wav");
				expect(promise).to.be.instanceof(Promise);
				promise.then(function(){
					done();
				});
			});

			it("can be created with an options object", function(){
				var player = new Player({
					"url" : "./audio/sine.wav",
					"loop" : true
				});
				player.dispose();
			});

			it("can autostart after loading", function(done){
				var player = new Player({
					"url" : "./audio/sine.wav",
					"autostart" : true,
					"onload" : function(){
						setTimeout(function(){
							expect(player.state).to.be.equal("started");
							done();
						}, 10);
					}
				});
			});

		});

		context("Reverse", function(){

			it("can be played in reverse", function(){
				var audioBuffer = buffer.get().getChannelData(0);
				var lastSample = audioBuffer[audioBuffer.length - 1];
				return Offline(function(){
					var player = new Player(buffer.get()).toMaster();
					player.reverse = true;
					player.start(0);
				}).then(function(buffer){
					var firstSample = buffer.toArray()[0];
					expect(firstSample).to.equal(lastSample);
				});
			});

		});

		context("Looping", function(){

			beforeEach(function(done){
				buffer.load("./audio/short_sine.wav", function(){
					done();
				});
			});

			it("can be set to loop", function(){
				var player = new Player();
				player.loop = true;
				expect(player.loop).to.be.true;
				player.dispose();
			});

			it("can set the loop points", function(){
				var player = new Player();
				player.loopStart = 0.4;
				expect(player.loopStart).to.equal(0.4);
				player.loopEnd = 0.5;
				expect(player.loopEnd).to.equal(0.5);
				player.setLoopPoints(0, 0.2);
				expect(player.loopStart).to.equal(0);
				expect(player.loopEnd).to.equal(0.2);
				player.dispose();
			});

			it("loops the audio", function(){
				return Meter(function(){
					var player = new Player(buffer);
					player.loop = true;
					player.toMaster();
					player.start(0);
				}, buffer.duration * 1.5).then(function(rms){
					rms.forEach(function(level){
						expect(level).to.be.above(0);
					});
				});
			});

			it("offset is the loopStart when set to loop", function(){
				var testSample = buffer.toArray()[Math.floor(0.1 * buffer.context.sampleRate)];
				return Offline(function(){
					var player = new Player(buffer);
					player.loopStart = 0.1;
					player.loop = true;
					player.toMaster();
					player.start(0);
				}, 0.05).then(function(buffer){
					expect(buffer.toArray()[0]).to.equal(testSample);
				});
			});

			it ("correctly compensates if the offset is greater than the loopEnd", function(){
				return Offline(function(){
					//make a ramp between 0-1
					var ramp = new Float32Array(Math.floor(Tone.context.sampleRate * 0.3));
					for (var i = 0; i < ramp.length; i++){
						ramp[i] = (i / (ramp.length)) * 0.3;
					}
					var buff = Buffer.fromArray(ramp);
					var player = new Player(buff).toMaster();
					player.loopStart = 0.1;
					player.loopEnd = 0.2;
					player.loop = true;
					player.start(0, 0.35);
				}, 0.05).then(function(buffer){
					buffer.forEach(function(sample, time){
						if (time < 0.04){
							expect(sample).to.be.within(0.15, 0.2);
						} else if (time > 0.05 && time < 0.09){
							expect(sample).to.be.within(0.1, 0.15);
						}
					});
				});
			});

		});

		context("Get/Set", function(){

			it("can be set with an options object", function(){
				var player = new Player();
				expect(player.loop).to.be.false;
				player.set({
					"loop" : true,
					"loopStart" : 0.4
				});
				expect(player.loop).to.be.true;
				expect(player.loopStart).to.equal(0.4);
				player.dispose();
			});

			it("can set attributes after player is started", function(){
				var player = new Player(buffer);
				expect(player.loop).to.be.false;
				player.start()
				player.set({
					"loopStart" : 0.2,
					"loopEnd" : 0.3,
					"loop" : true,
					"playbackRate" : 0.9
				});
				expect(player.loop).to.be.true;
				expect(player.loopStart).to.equal(0.2);
				expect(player.loopEnd).to.equal(0.3);
				expect(player.playbackRate).to.equal(0.9);
				player.dispose();
			});

			it("can get an options object", function(){
				var player = new Player({
					"url" : "./audio/sine.wav",
					"loopStart" : 0.2,
					"loopEnd" : 0.3,
					"loop" : true,
					"reverse" : true
				});
				expect(player.get().loopStart).to.equal(0.2);
				expect(player.get().loopEnd).to.equal(0.3);
				expect(player.get().loop).to.be.true;
				expect(player.get().reverse).to.be.true;
				player.dispose();
			});

			it("can get/set the playbackRate", function(){
				var player = new Player();
				player.playbackRate = 0.5;
				expect(player.playbackRate).to.equal(0.5);
				player.dispose();
			});

		});

		context("Start Scheduling", function(){

			it("can be start with an offset", function(){
				var testSample = buffer.toArray()[Math.floor(0.1 * buffer.context.sampleRate)];
				return Offline(function(){
					var player = new Player(buffer.get());
					player.toMaster();
					player.start(0, 0.1);
				}).then(function(buffer){
					expect(buffer.toArray()[0]).to.equal(testSample);
				});
			});

			it("is stopped and restarted if retrigger=false", function(){
				return Offline(function(){
					//make a ramp between 0-1
					var ramp = new Float32Array(Math.floor(Tone.context.sampleRate * 0.3));
					for (var i = 0; i < ramp.length; i++){
						ramp[i] = (i / (ramp.length-1));
					}
					var buff = new Buffer().fromArray(ramp);
					var player = new Player(buff).toMaster();
					player.retrigger = false;
					player.start(0);
					player.start(0.1);
				}, 0.31).then(function(buffer){
					expect(buffer.max()).to.be.lessThan(1);
				});
			});

			it("can be retriggered", function(){
				return Offline(function(){
					//make a ramp between 0-1
					var ramp = new Float32Array(Math.floor(Tone.context.sampleRate * 0.3));
					for (var i = 0; i < ramp.length; i++){
						ramp[i] = (i / (ramp.length-1));
					}
					var buff = new Buffer().fromArray(ramp);
					var player = new Player(buff).toMaster();
					player.retrigger = true;
					player.start(0);
					player.start(0.1);
				}, 0.31).then(function(buffer){
					expect(buffer.max()).to.be.greaterThan(1);
				});
			});

			it("only seeks if player is started", function(){
				return Offline(function(){
					var player = new Player(buffer).toMaster();
					player.seek(0.2, 0.01);
				}, 0.05).then(function(buffer){
					expect(buffer.isSilent()).to.be.true;
				});
			});

			it("can seek to a position at the given time", function(){
				return Offline(function(){
					var ramp = new Float32Array(Math.floor(Tone.context.sampleRate * 0.3));
					for (var i = 0; i < ramp.length; i++){
						ramp[i] = (i / (ramp.length)) * 0.3;
					}
					var buff = new Buffer().fromArray(ramp);
					var player = new Player(buff).toMaster();
					player.start(0);
					player.seek(0.2, 0.1);
				}, 0.3).then(function(buffer){
					buffer.forEach(function(sample, time){
						if (time < 0.09){
							expect(sample).to.be.within(0, 0.1);
						} else if (time > 0.1 && time < 0.19){
							expect(sample).to.be.within(0.2, 0.3);
						}
					});
				});
			});

			it("can be play for a specific duration", function(){
				return Offline(function(){
					var player = new Player(buffer);
					player.toMaster();
					player.start(0).stop(0.1);
					return function(time){
						Test.whenBetween(time, 0.1, Infinity, function(){
							expect(player.state).to.equal("stopped");
						});
						Test.whenBetween(time, 0, 0.1, function(){
							expect(player.state).to.equal("started");
						});
					};
				}, 0.3).then(function(buffer){
					buffer.forEach(function(sample){
						expect(sample).to.equal(0);
					}, 0.11, 0.15);
				});
			});

			it("stops playing if invoked with 'stop' at a sooner time", function(){
				return Offline(function(){
					var player = new Player(buffer);
					player.toMaster();
					player.start(0).stop(0.1).stop(0.05);
				}, 0.3).then(function(buffer){
					expect(buffer.getLastSoundTime()).to.be.closeTo(0.05, 0.02);
				});
			});

			it("can be play for a specific duration passed in the 'start' method", function(){
				return Offline(function(){
					var player = new Player(buffer);
					player.toMaster();
					player.start(0, 0, 0.1);
					return function(time){
						Test.whenBetween(time, 0.1, Infinity, function(){
							expect(player.state).to.equal("stopped");
						});
						Test.whenBetween(time, 0, 0.1, function(){
							expect(player.state).to.equal("started");
						});
					};
				}, 0.3).then(function(buffer){
					expect(buffer.getLastSoundTime()).to.be.closeTo(0.1, 0.02);
				});
			});

			it("reports itself as stopped after a single iterations of the buffer", function(){
				return Offline(function(){
					var player = new Player(buffer).toMaster();
					player.start();

					return function(time){
						Test.whenBetween(time, buffer.duration, Infinity, function(){
							expect(player.state).to.equal("stopped");
						});
						Test.whenBetween(time, 0, buffer.duration, function(){
							expect(player.state).to.equal("started");
						});
					};
				}, buffer.duration * 1.1);
			});

			it("offsets correctly when started by the Transport", function(){
				var testSample = buffer.toArray()[Math.floor(0.13125 * buffer.context.sampleRate)];
				return Offline(function(Transport){
					var player = new Player(buffer).sync().start(0, 0.1).toMaster();
					Transport.start(0, 0.03125);
				}, 0.05).then(function(buffer){
					expect(buffer.toArray()[0]).to.equal(testSample);
				});
			});
		});
	});
});<|endoftext|>


<commit_before>jest.mock('fs-extra');

jest.mock('@emdaer/core', () => async () => 'Hello, World!', {
  virtual: true,
});

const fs = require('fs-extra');

const importPlugin = require('./');

describe('@emdaer/plugin-import', () => {
  test('imports a file', async () => {
    fs.readFile.mockImplementation(
      async () =>
        'This is the water and this is the well. Drink full and descend. The horse is the white of the eyes and dark within.'
    );
    expect(await importPlugin({ path: './tmp/.DS_Store' })).toBe(
      'This is the water and this is the well. Drink full and descend. The horse is the white of the eyes and dark within.'
    );
  });

  test('imports a file and runs emdaer on it', async () => {
    fs.readFile.mockImplementation(
      async () =>
        `This is the water and this is the well. Drink full and descend. The horse is the white of the eyes and dark within.
<!--emdaer-p
  - '@emdaer/plugin-value-from-package'
  - value: name
-->`
    );
    expect(
      await importPlugin({ path: './tmp/.DS_Store', runEmdaer: true })
    ).toBe('Hello, World!');
  });
});
<commit_msg>test(plugin-import): hey core is here<commit_after>jest.mock('fs-extra');

jest.mock('@emdaer/core');

const fs = require('fs-extra');
const emdaer = require('@emdaer/core');

const importPlugin = require('./');

describe('@emdaer/plugin-import', () => {
  test('imports a file', async () => {
    fs.readFile.mockImplementation(
      async () =>
        'This is the water and this is the well. Drink full and descend. The horse is the white of the eyes and dark within.'
    );
    expect(await importPlugin({ path: './tmp/.DS_Store' })).toBe(
      'This is the water and this is the well. Drink full and descend. The horse is the white of the eyes and dark within.'
    );
  });

  test('imports a file and runs emdaer on it', async () => {
    fs.readFile.mockImplementation(
      async () =>
        `This is the water and this is the well. Drink full and descend. The horse is the white of the eyes and dark within.
<!--emdaer-p
  - '@emdaer/plugin-value-from-package'
  - value: name
-->`
    );
    await importPlugin({ path: './tmp/.DS_Store', runEmdaer: true });
    expect(emdaer).toHaveBeenCalled();
  });
});
<|endoftext|>