<commit_before>var dgram = require('dgram');
var util = require('util');
var EventEmitter = require('events').EventEmitter;

var Artnet = function (config) {
    if (!(this instanceof Artnet)) {
        return new Artnet(config);
    }

    var that = this;

    config = config || {};

    /* eslint-disable no-multi-spaces */
    var host =     config.host                    || '255.255.255.255';
    var port =     parseInt(config.port, 10)      || 6454;
    var refresh =  parseInt(config.refresh, 10)   || 4000;
    var sendAll =  config.sendAll                 || false;

    var socket = dgram.createSocket('udp4');

    socket.on('error', function (err) {
        that.emit('error', err);
    });

    if (config.iface && (host === '255.255.255.255')) {
        socket.bind(port, config.iface, function () {
            socket.setBroadcast(true);
        });
    } else if (host.endsWith('255')) {
        socket.bind(port, function () {
            socket.setBroadcast(true);
        });
    }

    // Index of the following arrays is the universe
    var data =          []; // The 512 dmx channels
    var interval =      []; // The intervals for the 4sec refresh
    var sendThrottle =  []; // The timeouts
    var sendDelayed =   []; // Boolean flag indicating if data should be sent after sendThrottle timeout
    var dataChanged =   []; // The highest channel number that had a change. mind that channel counting starts at 1!

    this.data = data;

    var startRefresh = function (universe) {
        interval[universe] = setInterval(function () {
            that.send(universe, 512);
        }, refresh);
    };

    // See http://www.artisticlicence.com/WebSiteMaster/User%20Guides/art-net.pdf page 45
    var artdmxPackage = function (universe, length) {
        length = parseInt(length, 10) || 2;
        if (length % 2) {
            length += 1;
        }

        /* eslint-disable unicorn/number-literal-case */
        var hUni = (universe >> 8) & 0xff;
        var lUni = universe & 0xff;

        var hLen = (length >> 8) & 0xff;
        var lLen = (length & 0xff);

        var header = [65, 114, 116, 45, 78, 101, 116, 0, 0, 80, 0, 14, 0, 0, lUni, hUni, hLen, lLen];

        if (!data[universe]) {
            data[universe] = Array.apply(null, new Array(512)).map(function () {
                return null;
            }, 0);
        }
        // eslint-disable-next-line unicorn/no-new-buffer
        return new Buffer(header.concat(data[universe].slice(0, (hLen * 256) + lLen)));
    };

    // If refresh is set to true all 512 channels will be sent, otherwise from channel 1 to the last changed channel
    this.send = function (universe, refresh, callback) {
        if (typeof refresh === 'function') {
            callback = refresh;
            refresh = false;
        }

        if (sendAll) {
            refresh = true;
        }

        if (!interval[universe]) {
            startRefresh(universe);
        }

        if (sendThrottle[universe]) {
            sendDelayed[universe] = true;
            return;
        }

        clearTimeout(sendThrottle[universe]);
        sendThrottle[universe] = setTimeout(function () {
            sendThrottle[universe] = null;
            if (sendDelayed[universe]) {
                sendDelayed[universe] = false;
                that.send(universe, callback);
            }
        }, 25);

        var buf = artdmxPackage(universe, refresh ? 512 : dataChanged[universe]);
        dataChanged[universe] = 0;
        socket.send(buf, 0, buf.length, port, host, callback);
    };

    /* [ [ uint15 universe, ] uint9 channel, ] uint8 value [, function callback ] */
    /* [ [ uint15 universe, ] uint9 channel, ] array[uint8] values [, function callback ] */
    this.set = function () {
        var universe;
        var channel;
        var value;
        var callback;

        if (arguments.length === 4) {
            universe = arguments[0];
            channel = arguments[1];
            value = arguments[2];
            callback = arguments[3];
        } else if (arguments.length === 3) {
            if (typeof arguments[2] === 'function') {
                channel = arguments[0];
                value = arguments[1];
                callback = arguments[2];
            } else {
                universe = arguments[0];
                channel = arguments[1];
                value = arguments[2];
            }
        } else if (arguments.length === 2) {
            if (typeof arguments[1] === 'function') {
                channel = 1;
                value = arguments[0];
                callback = arguments[1];
            } else {
                channel = arguments[0];
                value = arguments[1];
            }
        } else if (arguments.length === 1) {
            channel = 1;
            value = arguments[0];
        } else {
            return false;
        }

        universe = parseInt(universe, 10) || 0;

        if (!data[universe]) {
            data[universe] = Array.apply(null, new Array(512)).map(function () {
                return null;
            }, 0);
        }

        dataChanged[universe] = dataChanged[universe] || 0;

        var index;
        if ((typeof value === 'object') && (value.length > 0)) {
            for (var i = 0; i < value.length; i++) {
                index = channel + i - 1;
                if (typeof value[i] === 'number' && data[universe][index] !== value[i]) {
                    data[universe][index] = value[i];
                    if ((index + 1) > dataChanged[universe]) {
                        dataChanged[universe] = index + 1;
                    }
                }
            }
        } else if (typeof value === 'number' && data[universe][channel - 1] !== value) {
            data[universe][channel - 1] = value;
            if (channel > dataChanged[universe]) {
                dataChanged[universe] = channel;
            }
        }

        if (dataChanged[universe]) {
            that.send(universe, callback);
        } else if (typeof callback === 'function') {
            callback(null, null);
        }

        return true;
    };

    this.close = function () {
        var i;
        for (i = 0; i < interval.length; i++) {
            clearInterval(interval[i]);
        }
        for (i = 0; i < sendThrottle.length; i++) {
            clearTimeout(sendThrottle[i]);
        }
        socket.close();
    };

    this.setHost = function (h) {
        host = h;
    };

    this.setPort = function (p) {
        if (host === '255.255.255.255') {
            throw new Error('Can\'t change port when using broadcast address 255.255.255.255');
        } else {
            port = p;
        }
    };
};

util.inherits(Artnet, EventEmitter);

module.exports = Artnet;
<commit_msg>keep compatiblity to old node versions<commit_after>var dgram = require('dgram');
var util = require('util');
var EventEmitter = require('events').EventEmitter;

var Artnet = function (config) {
    if (!(this instanceof Artnet)) {
        return new Artnet(config);
    }

    var that = this;

    config = config || {};

    /* eslint-disable no-multi-spaces */
    var host =     config.host                    || '255.255.255.255';
    var port =     parseInt(config.port, 10)      || 6454;
    var refresh =  parseInt(config.refresh, 10)   || 4000;
    var sendAll =  config.sendAll                 || false;

    var socket = dgram.createSocket('udp4');

    socket.on('error', function (err) {
        that.emit('error', err);
    });

    if (config.iface && (host === '255.255.255.255')) {
        socket.bind(port, config.iface, function () {
            socket.setBroadcast(true);
        });
    } else if (host.match(/255$/)) {
        socket.bind(port, function () {
            socket.setBroadcast(true);
        });
    }

    // Index of the following arrays is the universe
    var data =          []; // The 512 dmx channels
    var interval =      []; // The intervals for the 4sec refresh
    var sendThrottle =  []; // The timeouts
    var sendDelayed =   []; // Boolean flag indicating if data should be sent after sendThrottle timeout
    var dataChanged =   []; // The highest channel number that had a change. mind that channel counting starts at 1!

    this.data = data;

    var startRefresh = function (universe) {
        interval[universe] = setInterval(function () {
            that.send(universe, 512);
        }, refresh);
    };

    // See http://www.artisticlicence.com/WebSiteMaster/User%20Guides/art-net.pdf page 45
    var artdmxPackage = function (universe, length) {
        length = parseInt(length, 10) || 2;
        if (length % 2) {
            length += 1;
        }

        /* eslint-disable unicorn/number-literal-case */
        var hUni = (universe >> 8) & 0xff;
        var lUni = universe & 0xff;

        var hLen = (length >> 8) & 0xff;
        var lLen = (length & 0xff);

        var header = [65, 114, 116, 45, 78, 101, 116, 0, 0, 80, 0, 14, 0, 0, lUni, hUni, hLen, lLen];

        if (!data[universe]) {
            data[universe] = Array.apply(null, new Array(512)).map(function () {
                return null;
            }, 0);
        }
        // eslint-disable-next-line unicorn/no-new-buffer
        return new Buffer(header.concat(data[universe].slice(0, (hLen * 256) + lLen)));
    };

    // If refresh is set to true all 512 channels will be sent, otherwise from channel 1 to the last changed channel
    this.send = function (universe, refresh, callback) {
        if (typeof refresh === 'function') {
            callback = refresh;
            refresh = false;
        }

        if (sendAll) {
            refresh = true;
        }

        if (!interval[universe]) {
            startRefresh(universe);
        }

        if (sendThrottle[universe]) {
            sendDelayed[universe] = true;
            return;
        }

        clearTimeout(sendThrottle[universe]);
        sendThrottle[universe] = setTimeout(function () {
            sendThrottle[universe] = null;
            if (sendDelayed[universe]) {
                sendDelayed[universe] = false;
                that.send(universe, callback);
            }
        }, 25);

        var buf = artdmxPackage(universe, refresh ? 512 : dataChanged[universe]);
        dataChanged[universe] = 0;
        socket.send(buf, 0, buf.length, port, host, callback);
    };

    /* [ [ uint15 universe, ] uint9 channel, ] uint8 value [, function callback ] */
    /* [ [ uint15 universe, ] uint9 channel, ] array[uint8] values [, function callback ] */
    this.set = function () {
        var universe;
        var channel;
        var value;
        var callback;

        if (arguments.length === 4) {
            universe = arguments[0];
            channel = arguments[1];
            value = arguments[2];
            callback = arguments[3];
        } else if (arguments.length === 3) {
            if (typeof arguments[2] === 'function') {
                channel = arguments[0];
                value = arguments[1];
                callback = arguments[2];
            } else {
                universe = arguments[0];
                channel = arguments[1];
                value = arguments[2];
            }
        } else if (arguments.length === 2) {
            if (typeof arguments[1] === 'function') {
                channel = 1;
                value = arguments[0];
                callback = arguments[1];
            } else {
                channel = arguments[0];
                value = arguments[1];
            }
        } else if (arguments.length === 1) {
            channel = 1;
            value = arguments[0];
        } else {
            return false;
        }

        universe = parseInt(universe, 10) || 0;

        if (!data[universe]) {
            data[universe] = Array.apply(null, new Array(512)).map(function () {
                return null;
            }, 0);
        }

        dataChanged[universe] = dataChanged[universe] || 0;

        var index;
        if ((typeof value === 'object') && (value.length > 0)) {
            for (var i = 0; i < value.length; i++) {
                index = channel + i - 1;
                if (typeof value[i] === 'number' && data[universe][index] !== value[i]) {
                    data[universe][index] = value[i];
                    if ((index + 1) > dataChanged[universe]) {
                        dataChanged[universe] = index + 1;
                    }
                }
            }
        } else if (typeof value === 'number' && data[universe][channel - 1] !== value) {
            data[universe][channel - 1] = value;
            if (channel > dataChanged[universe]) {
                dataChanged[universe] = channel;
            }
        }

        if (dataChanged[universe]) {
            that.send(universe, callback);
        } else if (typeof callback === 'function') {
            callback(null, null);
        }

        return true;
    };

    this.close = function () {
        var i;
        for (i = 0; i < interval.length; i++) {
            clearInterval(interval[i]);
        }
        for (i = 0; i < sendThrottle.length; i++) {
            clearTimeout(sendThrottle[i]);
        }
        socket.close();
    };

    this.setHost = function (h) {
        host = h;
    };

    this.setPort = function (p) {
        if (host === '255.255.255.255') {
            throw new Error('Can\'t change port when using broadcast address 255.255.255.255');
        } else {
            port = p;
        }
    };
};

util.inherits(Artnet, EventEmitter);

module.exports = Artnet;
<|endoftext|>


<commit_before>import path from 'path';
import postcss from 'postcss';
import logError from './log_error';
import promisify from 'es6-promisify';
import {readFile} from './async';

async function scanUrls(decl, updatePath) {
  let tokens = decl.value.split(/(url\(.*?\))/); //urls will be at odd indices in the resulting array
  if (tokens.length < 2) return; //no urls
  for (let i = 1; i < tokens.length; i += 2) {
    let token = tokens[i];
    let [, url, queryString] = token.match(/url\(\s*['"]?([^'"?#]*)([^'")]*)/);
    let newUrl = await updatePath(url);
    tokens[i] = `url('${newUrl}${queryString}')`;
  }
  decl.value = tokens.join('');
}

function decls(root) {
  let decls = [];
  root.eachDecl(decl => decls.push(decl));
  return decls;
}

function updateCssPaths(css, updatePath) {
  return logError(
    postcss([
      async root => await* decls(root).map(decl =>
        logError(scanUrls(decl, updatePath), `Failed to parse CSS rule ${decl.value}`)
      )
    ]).process(css),
    'PostCSS has failed to parse the CSS. Exiting.'
  );
}

export default async (cssFiles, askUserForPath) => {
  askUserForPath = promisify(askUserForPath);
  let concatenatedCss = '';
  for (let cssFile of cssFiles) {
    console.error(`Processing css: ${cssFile}`);
    let css = await logError(readFile(cssFile), `Could not read CSS file: ${cssFile}. Exiting.`);
    let result = await updateCssPaths(css, async assetPath => {
      console.error(`Processing asset: ${assetPath}`);
      let asset = await logError(
        readFile(path.resolve(path.dirname(cssFile), assetPath)),
        `Could not read asset ${assetPath} imported by ${cssFile}`
      );
      let {path: newPath} = await logError(askUserForPath({path: assetPath, importedBy: cssFile, contents: asset}));
      return newPath;
    });
    concatenatedCss += `\n${result.css}`;
  }
  await logError(askUserForPath({path: 'components.css', contents: new Buffer(concatenatedCss)}));
};
<commit_msg>feat(logging): Put logging behind NODE_DEBUG=dr-frankenstyle flag<commit_after>import util from 'util';
import path from 'path';
import postcss from 'postcss';
import logError from './log_error';
import promisify from 'es6-promisify';
import {readFile} from './async';

const debug = util.debuglog('dr-frankenstyle');

async function scanUrls(decl, updatePath) {
  let tokens = decl.value.split(/(url\(.*?\))/); //urls will be at odd indices in the resulting array
  if (tokens.length < 2) return; //no urls
  for (let i = 1; i < tokens.length; i += 2) {
    let token = tokens[i];
    let [, url, queryString] = token.match(/url\(\s*['"]?([^'"?#]*)([^'")]*)/);
    let newUrl = await updatePath(url);
    tokens[i] = `url('${newUrl}${queryString}')`;
  }
  decl.value = tokens.join('');
}

function decls(root) {
  let decls = [];
  root.eachDecl(decl => decls.push(decl));
  return decls;
}

function updateCssPaths(css, updatePath) {
  return logError(
    postcss([
      async root => await* decls(root).map(decl =>
        logError(scanUrls(decl, updatePath), `Failed to parse CSS rule ${decl.value}`)
      )
    ]).process(css),
    'PostCSS has failed to parse the CSS. Exiting.'
  );
}

export default async (cssFiles, askUserForPath) => {
  askUserForPath = promisify(askUserForPath);
  let concatenatedCss = '';
  for (let cssFile of cssFiles) {
    debug(`Processing css: ${cssFile}`);
    let css = await logError(readFile(cssFile), `Could not read CSS file: ${cssFile}. Exiting.`);
    let result = await updateCssPaths(css, async assetPath => {
      debug(`Processing asset: ${assetPath}`);
      let asset = await logError(
        readFile(path.resolve(path.dirname(cssFile), assetPath)),
        `Could not read asset ${assetPath} imported by ${cssFile}`
      );
      let {path: newPath} = await logError(askUserForPath({path: assetPath, importedBy: cssFile, contents: asset}));
      return newPath;
    });
    concatenatedCss += `\n${result.css}`;
  }
  await logError(askUserForPath({path: 'components.css', contents: new Buffer(concatenatedCss)}));
};
<|endoftext|>


<commit_before>// jQuery UI comes from the static application
$.fn.sortable = function () {} // noop

module('Sorting options', {
  setup: function () {
    this.container = $('<fieldset></fieldset>')
    var thingOne = $('
one <input name="input_one" type="text" />other thing: <input name="other_thing_one" type="text" />
')
    var thingTwo = $('
two <input name="input_two" type="text" />other thing: <input name="other_thing_two" type="text" />
')
    this.container.append(thingOne)
    this.container.append(thingTwo)
    $('#qunit-fixture').append(this.container)
  }
})

test('should build a list from the contents of the labels', function () {
  this.container.enableSortable()
  var list = this.container.siblings('ul')
  equal('one other thing: two other thing: ', list.text()) // I would compare arrays, but Javascript can't do that easily. GAH.
})

test('should hide the input fields', function () {
  this.container.enableSortable()
  ok(!this.container.children('input').is(':visible'))
})
<commit_msg>Port sortable JS tests from QUnit to Jasmine<commit_after>describe('jQuery.enableSortable', function () {
  var container, fieldset

  beforeEach(function () {
    fieldset = $(
      '<fieldset>' +
        '
one <input name="input_one" type="text" />other thing: <input name="other_thing_one" type="text" />
' +
        '
two <input name="input_two" type="text" />other thing: <input name="other_thing_two" type="text" />
' +
      '</fieldset>'
    )
    container = $('
').append(fieldset)
    $(document.body).append(container)
  })

  afterEach(function () {
    container.remove()
  })

  it('should build a list from the contents of the labels', function () {
    fieldset.enableSortable()
    var listText = fieldset
      .siblings('ul')
      .children()
      .map(function () { return $(this).text() })
      .get()
    expect(listText).toEqual(['one other thing: ', 'two other thing: '])
  })

  it('should hide the input fields', function () {
    fieldset.enableSortable()
    expect(fieldset.children('input').is(':visible')).toBeFalse()
  })
})
<|endoftext|>


<commit_before>import { read } from './path'
import { message, extend, extract } from './message'

const get = path => extend((input) => {
  const location = extract(path(input))

  let value = read(location, input.data)
  if (value === undefined) {
    value = read(location, input.scope)
  }

  return value
})

export default get
<commit_msg>collapse<commit_after>import { read } from './path'
import { message, extend, extract, collapse } from './message'

const get = path => extend(input =>
  read(extract(path(input)), collapse(input))
)

export default get
<|endoftext|>


<commit_before>module.exports = function bridge(win){
  function isObject(o){
    if (o == null) return o !== null && o !== undefined;
    return typeof o === 'object' || typeof o === 'function';
  }

  var _call      = Function.prototype.call,
      _apply     = Function.prototype.apply,
      _bind      = Function.prototype.bind,
      _slice     = Array.prototype.slice,
      _hasOwn    = Object.prototype.hasOwnProperty;

  var proxies = new WeakMap,
      farIDs = new WeakMap,
      nearIDs = new WeakMap,
      mirrors = Object.create(null);

  if (!arguments.length) {
    var items = [window],
        pipe = appjs,
        nid = 'bid',
        bid = 'nid';
    nearIDs.set(window, 0);
    setTimeout(function(){ window.node = unwrap([bid, 0]) }, 100);
  } else {
    var items = [global],
        pipe = win,
        nid = 'nid',
        bid = 'bid';
    nearIDs.set(global, 0);
    setTimeout(function(){ win.window = unwrap([bid, 0]) }, 100);
  }

  var TRUE        = [ 'ø', true ],
      FALSE       = [ 'ø', false ],
      UNDEFINED   = [ 'ø', '_Δ' ],
      NULL        = [ 'ø', null ],
      NAN         = [ 'ø', '_ƒ' ],
      INFINITY    = [ 'ø', '_Ω' ],
      NEGINFINITY = [ 'ø', '_-Ω' ],
      NEGZERO     = [ 'ø', '_π' ],
      ZERO        = [ 'ø', 0 ];

  function encodePrimitive(o){
    switch (typeof o) {
      case 'boolean':      return o ? TRUE : FALSE;
      case 'undefined':    return UNDEFINED;
      case 'object':       return NULL;
      case 'string':       return ['ø', o];
      case 'number':
        switch (o) {
          case Infinity:   return INFINITY;
          case -Infinity:  return NEGINFINITY;
          case NaN:        return NAN;
          case 0:          return 1 / o === -Infinity ? NEGZERO : ZERO;
          default:         return o !== o ? NAN : ['ø', o];
        }
    }
  }

  function decodePrimitive(o){
    switch (o[1]) {
      case '_Δ': return undefined;
      case '_ƒ': return NaN;
      case '_Ω': return Infinity;
      case '_-Ω': return -Infinity;
      case '_π': return -0;
      default: return o[1];
    }
  }

  function unwrap(obj){
    if (!isObject(obj)) {
      return obj;
    } else if (obj[0] == 'ø') {
      return decodePrimitive(obj);
    } else if (obj[0] === bid) {
      if (obj[1] in mirrors) {
        return farIDs.get(mirrors[obj[1]]);
      } else {
        var proxy = new Mirror(obj);
        proxies.set(proxy, obj);
        farIDs.set(obj, proxy);
        mirrors[obj[1]] = obj;
        return proxy;
      }
    } else if (obj[0] === nid) {
      return items[obj[1]];
    } else {
      return obj;
    }
  }

  function wrap(obj){
    if (!isObject(obj)) {
      return encodePrimitive(obj);
    } else if (proxies.has(obj)) {
      return proxies.get(obj);
    } else {
      var id = nearIDs.get(obj);
      if (id === undefined) {
        nearIDs.set(obj, id = items.length);
        items.push(obj);
      }
      return [nid, id];
    }
  }

  var mirror = {
    type: function type(obj){
      return [typeof obj];
    },
    keys: function keys(obj){
      return Object.keys(obj);
    },
    enumerate: function enumerate(obj){
      var i=0, k=[];
      for (k[i++] in obj);
      return k;
    },
    props: function props(obj){
      return Object.getOwnPropertyNames(obj);
    },
    get: function get(obj, key){
      return wrap(obj[key]);
    },
    proto: function proto(obj){
      return wrap(obj.__proto__);
    },
    has: function has(obj, key){
      return wrap(key in obj);
    },
    hasOwn: function hasOwn(obj, key){
      return wrap(_hasOwn.call(obj, key));
    },
    delete: function delete_(obj, key){
      delete obj[key];
      return TRUE;
    },
    define: function define(obj, key, desc){
      if (_hasOwn.call(desc, 'value')) {
        desc.value = unwrap(desc.value);
      } else {
        desc.get = unwrap(desc.get);
        desc.set = unwrap(desc.set);
      }
      Object.defineProperty(obj, key, desc);
      return TRUE;
    },
    describe: function describe(obj, key){
      var desc = Object.getOwnPropertyDescriptor(obj, key);
      if (desc) {
        desc.configurable = true;
        if (_hasOwn.call(desc, 'value')) {
          if (desc.value === undefined) desc.value = obj[key];
          desc.value = wrap(desc.value);
        } else {
          desc.get = wrap(desc.get);
          desc.set = wrap(desc.set);
        }
        return desc;
      } else if (desc === undefined && _hasOwn.call(obj, key)) {
        return { configurable: true,
                 enumerable: true,
                 writable: true,
                 value: wrap(obj[key]) };
      } else {
        return UNDEFINED;
      }
    },
    construct: function construct(obj, args){
      try {
        return wrap(new (_bind.apply(obj, [null].concat(args.map(unwrap)))));
      } catch (e) {
        return wrap(e);
      }
    },
  };

  if (win) {
    mirror.apply = function apply(obj, receiver, args){
      try {
        return wrap(_apply.call(obj, unwrap(receiver), args.map(unwrap)));
      } catch (e) {
        return wrap(e);
      }
    };
    mirror.set = function set(obj, key, value){
      obj[key] = unwrap(value);
      return TRUE;
    };
  } else {
    var proxyForProxy = function proxyForProxy(fn){
      return function(){ return _apply.call(fn, this, arguments) };
    }
    mirror.apply = function apply(obj, receiver, args){
      try {
        // workaround for bug where proxy functions are not valid DOM event handlers
        args = args.map(unwrap);
        if (obj.name === 'addEventListener' && typeof args[1] === 'function') {
          args[1] = proxyForProxy(args[1]);
        }
        return wrap(_apply.call(obj, unwrap(receiver), args));
      } catch (e) {
        return wrap(e);
      }
    };
    mirror.set = function set(obj, key, value){
      value = unwrap(value);
      obj[key] = value;
      if (obj[key] === null && typeof value === 'function') {
        // workaround for bug where proxy functions are not valid DOM event handlers
        obj[key] = proxyForProxy(value);
      }
      return TRUE;
    };
  }

  function Mirror(obj){
    var self = this;
    var type = pipe.send('Δtype', obj)[0];
    this.a = obj;
    this.b = obj.concat(null);
    this.c = obj.concat(null, null);
    if (type === 'function') {
      return Proxy.createFunction(this,
        function(){ return self.apply(this, _slice.call(arguments)) },
        function(){ return self.construct(_slice.call(arguments)) }
      );
    } else {
      return Proxy.create(this, unwrap(pipe.send('Δproto', this.a)));
    }
  }

  Mirror.prototype = {
    keys: function keys(){
      return pipe.send('Δkeys', this.a);
    },
    enumerate: function enumerate(){
      return pipe.send('Δenumerate', this.a);
    },
    getOwnPropertyNames: function getOwnPropertyNames(){
      return pipe.send('Δprops', this.a);
    },
    get: function get(rcvr, key){
      this.b[2] = key;
      if (wrap(rcvr) !== this.a) {
        console.log(rcvr);
      }
      return unwrap(pipe.send('Δget', this.b));
    },
    set: function set(rcvr, key, value){
      this.c[2] = key;
      this.c[3] = wrap(value);
      if (wrap(rcvr) !== this.a) {
        console.log(rcvr);
      }
      pipe.send('Δset', this.c);
      return true;
    },
    getOwnPropertyDescriptor: function getOwnPropertyDescriptor(key){
      this.b[2] = key;
      var desc = pipe.send('Δdescribe', this.b);
      if (desc) {
        desc.configurable = true;
        if (isObject(desc.value)) {
          desc.value = unwrap(desc.value);
        } else {
          desc.get = unwrap(desc.get);
          desc.set = unwrap(desc.set);
        }
      }
      return desc;
    },
    has: function has(key){
      this.b[2] = key;
      return pipe.send('Δhas', this.b);
    },
    hasOwn: function hasOwn(key){
      this.b[2] = key;
      return pipe.send('ΔhasOwn', this.b);
    },
    delete: function delete_(key){
      this.b[2] = key;
      pipe.send('Δdelete', this.b);
      return true;
    },
    defineProperty: function defineProperty(key, desc){
      this.c[2] = key;
      this.c[3] = desc = wrap(desc);
      if (_hasOwn.call(desc, 'value')) {
        desc.value = wrap(desc.value);
      } else {
        desc.get = wrap(desc.get);
        desc.set = wrap(desc.set);
      }
      pipe.send('Δdefine', this.c);
    },
    apply: function apply(receiver, args){
      this.c[2] = wrap(receiver);
      this.c[3] = args.map(wrap);
      return unwrap(pipe.send('Δapply', this.c));
    },
    construct: function construct(args){
      this.b[2] = args.map(wrap);
      return unwrap(pipe.send('Δconstruct', this.b));
    }
  };

  Object.keys(mirror).forEach(function(key){
    pipe.on('Δ'+key, function(val, res){
      res.result = mirror[key](unwrap(val), val[2], val[3]);
    });
  });
}
<commit_msg>make it so the bridge is available for the ready event<commit_after>module.exports = function bridge(win){
  function isObject(o){
    if (o == null) return o !== null && o !== undefined;
    return typeof o === 'object' || typeof o === 'function';
  }

  var _call      = Function.prototype.call,
      _apply     = Function.prototype.apply,
      _bind      = Function.prototype.bind,
      _slice     = Array.prototype.slice,
      _hasOwn    = Object.prototype.hasOwnProperty;

  var proxies = new WeakMap,
      farIDs = new WeakMap,
      nearIDs = new WeakMap,
      mirrors = Object.create(null);

  var TRUE        = [ 'ø', true ],
      FALSE       = [ 'ø', false ],
      UNDEFINED   = [ 'ø', '_Δ' ],
      NULL        = [ 'ø', null ],
      NAN         = [ 'ø', '_ƒ' ],
      INFINITY    = [ 'ø', '_Ω' ],
      NEGINFINITY = [ 'ø', '_-Ω' ],
      NEGZERO     = [ 'ø', '_π' ],
      ZERO        = [ 'ø', 0 ];

  function encodePrimitive(o){
    switch (typeof o) {
      case 'boolean':      return o ? TRUE : FALSE;
      case 'undefined':    return UNDEFINED;
      case 'object':       return NULL;
      case 'string':       return ['ø', o];
      case 'number':
        switch (o) {
          case Infinity:   return INFINITY;
          case -Infinity:  return NEGINFINITY;
          case NaN:        return NAN;
          case 0:          return 1 / o === -Infinity ? NEGZERO : ZERO;
          default:         return o !== o ? NAN : ['ø', o];
        }
    }
  }

  function decodePrimitive(o){
    switch (o[1]) {
      case '_Δ': return undefined;
      case '_ƒ': return NaN;
      case '_Ω': return Infinity;
      case '_-Ω': return -Infinity;
      case '_π': return -0;
      default: return o[1];
    }
  }

  function unwrap(obj){
    if (!isObject(obj)) {
      return obj;
    } else if (obj[0] == 'ø') {
      return decodePrimitive(obj);
    } else if (obj[0] === bid) {
      if (obj[1] in mirrors) {
        return farIDs.get(mirrors[obj[1]]);
      } else {
        var proxy = new Mirror(obj);
        proxies.set(proxy, obj);
        farIDs.set(obj, proxy);
        mirrors[obj[1]] = obj;
        return proxy;
      }
    } else if (obj[0] === nid) {
      return items[obj[1]];
    } else {
      return obj;
    }
  }

  function wrap(obj){
    if (!isObject(obj)) {
      return encodePrimitive(obj);
    } else if (proxies.has(obj)) {
      return proxies.get(obj);
    } else {
      var id = nearIDs.get(obj);
      if (id === undefined) {
        nearIDs.set(obj, id = items.length);
        items.push(obj);
      }
      return [nid, id];
    }
  }

  var mirror = {
    type: function type(obj){
      return [typeof obj];
    },
    keys: function keys(obj){
      return Object.keys(obj);
    },
    enumerate: function enumerate(obj){
      var i=0, k=[];
      for (k[i++] in obj);
      return k;
    },
    props: function props(obj){
      return Object.getOwnPropertyNames(obj);
    },
    get: function get(obj, key){
      return wrap(obj[key]);
    },
    proto: function proto(obj){
      return wrap(obj.__proto__);
    },
    has: function has(obj, key){
      return wrap(key in obj);
    },
    hasOwn: function hasOwn(obj, key){
      return wrap(_hasOwn.call(obj, key));
    },
    delete: function delete_(obj, key){
      delete obj[key];
      return TRUE;
    },
    define: function define(obj, key, desc){
      if (_hasOwn.call(desc, 'value')) {
        desc.value = unwrap(desc.value);
      } else {
        desc.get = unwrap(desc.get);
        desc.set = unwrap(desc.set);
      }
      Object.defineProperty(obj, key, desc);
      return TRUE;
    },
    describe: function describe(obj, key){
      var desc = Object.getOwnPropertyDescriptor(obj, key);
      if (desc) {
        desc.configurable = true;
        if (_hasOwn.call(desc, 'value')) {
          if (desc.value === undefined) desc.value = obj[key];
          desc.value = wrap(desc.value);
        } else {
          desc.get = wrap(desc.get);
          desc.set = wrap(desc.set);
        }
        return desc;
      } else if (desc === undefined && _hasOwn.call(obj, key)) {
        return { configurable: true,
                 enumerable: true,
                 writable: true,
                 value: wrap(obj[key]) };
      } else {
        return UNDEFINED;
      }
    },
    construct: function construct(obj, args){
      try {
        return wrap(new (_bind.apply(obj, [null].concat(args.map(unwrap)))));
      } catch (e) {
        return wrap(e);
      }
    },
  };

  if (win) {
    mirror.apply = function apply(obj, receiver, args){
      try {
        return wrap(_apply.call(obj, unwrap(receiver), args.map(unwrap)));
      } catch (e) {
        return wrap(e);
      }
    };
    mirror.set = function set(obj, key, value){
      obj[key] = unwrap(value);
      return TRUE;
    };
  } else {
    var proxyForProxy = function proxyForProxy(fn){
      return function(){ return _apply.call(fn, this, arguments) };
    }
    mirror.apply = function apply(obj, receiver, args){
      try {
        // workaround for bug where proxy functions are not valid DOM event handlers
        args = args.map(unwrap);
        if (obj.name === 'addEventListener' && typeof args[1] === 'function') {
          args[1] = proxyForProxy(args[1]);
        }
        return wrap(_apply.call(obj, unwrap(receiver), args));
      } catch (e) {
        return wrap(e);
      }
    };
    mirror.set = function set(obj, key, value){
      value = unwrap(value);
      obj[key] = value;
      if (obj[key] === null && typeof value === 'function') {
        // workaround for bug where proxy functions are not valid DOM event handlers
        obj[key] = proxyForProxy(value);
      }
      return TRUE;
    };
  }

  function Mirror(obj){
    var self = this;
    var type = pipe.send('Δtype', obj)[0];
    this.id = obj;
    this.id2 = obj.concat(null);
    this.id3 = obj.concat(null, null);
    if (type === 'function') {
      return Proxy.createFunction(this,
        function(){ return self.apply(this, _slice.call(arguments)) },
        function(){ return self.construct(_slice.call(arguments)) }
      );
    } else {
      return Proxy.create(this, unwrap(pipe.send('Δproto', this.id)));
    }
  }

  Mirror.prototype = {
    keys: function keys(){
      return pipe.send('Δkeys', this.id);
    },
    enumerate: function enumerate(){
      return pipe.send('Δenumerate', this.id);
    },
    getOwnPropertyNames: function getOwnPropertyNames(){
      return pipe.send('Δprops', this.id);
    },
    get: function get(rcvr, key){
      this.id2[2] = key;
      return unwrap(pipe.send('Δget', this.id2));
    },
    set: function set(rcvr, key, value){
      this.id3[2] = key;
      this.id3[3] = wrap(value);
      pipe.send('Δset', this.id3);
      return true;
    },
    getOwnPropertyDescriptor: function getOwnPropertyDescriptor(key){
      this.id2[2] = key;
      var desc = pipe.send('Δdescribe', this.id2);
      if (desc) {
        desc.configurable = true;
        if (_hasOwn.call(desc, 'value')) {
          desc.value = unwrap(desc.value);
        } else {
          desc.get = unwrap(desc.get);
          desc.set = unwrap(desc.set);
        }
      }
      return desc;
    },
    has: function has(key){
      this.id2[2] = key;
      return pipe.send('Δhas', this.id2);
    },
    hasOwn: function hasOwn(key){
      this.id2[2] = key;
      return pipe.send('ΔhasOwn', this.id2);
    },
    delete: function delete_(key){
      this.id2[2] = key;
      pipe.send('Δdelete', this.id2);
      return true;
    },
    defineProperty: function defineProperty(key, desc){
      this.id3[2] = key;
      this.id3[3] = desc = wrap(desc);
      if (_hasOwn.call(desc, 'value')) {
        desc.value = wrap(desc.value);
      } else {
        desc.get = wrap(desc.get);
        desc.set = wrap(desc.set);
      }
      pipe.send('Δdefine', this.id3);
    },
    apply: function apply(receiver, args){
      this.id3[2] = wrap(receiver);
      this.id3[3] = args.map(wrap);
      return unwrap(pipe.send('Δapply', this.id3));
    },
    construct: function construct(args){
      this.id2[2] = args.map(wrap);
      return unwrap(pipe.send('Δconstruct', this.id2));
    }
  };

  var pipe = win || appjs;

  Object.keys(mirror).forEach(function(key){
    pipe.on('Δ'+key, function(val, res){
      res.result = mirror[key](unwrap(val), val[2], val[3]);
    });
  });

  if (!arguments.length) {
    var items = [window],
        nid = 'bid',
        bid = 'nid';
    nearIDs.set(window, 0);
    window.node = unwrap([bid, 0]);
  } else {
    var items = [global],
        nid = 'nid',
        bid = 'bid';
    nearIDs.set(global, 0);
    win.window = unwrap([bid, 0]);
  }
}
<|endoftext|>


<commit_before>// [VexFlow](http://vexflow.com) - Copyright (c) Mohit Muthanna 2010.
// @author Mohit Cheppudira
//
// ## Description
//
// This file implements a high level API around VexFlow. It will eventually
// become the canonical way to use VexFlow.
//
// *This API is currently DRAFT*

import { Vex } from './vex';
import { Accidental } from './accidental';
import { Formatter } from './formatter';
import { ModifierContext } from './modifiercontext';
import { Renderer } from './renderer';
import { Stave } from './stave';
import { StaveNote } from './stavenote';
import { StaveConnector } from './staveconnector';
import { System } from './system';
import { TickContext } from './tickcontext';
import { Tuplet } from './tuplet';
import { Voice } from './voice';
import { Beam } from './beam';
import { GraceNote } from './gracenote';
import { GraceNoteGroup } from './gracenotegroup';
import { EasyScore } from './easyscore';

// To enable logging for this class. Set `Vex.Flow.Factory.DEBUG` to `true`.
function L(...args) { if (Factory.DEBUG) Vex.L('Vex.Flow.Factory', args); }

// Exceptions for this class.
function X(message, data) {
  this.name = 'FactoryException';
  this.message = message;
  this.data = data;
  L(this.name + ':', message, data);
}

function setDefaults(params = {}, defaults) {
  const default_options = defaults.options;
  params = Object.assign(defaults, params);
  params.options = Object.assign(default_options, params.options);
  return params;
}

export class Factory {
  constructor(options) {
    L('New factory: ', options);
    const defaults = {
      stave: {
        space: 10,
      },
      renderer: {
        context: null,
        selector: '',
        backend: Renderer.Backends.SVG,
        width: 500,
        height: 200,
        background: '#FFF',
      },
      font: {
        face: 'Arial',
        point: 10,
        style: '',
      },
    };

    this.options = defaults;
    this.setOptions(options);
    if (this.options.renderer.selector !== null || this.options.renderer.context) {
      this.initRenderer();
    }

    this.renderQ = [];
    this.systems = [];
    this.staves = [];
    this.voices = [];
    this.stave = null; // current stave
  }

  getOptions() { return this.options; }
  setOptions(options) {
    for (const key of ['stave', 'renderer', 'font']) {
      Object.assign(this.options[key], options[key]);
    }
  }

  initRenderer() {
    const { selector, backend, width, height, background } = this.options.renderer;
    if (selector === '') {
      throw new X('HTML DOM element not set in Factory');
    }

    this.context = Renderer.buildContext(selector, backend, width, height, background);
  }

  getContext() { return this.context; }
  setContext(context) { this.context = context; return this; }
  getStave() { return this.stave; }

  // Returns pixels from current stave spacing.
  space(spacing) { return this.options.stave.space * spacing; }

  Stave(params) {
    params = setDefaults(params, {
      x: 0,
      y: 0,
      width: this.options.renderer.width - this.space(1),
      options: {
        spacing_between_lines_px: this.options.stave.space,
      },
    });

    const stave = new Stave(params.x, params.y, params.width, params.options);
    this.staves.push(stave);
    stave.setContext(this.context);
    this.stave = stave;
    return stave;
  }

  StaveNote(noteStruct) {
    const note = new StaveNote(noteStruct);
    if (this.stave) note.setStave(this.stave);
    note.setContext(this.context);
    this.renderQ.push(note);
    return note;
  }

  GraceNote(noteStruct) {
    const note = new GraceNote(noteStruct);
    if (this.stave) note.setStave(this.stave);
    note.setContext(this.context);
    return note;
  }

  GraceNoteGroup(params) {
    const group = new GraceNoteGroup(params.notes, params.slur);
    group.setContext(this.context);
    return group;
  }

  Accidental(params) {
    params = setDefaults(params, {
      type: null,
      options: {},
    });

    const acc = new Accidental(params.type);
    acc.setContext(this.context);
    return acc;
  }

  TickContext() {
    return new TickContext().setContext(this.context);
  }

  ModifierContext() {
    return new ModifierContext();
  }

  Voice(params) {
    params = setDefaults(params, {
      time: '4/4',
      options: {},
    });
    const voice = new Voice(params.time);
    this.voices.push(voice);
    return voice;
  }

  StaveConnector(params) {
    params = setDefaults(params, {
      top_stave: null,
      bottom_stave: null,
      options: {},
    });
    const connector = new StaveConnector(params.top_stave, params.bottom_stave);
    connector.setContext(this.context);
    this.renderQ.push(connector);
    return connector;
  }

  Formatter() {
    return new Formatter();
  }

  Tuplet(params) {
    params = setDefaults(params, {
      notes: [],
      options: {},
    });

    const tuplet = new Tuplet(params.notes, params.options).setContext(this.context);
    this.renderQ.push(tuplet);
    return tuplet;
  }

  Beam(params) {
    params = setDefaults(params, {
      notes: [],
      options: {
        autoStem: false,
      },
    });

    const beam = new Beam(params.notes, params.options.autoStem).setContext(this.context);
    this.renderQ.push(beam);
    return beam;
  }

  System(params = {}) {
    params.factory = this;
    const system = new System(params).setContext(this.context);
    this.systems.push(system);
    return system;
  }

  EasyScore(params = {}) {
    params.factory = this;
    return new EasyScore(params);
  }

  draw() {
    this.systems.forEach(i => i.setContext(this.context).format());
    this.staves.forEach(i => i.setContext(this.context).draw());
    this.voices.forEach(i => i.setContext(this.context).draw());
    this.renderQ.forEach(i => {
      if (!i.isRendered()) i.setContext(this.context).draw();
    });
    this.systems.forEach(i => i.setContext(this.context).draw());
  }
}
<commit_msg>Reset `Factory` after calling `draw` so it can be reused.<commit_after>// [VexFlow](http://vexflow.com) - Copyright (c) Mohit Muthanna 2010.
// @author Mohit Cheppudira
//
// ## Description
//
// This file implements a high level API around VexFlow. It will eventually
// become the canonical way to use VexFlow.
//
// *This API is currently DRAFT*

import { Vex } from './vex';
import { Accidental } from './accidental';
import { Formatter } from './formatter';
import { ModifierContext } from './modifiercontext';
import { Renderer } from './renderer';
import { Stave } from './stave';
import { StaveNote } from './stavenote';
import { StaveConnector } from './staveconnector';
import { System } from './system';
import { TickContext } from './tickcontext';
import { Tuplet } from './tuplet';
import { Voice } from './voice';
import { Beam } from './beam';
import { GraceNote } from './gracenote';
import { GraceNoteGroup } from './gracenotegroup';
import { EasyScore } from './easyscore';

// To enable logging for this class. Set `Vex.Flow.Factory.DEBUG` to `true`.
function L(...args) { if (Factory.DEBUG) Vex.L('Vex.Flow.Factory', args); }

// Exceptions for this class.
function X(message, data) {
  this.name = 'FactoryException';
  this.message = message;
  this.data = data;
  L(this.name + ':', message, data);
}

function setDefaults(params = {}, defaults) {
  const default_options = defaults.options;
  params = Object.assign(defaults, params);
  params.options = Object.assign(default_options, params.options);
  return params;
}

export class Factory {
  constructor(options) {
    L('New factory: ', options);
    const defaults = {
      stave: {
        space: 10,
      },
      renderer: {
        context: null,
        selector: '',
        backend: Renderer.Backends.SVG,
        width: 500,
        height: 200,
        background: '#FFF',
      },
      font: {
        face: 'Arial',
        point: 10,
        style: '',
      },
    };

    this.options = defaults;
    this.setOptions(options);
    if (this.options.renderer.selector !== null || this.options.renderer.context) {
      this.initRenderer();
    }

    this.reset();
  }

  reset() {
    this.renderQ = [];
    this.systems = [];
    this.staves = [];
    this.voices = [];
    this.stave = null; // current stave
  }

  getOptions() { return this.options; }
  setOptions(options) {
    for (const key of ['stave', 'renderer', 'font']) {
      Object.assign(this.options[key], options[key]);
    }
  }

  initRenderer() {
    const { selector, backend, width, height, background } = this.options.renderer;
    if (selector === '') {
      throw new X('HTML DOM element not set in Factory');
    }

    this.context = Renderer.buildContext(selector, backend, width, height, background);
  }

  getContext() { return this.context; }
  setContext(context) { this.context = context; return this; }
  getStave() { return this.stave; }

  // Returns pixels from current stave spacing.
  space(spacing) { return this.options.stave.space * spacing; }

  Stave(params) {
    params = setDefaults(params, {
      x: 0,
      y: 0,
      width: this.options.renderer.width - this.space(1),
      options: {
        spacing_between_lines_px: this.options.stave.space,
      },
    });

    const stave = new Stave(params.x, params.y, params.width, params.options);
    this.staves.push(stave);
    stave.setContext(this.context);
    this.stave = stave;
    return stave;
  }

  StaveNote(noteStruct) {
    const note = new StaveNote(noteStruct);
    if (this.stave) note.setStave(this.stave);
    note.setContext(this.context);
    this.renderQ.push(note);
    return note;
  }

  GraceNote(noteStruct) {
    const note = new GraceNote(noteStruct);
    if (this.stave) note.setStave(this.stave);
    note.setContext(this.context);
    return note;
  }

  GraceNoteGroup(params) {
    const group = new GraceNoteGroup(params.notes, params.slur);
    group.setContext(this.context);
    return group;
  }

  Accidental(params) {
    params = setDefaults(params, {
      type: null,
      options: {},
    });

    const acc = new Accidental(params.type);
    acc.setContext(this.context);
    return acc;
  }

  TickContext() {
    return new TickContext().setContext(this.context);
  }

  ModifierContext() {
    return new ModifierContext();
  }

  Voice(params) {
    params = setDefaults(params, {
      time: '4/4',
      options: {},
    });
    const voice = new Voice(params.time);
    this.voices.push(voice);
    return voice;
  }

  StaveConnector(params) {
    params = setDefaults(params, {
      top_stave: null,
      bottom_stave: null,
      options: {},
    });
    const connector = new StaveConnector(params.top_stave, params.bottom_stave);
    connector.setContext(this.context);
    this.renderQ.push(connector);
    return connector;
  }

  Formatter() {
    return new Formatter();
  }

  Tuplet(params) {
    params = setDefaults(params, {
      notes: [],
      options: {},
    });

    const tuplet = new Tuplet(params.notes, params.options).setContext(this.context);
    this.renderQ.push(tuplet);
    return tuplet;
  }

  Beam(params) {
    params = setDefaults(params, {
      notes: [],
      options: {
        autoStem: false,
      },
    });

    const beam = new Beam(params.notes, params.options.autoStem).setContext(this.context);
    this.renderQ.push(beam);
    return beam;
  }

  System(params = {}) {
    params.factory = this;
    const system = new System(params).setContext(this.context);
    this.systems.push(system);
    return system;
  }

  EasyScore(params = {}) {
    params.factory = this;
    return new EasyScore(params);
  }

  draw() {
    this.systems.forEach(i => i.setContext(this.context).format());
    this.staves.forEach(i => i.setContext(this.context).draw());
    this.voices.forEach(i => i.setContext(this.context).draw());
    this.renderQ.forEach(i => {
      if (!i.isRendered()) i.setContext(this.context).draw();
    });
    this.systems.forEach(i => i.setContext(this.context).draw());
    this.reset();
  }
}
<|endoftext|>


<commit_before>Object.defineProperty(Array.prototype, "chunk", {value:function(chunkSize) {
  var array = this;
  return [].concat.apply([], array.map(function(elem, i) {
    return i % chunkSize ? [] : [array.slice(i, i + chunkSize)];
  }));
}});

var getGPA = function() {
  var dataTable = Array.prototype.slice.call(document.getElementsByClassName("linkDescList grid"));
  var dataArray = [];
  $(dataTable).each(function() {
    var arrayOfThisRow = [];
    var tableData = $(this).find("td");
    if (tableData.length > 0) {
      tableData.each(function() {
        arrayOfThisRow.push($(this).text());
      });
      dataArray.push(arrayOfThisRow);
    }
  });

  dataArray = dataArray[0].chunk(16);
  console.log(dataArray);
  console.log("Number of rows: " + dataArray.length);
  var numclasses = 0;
  var gpa2 = 0;
  for (var i = 0; !isNaN(parseInt(dataArray[i][12][0])); i++, numclasses++) {}

  var dictionary = {7:4.3, 6:4, 5:3.3, 4:2.3, 3:1.3, 2:0, 1:0};
  console.log("Number of classes: " + numclasses);
  for (var gpa = 0, i = 0, current = 0; i < numclasses; i++) {
    current = parseInt(dataArray[i][12][0]);
    gpa2 += dictionary[current];
    if ((dataArray[i][11].substring(0, 2) == "IB" || dataArray[i][11].substring(0, 2) == "AP") && dataArray[i][11].substring(0, 15) != "IB Math Studies") {
      gpa2 += 0.5;
    }
    gpa += current;
  }

  return [gpa / numclasses, gpa2 / numclasses];
};

var main = function() {
  var change = document.getElementsByTagName("tbody")[2];
  var GPAs = getGPA();
  var gpa_display = "
(S1) GPA: " + GPAs[0].toFixed(3) + "
 Traditional GPA: " + GPAs[1].toFixed(3) + "
";
  change.innerHTML = gpa_display;
};
main();<commit_msg>Deprecate change.innerHTML<commit_after>Object.defineProperty(Array.prototype, "chunk", {value:function(chunkSize) {
  var array = this;
  return [].concat.apply([], array.map(function(elem, i) {
    return i % chunkSize ? [] : [array.slice(i, i + chunkSize)];
  }));
}});

var getGPA = function() {
  var dataTable = Array.prototype.slice.call(document.getElementsByClassName("linkDescList grid"));
  var dataArray = [];
  $(dataTable).each(function() {
    var arrayOfThisRow = [];
    var tableData = $(this).find("td");
    if (tableData.length > 0) {
      tableData.each(function() {
        arrayOfThisRow.push($(this).text());
      });
      dataArray.push(arrayOfThisRow);
    }
  });

  dataArray = dataArray[0].chunk(16);
  console.log(dataArray);
  console.log("Number of rows: " + dataArray.length);
  var numclasses = 0;
  var gpa2 = 0;
  for (var i = 0; !isNaN(parseInt(dataArray[i][12][0])); i++, numclasses++) {}

  var dictionary = {7:4.3, 6:4, 5:3.3, 4:2.3, 3:1.3, 2:0, 1:0};
  console.log("Number of classes: " + numclasses);
  for (var gpa = 0, i = 0, current = 0; i < numclasses; i++) {
    current = parseInt(dataArray[i][12][0]);
    gpa2 += dictionary[current];
    if ((dataArray[i][11].substring(0, 2) == "IB" || dataArray[i][11].substring(0, 2) == "AP") && dataArray[i][11].substring(0, 15) != "IB Math Studies") {
      gpa2 += 0.5;
    }
    gpa += current;
  }

  return [gpa / numclasses, gpa2 / numclasses];
};

var main = function() {
  var change = document.getElementsByTagName("tbody")[2];
  var GPAs = getGPA();
  var gpa_display = "(S1) GPA: " + GPAs[0].toFixed(3);
  var gpa_display2 = "Traditional GPA: " + GPAs[1].toFixed(3);

  var disp = document.createElement("P");                       // Create a
 element

  disp.style.fontSize = "20px";
  disp.style.fontFamily = "Helvetica Neue";
  disp.style.textAlign = "center";
  disp.style.marginBottom =  "-5px";

  disp.appendChild(document.createTextNode(gpa_display));
  disp.appendChild(document.createElement("br"));
  disp.appendChild(document.createTextNode(gpa_display2));

  document.getElementsByTagName("tbody")[2].appendChild(disp);

};
main();<|endoftext|>


<commit_before>define([
    'fossil/core',
    'fossil/mixins/events',
    'underscore',
    'backbone'
], function (Fossil, Events, _, Backbone) {

    Fossil.Factories = {};

    var Factory = Fossil.Factory = function (options) {
        this.options = _.extend({}, this.options, options || {});
        this.registerEvents();
        this.initialize.apply(this, arguments);
    };

    _.extend(Factory.prototype, Fossil.Mixins.Events, {
        // default options
        options: {
            // should the factory be exposed  to module context ?
            // an exposed factory will be available under module.factories[factoryid]
            exposeToModule: false,
            // should there be a shortlink on module
            // this would make factory available under module[factoryid]
            // to avoid conflic this MUST be set by user.
            linkToApplcation: false
        },
        // A hook to initialize factory,
        // after application and modules are initialized.
        initialize: function (options) {
        },

        // activate Factory for application
        activateApplication: function (application, id) {
            var factory = this;
            this.prefixEvent = _.bind(prefixEvent, this, id);

            // create pubSub
            this.application = application.createPubSub(this, 'applicationEvents');
            // activate application
            this._doActivateApplication(application);
            // activate all modules
            _.each(application.getModule(), function (module) {
                factory.activateModule.call(factory, module, application, id);
            });
            // register on new module connection
            this.listenTo(application, 'module:connect', _.bind(this.activateModuleListener, this, id));
            // tell the world we're ready
            application.trigger(this.prefixEvent('ready'), this);
        },
        // unplug for application
        suspendApplication: function (application, id) {
            var factory = this;
            // suspend for every application modules
            _.each(application.getModule(), function (module) {
                factory.suspendModule.call(factory, module, application, id);
            });
            // remove event handler
            this.stopListening();
            // remove pubsub reference
            this.application = null;
            // finally suspend for application
            this._doSuspendApplication(application);
        },

        activateModule: function (module, application, id) {
            if (!module.factories) {
                // module isn't booted yet.
                return ;
            }
            if (this.options.exposeToModule) {
                module.factories[id] = this;
            }
            if (this.options.linkToApplcation) {
                module[id] = this;
            }
            this._doActivateModule.apply(this, arguments);
            module.trigger(this.prefixEvent('ready'), this);
        },
        suspendModule: function (module, application, id) {
            if (this.options.exposeToModule) {
                module.factories[id] = null;
            }
            this._doSuspendModule.apply(this, arguments);
        },

        activateModuleListener: function (id, module, path, application) {
            this.activateModule(module, application, id);
        },

        // activate factory on application.
        // this method has to be overriden with the factory logic.
        _doActivateApplication: function (application) {
        },
        // activate factory on module.
        // this method has to be overriden with the factory logic.
        _doActivateModule: function (module, application) {
        },
        // suspend factory on application.
        // this method has to be overriden with the factory logic.
        _doSuspendApplication: function (application) {
        },
        // suspend factory on module.
        // this method has to be overriden with the factory logic.
        _doSuspendModule: function (module, application) {
        }
    });

    function prefixEvent (id, event) {
        return ['factory', id, event].join(':');
    }

    Factory.extend = Backbone.Model.extend;

    return Factory;
});
<commit_msg>Typo fix in factory options.<commit_after>define([
    'fossil/core',
    'fossil/mixins/events',
    'underscore',
    'backbone'
], function (Fossil, Events, _, Backbone) {

    Fossil.Factories = {};

    var Factory = Fossil.Factory = function (options) {
        this.options = _.extend({}, this.options, options || {});
        this.registerEvents();
        this.initialize.apply(this, arguments);
    };

    _.extend(Factory.prototype, Fossil.Mixins.Events, {
        // default options
        options: {
            // should the factory be exposed  to module context ?
            // an exposed factory will be available under module.factories[factoryid]
            exposeToModule: false,
            // should there be a shortlink on module
            // this would make factory available under module[factoryid]
            // to avoid conflic this MUST be set by user.
            linkToApplication: false
        },
        // A hook to initialize factory,
        // after application and modules are initialized.
        initialize: function (options) {
        },

        // activate Factory for application
        activateApplication: function (application, id) {
            var factory = this;
            this.prefixEvent = _.bind(prefixEvent, this, id);

            // create pubSub
            this.application = application.createPubSub(this, 'applicationEvents');
            // activate application
            this._doActivateApplication(application);
            // activate all modules
            _.each(application.getModule(), function (module) {
                factory.activateModule.call(factory, module, application, id);
            });
            // register on new module connection
            this.listenTo(application, 'module:connect', _.bind(this.activateModuleListener, this, id));
            // tell the world we're ready
            application.trigger(this.prefixEvent('ready'), this);
        },
        // unplug for application
        suspendApplication: function (application, id) {
            var factory = this;
            // suspend for every application modules
            _.each(application.getModule(), function (module) {
                factory.suspendModule.call(factory, module, application, id);
            });
            // remove event handler
            this.stopListening();
            // remove pubsub reference
            this.application = null;
            // finally suspend for application
            this._doSuspendApplication(application);
        },

        activateModule: function (module, application, id) {
            if (!module.factories) {
                // module isn't booted yet.
                return ;
            }
            if (this.options.exposeToModule) {
                module.factories[id] = this;
            }
            if (this.options.linkToApplication) {
                module[id] = this;
            }
            this._doActivateModule.apply(this, arguments);
            module.trigger(this.prefixEvent('ready'), this);
        },
        suspendModule: function (module, application, id) {
            if (this.options.exposeToModule) {
                module.factories[id] = null;
            }
            this._doSuspendModule.apply(this, arguments);
        },

        activateModuleListener: function (id, module, path, application) {
            this.activateModule(module, application, id);
        },

        // activate factory on application.
        // this method has to be overriden with the factory logic.
        _doActivateApplication: function (application) {
        },
        // activate factory on module.
        // this method has to be overriden with the factory logic.
        _doActivateModule: function (module, application) {
        },
        // suspend factory on application.
        // this method has to be overriden with the factory logic.
        _doSuspendApplication: function (application) {
        },
        // suspend factory on module.
        // this method has to be overriden with the factory logic.
        _doSuspendModule: function (module, application) {
        }
    });

    function prefixEvent (id, event) {
        return ['factory', id, event].join(':');
    }

    Factory.extend = Backbone.Model.extend;

    return Factory;
});
<|endoftext|>


<commit_before>const EventEmitter = require('events'),
  blessed = require('blessed'),
  timestamp = require('./util/timestamp'),
  Discord = require('discord.js');

class GUI extends EventEmitter {
  constructor(screen) {
    super();
    this.history = []; // For storing past messages
    this.historyAt = 1; // For indexing history
    this.screen = screen;
    this.chatbox = blessed.box({
      label: 'Retrocord Light',
      left: '0.5%',
      width: '86%',
      height: '96%-1',
      border: {
        type: 'line'
      },
      style: {
        border: {
          fg: 'white'
        }
      }
    });
    this.infobox = blessed.textbox({
      label: 'Info',
      left: '86%',
      width: '14%',
      height: '96%-1',
      border: {
        type: "line"
      },
      style: {
        border: {
          fg: "white"
        }
      }
    });
    this.consolebox = blessed.log({
      parent: this.chatbox,
      tags: true,
      scrollable: true,
      label: '',
      alwaysScroll: true,
      scrollbar: {
        ch: '',
        inverse: true,
      },
      mouse: true
    });
    this.inputbox = blessed.textbox({
      bottom: 0,
      width: '100%',
      height: 3,
      inputOnFocus: true,
      border: {
        type: 'line'
      },
      style: {
        border: {
          fg: 'grey'
        }
      }
    });
    this.infolog = blessed.log({
      parent: this.infobox,
      tags: true,
      scrollable: true,
      label: '',
      alwaysScroll: true,
      scrollbar: {
        ch: '',
        inverse: true,
      },
      mouse: true
    });
    this.awaitingResponse = false;
  }
  renderInfo() {
    if (global.ctx && ctx.discord && ctx.discord.user) {
      const uname = ctx.discord.user.tag,
        friendCount = ctx.discord.user.friends.array().length,
        friends = ctx.discord.user.friends,
        isInDm = ctx.current.channel ? (ctx.current.channel instanceof Discord.DMChannel) : false,
        listSize = friendCount > 24 ? 25 : friendCount;
      let txt = `
      {yellow-fg}{bold}${uname}{/bold}{/yellow-fg}
      `;
      if (isInDm) {
        txt += `\n{center}DM:\n{white-fg}{bold}${ctx.current.channel.recipient.username}{/white-fg}{/bold}{/center}`;
        if (ctx.dmIsTyping) {
          txt += `\n{center}{underline}{white-fg}is typing...{/white-fg}{/underline}{/center}`;
        }
        txt += `\n{underline}Status: {bold}${ctx.current.channel.recipient.presence.status}{/underline}{/center}\n`;
      }
      if (!ctx.hideFriends) {
        txt += "\nFriends:";
        var fs = friends.array();
        var chns = ctx.discord.channels.filterArray(c => c.type === 'dm');
        // /*
        chns.sort((a, b) => {
          if (!a.recipient.lastMessage || !b.recipient.lastMessage) return -1;
          return (b.recipient.lastMessage.createdTimestamp + a.recipient.lastMessage.createdTimestamp);
        });
        // */
        for (var i = 0; i < listSize; ++i) {
          txt += `\n{white-fg}{bold}-{/bold}{/white-fg} {yellow-fg}${chns[i].recipient.tag}{/yellow-fg}`
        }
      }
      this.infolog.setContent(txt);
    } else {
      this.infolog.setContent('Not logged in :(.');
    }
  }
  init() {
    const me = this;
    this.inputbox.key('enter', () => {
      if (this.awaitingResponse) this.emit('internalInput', this.inputbox.getValue());
      else this.emit('input', this.inputbox.getValue());
        this.history.push(this.inputbox.getValue());
      this.inputbox.clearValue();
      this.inputbox.focus();
      this.screen.render();
        this.historyAt = 1; // Reset history index after message sent
    });
    this.inputbox.key('up', () => {
        const back = me.history[me.history.length - me.historyAt];
        me.historyAt++;
        if (back) {
            me.inputbox.setValue(back);
        }
    });
    this.inputbox.key('down', () => {
        if (me.historyAt < 1) {
            return; // History index too small
        }
        const forward = me.history[me.history.length - me.historyAt];
        if (forward) {
            me.inputbox.setValue(forward);
        }
    });
    this.screen.append(this.chatbox);
    this.screen.append(this.inputbox);
    this.screen.append(this.infobox);
    this.screen.render();
    this.inputbox.focus();
    me.renderInfo.call(me);
    setInterval(() => {
      me.renderInfo.call(me);
    }, 750);
  }
  put(text) {
    this.consolebox.log(text);
  }
  puti(txt) {
    this.infolog.log(txt);
  }
  putMessages(messages) {
    const me = this;
    messages.forEach(m => {
      const ts = timestamp(m.createdAt),
        arrow = (m.author.id == ctx.discord.user.id) ? `{green-fg}{bold}<{/bold}{/green-fg}` : `{red-fg}{bold}>{/bold}{/red-fg}`,
        txt = `${arrow} {yellow-fg}{bold}${ts}{/bold}{/yellow-fg} {white-fg}{bold}${m.author.username}{/bold}{/white-fg} ${m.content}`;
      me.put(txt);
    });
  }
  putMessage(message, opt) {
    return this.putMessages([message], opt);
  }
  putTypingStart(channel, user) {
    // athis.put(`{blue-fg}{bold}↷{/bold}{/blue-fg} {white-fg}{bold}${user.username}{/bold}{/white-fg} has {green-fg}started{/green-fg} typing.`);
  }
  putTypingStop(channel, user) {
    // this.put(`{blue-fg}{bold}↶{/bold}{/blue-fg} {white-fg}{bold}${user.username}{/bold}{/white-fg} has {red-fg}stopped{/red-fg} typing.`);
  }
  awaitResponse(text) {
    this.awaitingResponse = true;
    return new Promise((resolve) => {
      this.put(text);
      this.once('internalInput', (input) => {
        this.awaitingResponse = false;
        resolve(input);
      });
    });
  }
}

const screen = blessed.screen({
  smartCSR: true,
  title: 'retrocord',
  fullUnicode: true,
});

const gui = new GUI(screen);

module.exports = gui;
<commit_msg>Fix centering for status<commit_after>const EventEmitter = require('events'),
  blessed = require('blessed'),
  timestamp = require('./util/timestamp'),
  Discord = require('discord.js');

class GUI extends EventEmitter {
  constructor(screen) {
    super();
    this.history = []; // For storing past messages
    this.historyAt = 1; // For indexing history
    this.screen = screen;
    this.chatbox = blessed.box({
      label: 'Retrocord Light',
      left: '0.5%',
      width: '86%',
      height: '96%-1',
      border: {
        type: 'line'
      },
      style: {
        border: {
          fg: 'white'
        }
      }
    });
    this.infobox = blessed.textbox({
      label: 'Info',
      left: '86%',
      width: '14%',
      height: '96%-1',
      border: {
        type: "line"
      },
      style: {
        border: {
          fg: "white"
        }
      }
    });
    this.consolebox = blessed.log({
      parent: this.chatbox,
      tags: true,
      scrollable: true,
      label: '',
      alwaysScroll: true,
      scrollbar: {
        ch: '',
        inverse: true,
      },
      mouse: true
    });
    this.inputbox = blessed.textbox({
      bottom: 0,
      width: '100%',
      height: 3,
      inputOnFocus: true,
      border: {
        type: 'line'
      },
      style: {
        border: {
          fg: 'grey'
        }
      }
    });
    this.infolog = blessed.log({
      parent: this.infobox,
      tags: true,
      scrollable: true,
      label: '',
      alwaysScroll: true,
      scrollbar: {
        ch: '',
        inverse: true,
      },
      mouse: true
    });
    this.awaitingResponse = false;
  }
  renderInfo() {
    if (global.ctx && ctx.discord && ctx.discord.user) {
      const uname = ctx.discord.user.tag,
        friendCount = ctx.discord.user.friends.array().length,
        friends = ctx.discord.user.friends,
        isInDm = ctx.current.channel ? (ctx.current.channel instanceof Discord.DMChannel) : false,
        listSize = friendCount > 24 ? 25 : friendCount;
      let txt = `
      {yellow-fg}{bold}${uname}{/bold}{/yellow-fg}
      `;
      if (isInDm) {
        txt += `\n{center}DM:\n{white-fg}{bold}${ctx.current.channel.recipient.username}{/white-fg}{/bold}{/center}`;
        if (ctx.dmIsTyping) {
          txt += `\n{center}{underline}{white-fg}is typing...{/white-fg}{/underline}{/center}`;
        }
        txt += `\n{center{{underline}Status: {bold}${ctx.current.channel.recipient.presence.status}{/underline}{/center}\n`;
      }
      if (!ctx.hideFriends) {
        txt += "\nFriends:";
        var fs = friends.array();
        var chns = ctx.discord.channels.filterArray(c => c.type === 'dm');
        // /*
        chns.sort((a, b) => {
          if (!a.recipient.lastMessage || !b.recipient.lastMessage) return -1;
          return (b.recipient.lastMessage.createdTimestamp + a.recipient.lastMessage.createdTimestamp);
        });
        // */
        for (var i = 0; i < listSize; ++i) {
          txt += `\n{white-fg}{bold}-{/bold}{/white-fg} {yellow-fg}${chns[i].recipient.tag}{/yellow-fg}`
        }
      }
      this.infolog.setContent(txt);
    } else {
      this.infolog.setContent('Not logged in :(.');
    }
  }
  init() {
    const me = this;
    this.inputbox.key('enter', () => {
      if (this.awaitingResponse) this.emit('internalInput', this.inputbox.getValue());
      else this.emit('input', this.inputbox.getValue());
        this.history.push(this.inputbox.getValue());
      this.inputbox.clearValue();
      this.inputbox.focus();
      this.screen.render();
        this.historyAt = 1; // Reset history index after message sent
    });
    this.inputbox.key('up', () => {
        const back = me.history[me.history.length - me.historyAt];
        me.historyAt++;
        if (back) {
            me.inputbox.setValue(back);
        }
    });
    this.inputbox.key('down', () => {
        if (me.historyAt < 1) {
            return; // History index too small
        }
        const forward = me.history[me.history.length - me.historyAt];
        if (forward) {
            me.inputbox.setValue(forward);
        }
    });
    this.screen.append(this.chatbox);
    this.screen.append(this.inputbox);
    this.screen.append(this.infobox);
    this.screen.render();
    this.inputbox.focus();
    me.renderInfo.call(me);
    setInterval(() => {
      me.renderInfo.call(me);
    }, 750);
  }
  put(text) {
    this.consolebox.log(text);
  }
  puti(txt) {
    this.infolog.log(txt);
  }
  putMessages(messages) {
    const me = this;
    messages.forEach(m => {
      const ts = timestamp(m.createdAt),
        arrow = (m.author.id == ctx.discord.user.id) ? `{green-fg}{bold}<{/bold}{/green-fg}` : `{red-fg}{bold}>{/bold}{/red-fg}`,
        txt = `${arrow} {yellow-fg}{bold}${ts}{/bold}{/yellow-fg} {white-fg}{bold}${m.author.username}{/bold}{/white-fg} ${m.content}`;
      me.put(txt);
    });
  }
  putMessage(message, opt) {
    return this.putMessages([message], opt);
  }
  putTypingStart(channel, user) {
    // athis.put(`{blue-fg}{bold}↷{/bold}{/blue-fg} {white-fg}{bold}${user.username}{/bold}{/white-fg} has {green-fg}started{/green-fg} typing.`);
  }
  putTypingStop(channel, user) {
    // this.put(`{blue-fg}{bold}↶{/bold}{/blue-fg} {white-fg}{bold}${user.username}{/bold}{/white-fg} has {red-fg}stopped{/red-fg} typing.`);
  }
  awaitResponse(text) {
    this.awaitingResponse = true;
    return new Promise((resolve) => {
      this.put(text);
      this.once('internalInput', (input) => {
        this.awaitingResponse = false;
        resolve(input);
      });
    });
  }
}

const screen = blessed.screen({
  smartCSR: true,
  title: 'retrocord',
  fullUnicode: true,
});

const gui = new GUI(screen);

module.exports = gui;
<|endoftext|>


<commit_before>'use strict';

const specHelper = require('../../support/specHelper'),
      models = specHelper.models,
      Member = models.Member,
      sinon = specHelper.sinon,
      Q = specHelper.Q,
      logger = specHelper.logger,
      moment = require('moment');

var memberService = require('../../../services/memberService');

function fakeNewMember(residentialAddress, postalAddress, date) {
  return {
            firstName: 'Sherlock',
            lastName: 'Holmes',
            gender: 'horse radish',
            email: 'sherlock@holmes.co.uk',
            dateOfBirth: date,
            primaryPhoneNumber: '0396291146',
            secondaryPhoneNumber: '0394291146',
            residentialAddress: residentialAddress,
            postalAddress: postalAddress,
            membershipType: 'full'
        };
}

function getExpectedNewMember(residentialAddressId, postalAddressId, dateOfBirth) {
    let momentDate = moment(dateOfBirth, 'DD/MM/YYYY').toDate();

    let member = fakeNewMember(residentialAddressId, postalAddressId, momentDate);

    member.residentialAddressId = member.residentialAddress;
    delete(member.residentialAddress);

    member.postalAddressId = member.postalAddress;
    delete(member.postalAddress);

    member.verified = false;

    return member;
}

describe('memberService', () => {
    describe('createMember', () => {
        const residentialAddressId = 1;
        const postalAddressId = 2;
        const date = '22/12/1900';
        const residentialAddressFromDb = [
            {
                dataValues: {
                    id: residentialAddressId
                }
            }
        ];
        const postalAddressFromDb = [
            {
                dataValues: {
                    id: postalAddressId
                }
            }
        ];

        let createMemberStub, addressStub, loggerStub,
            residentialAddress, postalAddress,
            newMember, expectedNewMember, createdMemberFromDb,
            residentialAddressPromise, postalAddressPromise, memberPromise;

        beforeEach(() => {
            createMemberStub = sinon.stub(models.Member, 'create');
            addressStub = sinon.stub(models.Address, 'findOrCreate');
            loggerStub = sinon.stub(logger, 'logMemberSignUpEvent');

            residentialAddress = {
                address: '221b Baker St',
                suburb: 'London',
                country: 'England',
                state: 'VIC',
                postcode: '1234'
            };
            postalAddress = {
                address: '47 I dont want your spam St',
                suburb: 'Moriarty',
                country: 'USA',
                state: 'NM',
                postcode: '5678'
            };

            newMember = fakeNewMember(residentialAddress, postalAddress, date);
            expectedNewMember = getExpectedNewMember(residentialAddressId, postalAddressId, date);
            createdMemberFromDb = {
              dataValues : expectedNewMember
            };

            residentialAddressPromise = Q.defer();
            addressStub
                .withArgs({where: residentialAddress, defaults: residentialAddress})
                .returns(residentialAddressPromise.promise);

            postalAddressPromise = Q.defer();
            addressStub
                .withArgs({where: postalAddress, defaults: postalAddress})
                .returns(postalAddressPromise.promise);

            memberPromise = Q.defer();
            createMemberStub.returns(memberPromise.promise);
        });

        afterEach(() => {
            models.Member.create.restore();
            models.Address.findOrCreate.restore();
            loggerStub.restore();
        });

        it('creates a new member and address', (done) => {
            residentialAddressPromise.resolve(residentialAddressFromDb);
            postalAddressPromise.resolve(postalAddressFromDb);
            memberPromise.resolve(createdMemberFromDb);

            memberService.createMember(newMember)
                .finally((createdMember) => {
                    expect(createdMember.firstName).toEqual(expectedNewMember.firstName);
                    expect(Member.create).toHaveBeenCalledWith(jasmine.objectContaining(expectedNewMember));
                }).nodeify(done);
        });

        it('logs the member sign up event', (done) => {
            residentialAddressPromise.resolve(residentialAddressFromDb);
            postalAddressPromise.resolve(postalAddressFromDb);

            memberPromise.resolve(createdMemberFromDb);

            memberService.createMember(newMember)
                .finally(() => {
                    expect(logger.logMemberSignUpEvent).toHaveBeenCalledWith(expectedNewMember);
                }).nodeify(done);
        });

        describe('when postal and residential address are identical', () => {
            it('set them both to same value', (done) => {
                newMember = fakeNewMember(residentialAddress, residentialAddress, date);
                expectedNewMember = getExpectedNewMember(residentialAddressId, residentialAddressId, date);

                residentialAddressPromise.resolve(residentialAddressFromDb);
                postalAddressPromise.resolve(postalAddressFromDb);
                memberPromise.resolve(createdMemberFromDb);

                memberService.createMember(newMember)
                    .finally(() => {
                        expect(Member.create).toHaveBeenCalledWith(jasmine.objectContaining(expectedNewMember));
                    }).nodeify(done);
            });
        });

        describe('an error when saving the residential address to the database', () => {
            it('responds with a server error', (done) => {
                let errorMessage = 'Yes, we have no bananas.';
                residentialAddressPromise.reject(errorMessage);

                let promise = memberService.createMember(newMember);

                promise.finally(() => {
                    expect(models.Member.create).not.toHaveBeenCalled();
                    expect(promise.isRejected()).toBe(true);
                    done();
                });
            });
        });

        describe('an error when saving the postal address to the databse', () => {
            it('responds with a server error', (done) => {
                let errorMessage = 'Yes, we have no horses.';
                residentialAddressPromise.resolve(residentialAddressFromDb);
                postalAddressPromise.reject(errorMessage);

                let promise = memberService.createMember(newMember);

                promise.finally(() => {
                    expect(models.Member.create).not.toHaveBeenCalled();
                    expect(promise.isRejected()).toBe(true);
                    done();
                });
            });
        });

        describe('an error when saving the member to the database', () => {
            it('rejects the promise', (done) => {
                let errorMessage = 'Seriously, we still don\'t have any damn bananas.';
                residentialAddressPromise.resolve(residentialAddressFromDb);
                postalAddressPromise.resolve(postalAddressFromDb);
                memberPromise.reject(errorMessage);

                let promise = memberService.createMember(newMember);

                promise.finally(() => {
                    expect(promise.isRejected()).toBe(true);
                    done();
                });
            });
        });
    });
});
<commit_msg>Adding a validation to the create new member test to make sure it is returning the created member, take 2<commit_after>'use strict';

const specHelper = require('../../support/specHelper'),
      models = specHelper.models,
      Member = models.Member,
      sinon = specHelper.sinon,
      Q = specHelper.Q,
      logger = specHelper.logger,
      moment = require('moment');

var memberService = require('../../../services/memberService');

function fakeNewMember(residentialAddress, postalAddress, date) {
  return {
            firstName: 'Sherlock',
            lastName: 'Holmes',
            gender: 'horse radish',
            email: 'sherlock@holmes.co.uk',
            dateOfBirth: date,
            primaryPhoneNumber: '0396291146',
            secondaryPhoneNumber: '0394291146',
            residentialAddress: residentialAddress,
            postalAddress: postalAddress,
            membershipType: 'full'
        };
}

function getExpectedNewMember(residentialAddressId, postalAddressId, dateOfBirth) {
    let momentDate = moment(dateOfBirth, 'DD/MM/YYYY').toDate();

    let member = fakeNewMember(residentialAddressId, postalAddressId, momentDate);

    member.residentialAddressId = member.residentialAddress;
    delete(member.residentialAddress);

    member.postalAddressId = member.postalAddress;
    delete(member.postalAddress);

    member.verified = false;

    return member;
}

describe('memberService', () => {
    describe('createMember', () => {
        const residentialAddressId = 1;
        const postalAddressId = 2;
        const randomNewMemberId = 1;
        const date = '22/12/1900';
        const residentialAddressFromDb = [
            {
                dataValues: {
                    id: residentialAddressId
                }
            }
        ];
        const postalAddressFromDb = [
            {
                dataValues: {
                    id: postalAddressId
                }
            }
        ];

        let createMemberStub, addressStub, loggerStub,
            residentialAddress, postalAddress,
            newMember, expectedNewMember, createdMemberFromDb,
            residentialAddressPromise, postalAddressPromise, memberPromise;

        beforeEach(() => {
            createMemberStub = sinon.stub(models.Member, 'create');
            addressStub = sinon.stub(models.Address, 'findOrCreate');
            loggerStub = sinon.stub(logger, 'logMemberSignUpEvent');

            residentialAddress = {
                address: '221b Baker St',
                suburb: 'London',
                country: 'England',
                state: 'VIC',
                postcode: '1234'
            };
            postalAddress = {
                address: '47 I dont want your spam St',
                suburb: 'Moriarty',
                country: 'USA',
                state: 'NM',
                postcode: '5678'
            };

            newMember = fakeNewMember(residentialAddress, postalAddress, date);
            expectedNewMember = getExpectedNewMember(residentialAddressId, postalAddressId, date);
            createdMemberFromDb = {
              dataValues : expectedNewMember
            };
            createdMemberFromDb.dataValues.id = randomNewMemberId;

            residentialAddressPromise = Q.defer();
            addressStub
                .withArgs({where: residentialAddress, defaults: residentialAddress})
                .returns(residentialAddressPromise.promise);

            postalAddressPromise = Q.defer();
            addressStub
                .withArgs({where: postalAddress, defaults: postalAddress})
                .returns(postalAddressPromise.promise);

            memberPromise = Q.defer();
            createMemberStub.returns(memberPromise.promise);
        });

        afterEach(() => {
            models.Member.create.restore();
            models.Address.findOrCreate.restore();
            loggerStub.restore();
        });

        it('creates a new member and address', (done) => {
            residentialAddressPromise.resolve(residentialAddressFromDb);
            postalAddressPromise.resolve(postalAddressFromDb);
            memberPromise.resolve(createdMemberFromDb);

            memberService.createMember(newMember)
                .finally((createdMember) => {
                    expect(createdMember.firstName).toEqual(expectedNewMember.firstName);
                    expect(createdMember.id).toEqual(randomNewMemberId);

                    expect(Member.create).toHaveBeenCalledWith(jasmine.objectContaining(expectedNewMember));
                }).nodeify(done);
        });

        it('logs the member sign up event', (done) => {
            residentialAddressPromise.resolve(residentialAddressFromDb);
            postalAddressPromise.resolve(postalAddressFromDb);

            memberPromise.resolve(createdMemberFromDb);

            memberService.createMember(newMember)
                .finally(() => {
                    expect(logger.logMemberSignUpEvent).toHaveBeenCalledWith(expectedNewMember);
                }).nodeify(done);
        });

        describe('when postal and residential address are identical', () => {
            it('set them both to same value', (done) => {
                newMember = fakeNewMember(residentialAddress, residentialAddress, date);
                expectedNewMember = getExpectedNewMember(residentialAddressId, residentialAddressId, date);

                residentialAddressPromise.resolve(residentialAddressFromDb);
                postalAddressPromise.resolve(postalAddressFromDb);
                memberPromise.resolve(createdMemberFromDb);

                memberService.createMember(newMember)
                    .finally(() => {
                        expect(Member.create).toHaveBeenCalledWith(jasmine.objectContaining(expectedNewMember));
                    }).nodeify(done);
            });
        });

        describe('an error when saving the residential address to the database', () => {
            it('responds with a server error', (done) => {
                let errorMessage = 'Yes, we have no bananas.';
                residentialAddressPromise.reject(errorMessage);

                let promise = memberService.createMember(newMember);

                promise.finally(() => {
                    expect(models.Member.create).not.toHaveBeenCalled();
                    expect(promise.isRejected()).toBe(true);
                    done();
                });
            });
        });

        describe('an error when saving the postal address to the databse', () => {
            it('responds with a server error', (done) => {
                let errorMessage = 'Yes, we have no horses.';
                residentialAddressPromise.resolve(residentialAddressFromDb);
                postalAddressPromise.reject(errorMessage);

                let promise = memberService.createMember(newMember);

                promise.finally(() => {
                    expect(models.Member.create).not.toHaveBeenCalled();
                    expect(promise.isRejected()).toBe(true);
                    done();
                });
            });
        });

        describe('an error when saving the member to the database', () => {
            it('rejects the promise', (done) => {
                let errorMessage = 'Seriously, we still don\'t have any damn bananas.';
                residentialAddressPromise.resolve(residentialAddressFromDb);
                postalAddressPromise.resolve(postalAddressFromDb);
                memberPromise.reject(errorMessage);

                let promise = memberService.createMember(newMember);

                promise.finally(() => {
                    expect(promise.isRejected()).toBe(true);
                    done();
                });
            });
        });
    });
});
<|endoftext|>