<commit_before>
module.exports = SQSWorker

function SQSWorker(options, fn) {
  if (!(this instanceof SQSWorker)) return new SQSWorker(options, fn)

  this.client = options.client || new (require('aws-sdk').SQS)(options)

  // Five seconds more than WaitTimeSeconds
  this.client.config.httpOptions.timeout = 25000

  this.url = options.url
  this.parallel = options.parallel || 1
  this.timeout = options.timeout || void 0
  this.parse = options.parse
  this.log = options.log || console
  this.attributes = options.attributes || []

  this.fn = fn

  this.handling = 0
  this.receiving = 0

  this.maybeMore()
}

SQSWorker.prototype.maybeMore = function (retries) {
  if (this.receiving) return
  if (this.handling >= this.parallel) return

  this.receiving++

  retries = retries || 0
  retries++

  var self = this

  var params =
    { 'QueueUrl': this.url
    , 'MaxNumberOfMessages': Math.min(this.parallel, 10)
    , 'VisibilityTimeout': this.timeout
    , 'WaitTimeSeconds': 20
    , 'AttributeNames': this.attributes
    }

  this.client.receiveMessage(params, function (err, data) {
    self.receiving--

    if (err) {
      self.log.error({ err: err, params: params }, 'failed to receive messages')
      setTimeout(self.maybeMore.bind(self), Math.min(Math.pow(2, retries), 300) * 1000, retries)
      return
    }

    self.log.info({ params: params, response: data }, 'receiveMessage response')

    if (Array.isArray(data.Messages)) {
      data.Messages.map(self.handleMessage, self)
    }

    self.maybeMore()
  })
}

SQSWorker.prototype.handleMessage = function (message) {
  this.handling++

  var payload = message.Body

  if (this.parse) {
    try {
      payload = this.parse(payload)
    } catch (err) {
      this.log.error({ err: err, message: message }, 'error parsing message body')
      return
    }
  }

  var self = this

  if (this.fn.length === 2) {
    this.fn(payload, callback)
  } else {
    this.fn(payload, message, callback)
  }

  function callback(err, success) {
    self.handling--

    if (err) {
      self.log.error({ err: err, message: message, payload: payload }, 'error handling message')
      return
    }

    var params =
      { 'QueueUrl': self.url
      , 'ReceiptHandle': message.ReceiptHandle
      }

    if (!success) {
      params['VisibilityTimeout'] = 0
    }

    self.client[success ? 'deleteMessage' : 'changeMessageVisibility'](params, function (err) {
      if (err) {
        self.log.error(
            { err: err, message: message, payload: payload }
          , 'failed to ' + (success ? 'delete message' : 'change visibility timeout')
          )
        return
      }

      self.maybeMore()
    })
  }
}
<commit_msg>delete failed messages after 3 retries<commit_after>
module.exports = SQSWorker

function SQSWorker(options, fn) {
  if (!(this instanceof SQSWorker)) return new SQSWorker(options, fn)

  this.client = options.client || new (require('aws-sdk').SQS)(options)

  // Five seconds more than WaitTimeSeconds
  this.client.config.httpOptions.timeout = 25000

  this.url = options.url
  this.parallel = options.parallel || 1
  this.timeout = options.timeout || void 0
  this.parse = options.parse
  this.log = options.log || console
  this.attributes = Array.isArray(options.attributes) ? options.attributes.slice() : []
  this.attempts = options.attempts || 3

  if (this.attempts && !~this.attributes.indexOf('ApproximateReceiveCount')) {
    this.attributes.push('ApproximateReceiveCount')
  }

  this.fn = fn

  this.handling = 0
  this.receiving = 0

  this.maybeMore()
}

SQSWorker.prototype.maybeMore = function (retries) {
  if (this.receiving) return
  if (this.handling >= this.parallel) return

  this.receiving++

  retries = retries || 0
  retries++

  var self = this

  var params =
    { 'QueueUrl': this.url
    , 'MaxNumberOfMessages': Math.min(this.parallel, 10)
    , 'VisibilityTimeout': this.timeout
    , 'WaitTimeSeconds': 20
    , 'AttributeNames': this.attributes
    }

  this.client.receiveMessage(params, function (err, data) {
    self.receiving--

    if (err) {
      self.log.error({ err: err, params: params }, 'failed to receive messages')
      setTimeout(self.maybeMore.bind(self), Math.min(Math.pow(2, retries), 300) * 1000, retries)
      return
    }

    self.log.info({ params: params, response: data }, 'receiveMessage response')

    if (Array.isArray(data.Messages)) {
      data.Messages.map(self.handleMessage, self)
    }

    self.maybeMore()
  })
}

SQSWorker.prototype.handleMessage = function (message) {
  this.handling++

  var payload = message.Body

  if (this.parse) {
    try {
      payload = this.parse(payload)
    } catch (err) {
      this.log.error({ err: err, message: message }, 'error parsing message body')
      return
    }
  }

  var self = this

  if (this.fn.length === 2) {
    this.fn(payload, callback)
  } else {
    this.fn(payload, message, callback)
  }

  function callback(err, del) {
    self.handling--

    if (err) {
      self.log.error({ err: err, message: message, payload: payload }, 'error handling message')
      del = (self.attempts && Number(message['Attributes']['ApproximateReceiveCount']) >= self.attempts)
    }

    var params =
      { 'QueueUrl': self.url
      , 'ReceiptHandle': message.ReceiptHandle
      }

    if (!del) {
      params['VisibilityTimeout'] = 0
    }

    self.client[del ? 'deleteMessage' : 'changeMessageVisibility'](params, function (err) {
      if (err) {
        self.log.error(
            { err: err, message: message, payload: payload }
          , 'failed to ' + (del ? 'delete message' : 'change visibility timeout')
          )
        return
      }

      self.maybeMore()
    })
  }
}
<|endoftext|>


<commit_before>import expect  from 'expect';
import { writeOutput, __RewireAPI__ as bundler} from '../lib/bundler';
import { config } from './config.js';

let fs = {
   existsSync: function(path){
   },
   unlinkSync: function(path){
   },
   writeFileSync: function(path, string){
   },
   mkdirSync: function(path){
   }
};

let path = {
   dirname: function(path) {
   },
   resolve: function(path1, path2) {
   },
};

bundler.__Rewire__('fs', fs);
bundler.__Rewire__('path', path);

describe('write bundle output', ()=> {
  it('writes the bundler file to disk', ()=> {
     let spy = expect.spyOn(path, 'resolve');
     writeOutput({source: 'sdfsdf'}, 'the outfile', 'the base URL', true);
     expect(spy.calls.length).toBe(1);
  });

  it('creates output directory when not exists', ()=> {
     let spy = expect.spyOn(fs, 'mkdirSync');
     fs.existsSync = expect.createSpy(fs.existsSync).andReturn(false);

     writeOutput({source: 'bundler source'}, 'outfile', 'base URL', true);
     expect(spy.calls.length).toBe(1);
  });
});
<commit_msg>test(write outpu): proper interactions when output file already exits<commit_after>import expect  from 'expect';
import { writeOutput, __RewireAPI__ as bundler} from '../lib/bundler';
import { config } from './config.js';

let fs = {
   existsSync: function(path){ },
   unlinkSync: function(path){ },
   writeFileSync: function(path, string){ },
   mkdirSync: function(path){ }
};

let path = {
   dirname: function(path) { },
   resolve: function(path1, path2) { },
};

bundler.__Rewire__('fs', fs);
bundler.__Rewire__('path', path);

describe('write bundle output', ()=> {
  it('writes the bundler file to disk', ()=> {
     let spy = expect.spyOn(path, 'resolve');
     writeOutput({source: 'sdfsdf'}, 'the outfile', 'the base URL', true);
     expect(spy.calls.length).toBe(1);
  });

  it('creates output directory when not exists', ()=> {
     let spy = expect.spyOn(fs, 'mkdirSync');
     fs.existsSync = expect.createSpy(fs.existsSync).andReturn(false);

     writeOutput({source: 'bundler source'}, 'outfile', 'base URL', true);
     expect(spy.calls.length).toBe(1);
  });

  describe('given out file exits', ()=> {
    it('does not overwrite the out file', () => {
       let spy = expect.createSpy(fs.existsSync).andReturn(true);
       fs.existsSync = spy;

       expect(_ => {
          writeOutput(
            {source: 'bundler source'},
            'outfile',
            'base URL', false)}).toThrow(/A bundle named/);

       expect(spy.calls.length).toBe(1);
    });

    it('removes the existing file when `force` option is supplied', () => {
       let spy = expect.createSpy(fs.existsSync).andReturn(true);
       fs.existsSync = spy;

       let unlinkSpy = expect.spyOn(fs, 'unlinkSync');

       expect(_ => {
          writeOutput(
            {source: 'bundler source'},
            'outfile',
            'base URL', true)}).toNotThrow(/A bundle named/);

       expect(unlinkSpy.calls.length).toBe(1);
    });

  });

});
<|endoftext|>


<commit_before>var fs = require('fs');
var should = require('should');

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var Utils = require('../src/common/utils.js').Utils;

var WorldPage = require('../src/common/world_page.js').WorldPage;

describe('WorldPage', function() {
  var utils = new Utils(XMLHttpRequest);
  var worldPage = new WorldPage(utils);

  describe('#parse', function() {
    it('should parse Antica', function(done) {
      var data = fs.readFileSync(__dirname + '/files/world_page_antica_633.html', 'utf8');
      var expected = require('./files/world_page_antica_633.expected.js').expected;
      worldPage.parse(data, function(err, res) {
        should.not.exist(err);
        res.should.eql(expected);
        Object.keys(res).should.have.length(633);
        done();
      });
    });

    it('should parse Inferna', function(done) {
      var data = fs.readFileSync(__dirname + '/files/world_page_inferna_7.html', 'utf8');
      var expected = require('./files/world_page_inferna_7.expected.js').expected;
      worldPage.parse(data, function(err, res) {
        should.not.exist(err);
        res.should.eql(expected);
        Object.keys(res).should.have.length(7);
        done();
      });
    });

    it('should parse offline Magera', function(done) {
      var data = fs.readFileSync(__dirname + '/files/world_page_magera_offline.html', 'utf8');
      worldPage.parse(data, function(err, res) {
        should.not.exist(err);
        res.should.eql({});
        Object.keys(res).should.have.length(0);
        done();
      });
    });

    it('should parse empty String', function(done) {
      worldPage.parse(' ', function(err, res) {
        should.not.exist(err);
        res.should.eql({});
        done();
      });
    });

    it('should not parse a Number', function(done) {
      worldPage.parse(42, function(err, res) {
        err.should.startWith('Data not a String ');
        done();
      });
    });

    it('should not parse an Object', function(done) {
      worldPage.parse({}, function(err, res) {
        err.should.startWith('Data not a String ');
        done();
      });
    });

    it('should not parse an Array', function(done) {
      worldPage.parse(['abc'], function(err, res) {
        err.should.startWith('Data not a String ');
        done();
      });
    });
  });

  describe('#query', function() {
    it('should not query a Number', function(done) {
      worldPage.query(42, function(err, res) {
        err.should.startWith('World name not a String ');
        done();
      });
    });

    it('should not query an Object', function(done) {
      worldPage.query({}, function(err, res) {
        err.should.startWith('World name not a String ');
        done();
      });
    });

    it('should not query an Array', function(done) {
      worldPage.query(['abc'], function(err, res) {
        err.should.startWith('World name not a String ');
        done();
      });
    });

    it('should not query an empty String', function(done) {
      worldPage.query(' ', function(err, res) {
        err.should.startWith('Empty world name ');
        done();
      });
    });

    it('should query Antica', function(done) {
      worldPage.worlds_cache.should.eql({});
      var time = new Date().getTime();
      worldPage.query('Antica', function(err, res) {
        should.not.exist(err);
        should.exist(res);
        worldPage.worlds_cache.should.have.keys('Antica');
        worldPage.worlds_cache.Antica.time.should.be.within(time, time + worldPage.cache_time);
        done();
      });
    });

    it('should use cached Antica', function(done) {
      worldPage.worlds_cache.should.have.keys('Antica');
      var time = worldPage.worlds_cache.Antica.time;
      var now = new Date().getTime();
      now.should.be.within(time, time + worldPage.cache_time);
      worldPage.query('Antica', function(err, res) {
        should.not.exist(err);
        should.exist(res);
        time.should.equal(worldPage.worlds_cache.Antica.time);
        worldPage.worlds_cache.should.have.keys('Antica');
        done();
      });
    });

    it('should not use cached Antica', function(done) {
      worldPage.worlds_cache.should.have.keys('Antica');
      // Move so its time to refresh cache
      worldPage.worlds_cache.Antica.time -= (worldPage.cache_time + 1);
      var time = worldPage.worlds_cache.Antica.time;
      worldPage.query('Antica', function(err, res) {
        should.not.exist(err);
        should.exist(res);
        worldPage.worlds_cache.Antica.time.should.be.above(time);
        worldPage.worlds_cache.should.have.keys('Antica');
        done();
      });
    });
  });
});
<commit_msg>Suspicious row testcase<commit_after>var fs = require('fs');
var should = require('should');

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var Utils = require('../src/common/utils.js').Utils;

var WorldPage = require('../src/common/world_page.js').WorldPage;

describe('WorldPage', function() {
  var utils = new Utils(XMLHttpRequest);
  var worldPage = new WorldPage(utils);

  describe('#parse', function() {
    it('should parse Antica', function(done) {
      var data = fs.readFileSync(__dirname + '/files/world_page_antica_633.html', 'utf8');
      var expected = require('./files/world_page_antica_633.expected.js').expected;
      worldPage.parse(data, function(err, res) {
        should.not.exist(err);
        res.should.eql(expected);
        Object.keys(res).should.have.length(633);
        done();
      });
    });

    it('should parse Inferna', function(done) {
      var data = fs.readFileSync(__dirname + '/files/world_page_inferna_7.html', 'utf8');
      var expected = require('./files/world_page_inferna_7.expected.js').expected;
      worldPage.parse(data, function(err, res) {
        should.not.exist(err);
        res.should.eql(expected);
        Object.keys(res).should.have.length(7);
        done();
      });
    });

    it('should parse offline Magera', function(done) {
      var data = fs.readFileSync(__dirname + '/files/world_page_magera_offline.html', 'utf8');
      worldPage.parse(data, function(err, res) {
        should.not.exist(err);
        res.should.eql({});
        Object.keys(res).should.have.length(0);
        done();
      });
    });

    it('should not parse suspicious row', function(done) {
      worldPage.parse('
Chorizo\'korv	70	Elite Sorcerer
', function(err, res) {
        err.should.startWith('Suspicious row match, name: ');
        done();
      });
    });

    it('should parse empty String', function(done) {
      worldPage.parse(' ', function(err, res) {
        should.not.exist(err);
        res.should.eql({});
        done();
      });
    });

    it('should not parse a Number', function(done) {
      worldPage.parse(42, function(err, res) {
        err.should.startWith('Data not a String ');
        done();
      });
    });

    it('should not parse an Object', function(done) {
      worldPage.parse({}, function(err, res) {
        err.should.startWith('Data not a String ');
        done();
      });
    });

    it('should not parse an Array', function(done) {
      worldPage.parse(['abc'], function(err, res) {
        err.should.startWith('Data not a String ');
        done();
      });
    });
  });

  describe('#query', function() {
    it('should not query a Number', function(done) {
      worldPage.query(42, function(err, res) {
        err.should.startWith('World name not a String ');
        done();
      });
    });

    it('should not query an Object', function(done) {
      worldPage.query({}, function(err, res) {
        err.should.startWith('World name not a String ');
        done();
      });
    });

    it('should not query an Array', function(done) {
      worldPage.query(['abc'], function(err, res) {
        err.should.startWith('World name not a String ');
        done();
      });
    });

    it('should not query an empty String', function(done) {
      worldPage.query(' ', function(err, res) {
        err.should.startWith('Empty world name ');
        done();
      });
    });

    it('should query Antica', function(done) {
      worldPage.worlds_cache.should.eql({});
      var time = new Date().getTime();
      worldPage.query('Antica', function(err, res) {
        should.not.exist(err);
        should.exist(res);
        worldPage.worlds_cache.should.have.keys('Antica');
        worldPage.worlds_cache.Antica.time.should.be.within(time, time + worldPage.cache_time);
        done();
      });
    });

    it('should use cached Antica', function(done) {
      worldPage.worlds_cache.should.have.keys('Antica');
      var time = worldPage.worlds_cache.Antica.time;
      var now = new Date().getTime();
      now.should.be.within(time, time + worldPage.cache_time);
      worldPage.query('Antica', function(err, res) {
        should.not.exist(err);
        should.exist(res);
        time.should.equal(worldPage.worlds_cache.Antica.time);
        worldPage.worlds_cache.should.have.keys('Antica');
        done();
      });
    });

    it('should not use cached Antica', function(done) {
      worldPage.worlds_cache.should.have.keys('Antica');
      // Move so its time to refresh cache
      worldPage.worlds_cache.Antica.time -= (worldPage.cache_time + 1);
      var time = worldPage.worlds_cache.Antica.time;
      worldPage.query('Antica', function(err, res) {
        should.not.exist(err);
        should.exist(res);
        worldPage.worlds_cache.Antica.time.should.be.above(time);
        worldPage.worlds_cache.should.have.keys('Antica');
        done();
      });
    });
  });
});
<|endoftext|>


<commit_before>/* eslint-env node */
'use strict';

var { requireUp } = require('./requireUp');
var { DEFAULT_EXTENSIONS } = require('./constants');

var rules = requireUp('eslint-local-rules', DEFAULT_EXTENSIONS, __dirname);

if (!rules) {
  throw new Error(
    'eslint-plugin-local-rules: ' +
      'Cannot find "eslint-local-rules{' +
      ['.js'].concat(exts.filter(Boolean)) +
      '} ' +
      'or eslint-local-rules/index.js (checked all ancestors of "' +
      __dirname +
      '").'
  );
}

module.exports = {
  rules: rules,
};
<commit_msg>Fix "undefined var exts when eslint-local-rules.js not found"<commit_after>/* eslint-env node */
'use strict';

var { requireUp } = require('./requireUp');
var { DEFAULT_EXTENSIONS } = require('./constants');

var rules = requireUp('eslint-local-rules', DEFAULT_EXTENSIONS, __dirname);

if (!rules) {
  throw new Error(
    'eslint-plugin-local-rules: ' +
      'Cannot find "eslint-local-rules{' +
      ['.js'].concat(DEFAULT_EXTENSIONS.filter(Boolean)) +
      '} ' +
      'or eslint-local-rules/index.js (checked all ancestors of "' +
      __dirname +
      '").'
  );
}

module.exports = {
  rules: rules,
};
<|endoftext|>


<commit_before>test("Caman is a function", function () {
  expect(1);

  ok(Caman, "Caman exists");

});
<commit_msg>Tests for rgb_to_xyz and xyz_to_rbg.<commit_after>test("Caman is a function", function () {
  expect(1);

  ok(Caman, "Caman exists");

});

test("rgb_to_xyz and xyz_to_rgb are symmetric", function() {
  var rgbColors = [
    {r: 127, g: 127, b: 127},
    {r:   0, g:   0, b: 255},
    {r:   0, g: 255, b:   0},
    {r: 255, g:   0, b:   0},
    {r:  12, g:  32, b:  64}
  ];

  expect(rgbColors.length * 3);

  for(var i = 0, len = rgbColors.length; i < len; ++i) {
    var originalRGB = rgbColors[i];
    var xyz = Caman.rgb_to_xyz(originalRGB.r, originalRGB.g, originalRGB.b);
    var rgb = Caman.xyz_to_rgb(xyz.x, xyz.y, xyz.z);
    var testColorStr = '{r: ' + originalRGB.r + ', g: ' + originalRGB.g + ', b: ' + originalRGB.b + '}';
    ok(Math.round(rgb.r) == originalRGB.r, "Red value for " + testColorStr);
    ok(Math.round(rgb.g) == originalRGB.g, "Green value for " + testColorStr);
    ok(Math.round(rgb.b) == originalRGB.b, "Blue value for " + testColorStr);
  }
});

test("xyz_to_rgb and rgb_to_xyz are symmetric", function() {
  var xyzColors = [
    {x: 50.5, y: 50.5, z: 50.5},
    {x:    0, y:    0, z:  100},
    {x:    0, y:  100, z:    0},
    {x:  100, y:    0, z:    0},
    {x: 10.4, y: 92.8, z: 39.2}
  ];

  expect(xyzColors.length * 3);

  for(var i = 0, len = xyzColors.length; i < len; ++i) {
    var originalXYZ = xyzColors[i];
    var rgb = Caman.xyz_to_rgb(originalXYZ.x, originalXYZ.y, originalXYZ.z);
    var xyz = Caman.rgb_to_xyz(rgb.r, rgb.g, rgb.b);

    var testColorStr = '{x: ' + originalXYZ.x + ', y: ' + originalXYZ.y + ', z: ' + originalXYZ.z + '}';
    ok(Math.abs(xyz.x - originalXYZ.x) < 0.01, "X value for " + testColorStr);
    ok(Math.abs(xyz.y - originalXYZ.y) < 0.01, "Y value for " + testColorStr);
    ok(Math.abs(xyz.z - originalXYZ.z) < 0.01, "Z value for " + testColorStr);
  }
});<|endoftext|>


<commit_before>require('dotenv').config()

if (process.env.NODE_ENV === 'production') {
  require('newrelic')
}

const http = require("http")
const app = require('express')()
const JIRA = require('./services/jira');

app.get('/', (req, res) => {
  res.send('Bot is running.')
})

app.get('/jira/:issueKey/status', (req, res) => {
  JIRA.getIssue(req.params.issueKey).then(issue => {
    res.send(issue.fields.status)
  })
})

app.get('/jira/:issueKey/assignee', (req, res) => {
  JIRA.getIssue(req.params.issueKey).then(issue => {
    res.send(issue.fields.assignee.key || 'unassigned')
  })
})

app.get('/jira/:issueKey/summary', (req, res) => {
  JIRA.getIssue(req.params.issueKey).then(issue => {
    res.send(issue.fields.summary)
  })
})

app.listen(process.env.PORT)

// keep alive
setInterval(() => {
  http.get(`http://${process.env.HEROKU_APP_ID}.herokuapp.com`)
}, 5 * 60 * 1000);

require('./bot')
require('./corn')()
<commit_msg>update<commit_after>require('dotenv').config()

if (process.env.NODE_ENV === 'production') {
  require('newrelic')
}

const http = require("http")
const app = require('express')()
const JIRA = require('./services/jira');

app.get('/', (req, res) => {
  res.send('Bot is running.')
})

app.get('/jira/:issueKey/status', (req, res) => {
  JIRA.getIssue(req.params.issueKey).then(issue => {
    res.send(issue.fields.status)
  })
})

app.get('/jira/:issueKey/assignee', (req, res) => {
  JIRA.getIssue(req.params.issueKey).then(issue => {
    res.send(issue.fields.assignee.key || 'unassigned')
  })
})

app.get('/jira/:issueKey/summary', (req, res) => {
  JIRA.getIssue(req.params.issueKey).then(issue => {
    res.send(issue.fields.summary)
  })
})

app.listen(process.env.PORT)

// keep alive
setInterval(() => {
  console.log(`http://${process.env.HEROKU_APP_NAME}.herokuapp.com`)
  http.get(`http://${process.env.HEROKU_APP_NAME}.herokuapp.com`)
}, 5 * 60 * 1000);

require('./bot')
require('./corn')()
<|endoftext|>


<commit_before>d = Date();
dv = d.valueOf();
var log = d;
function saveTextAsFile()
{
	var textToWrite = log;
	var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
	var fileNameToSaveAs = "classtrisLog" + dv + ".csv";

	var downloadLink = document.createElement("a");
	downloadLink.download = fileNameToSaveAs;
	downloadLink.innerHTML = "Download File";
	if (window.webkitURL != null)
	{
		// Chrome allows the link to be clicked
		// without actually adding it to the DOM.
		downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
	}
	else
	{
		// Firefox requires the link to be added to the DOM
		// before it can be clicked.
		downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
		downloadLink.onclick = destroyClickedElement;
		downloadLink.style.display = "none";
		document.body.appendChild(downloadLink);
	}

	downloadLink.click();
}

function destroyClickedElement(event)
{
	document.body.removeChild(event.target);
}

function checkUndefined(stud) {
    return stud != undefined;
}

function checkBlank(stud) {
    return stud != "";
}

function loadClassList()
{
	var fileToLoad = document.getElementById("fileToLoad").files[0];

	var fileReader = new FileReader();
	fileReader.onload = function(fileLoadedEvent)
	{
		var textFromFileLoaded = fileLoadedEvent.target.result;
		currentClass = textFromFileLoaded .split("\n");

		currentClass = currentClass.filter(checkUndefined);
		currentClass = currentClass.filter(checkBlank);

		document.getElementById("inputTextToSave").value = textFromFileLoaded;
		dynamicClass = currentClass;
		dynamicClass.sort(function(a, b){return 0.5 - Math.random()});
		document.getElementById("inputTextToSave").value = dynamicClass;
		up = [];

		// teams
		team1 = [];
		team2 = [];
		team3 = [];
		team4 = [];

		// team points
		tp = [0,0,0,0];

		var teamN = 0;
		for (i = 0; i < dynamicClass.length; i++) {
			teamN = i%4;
			switch(i%4) {
				case 1:
					team1.push(dynamicClass[i]);
					break;
				case 2:
					team2.push(dynamicClass[i]);
					break;
				case 3:
					team3.push(dynamicClass[i]);
					break;
				case 0:
					team4.push(dynamicClass[i]);
					break;
			}
		}
		/*
		document.getElementById('team1').innerHTML = team1;
		document.getElementById('team2').innerHTML = team2;
		document.getElementById('team3').innerHTML = team3;
		document.getElementById('team4').innerHTML = team4;
		*/

		for (i = 0; i < 4; i++) {
			up[i] = dynamicClass[i];
		}
		q = 0;
		document.getElementById('up').innerHTML = up[0];
		document.getElementById('next').innerHTML = up[1];
		document.getElementById('then1').innerHTML = up[2];
		document.getElementById('then2').value = up[3];

		if (up[1] === undefined) {
			cycleNext();
		}

	}
	fileReader.readAsText(fileToLoad, "UTF-8");
	log += '\n' + Date();
}

function loadQuestions(mode)
{
	var fileToLoad = document.getElementById("questionLoad").files[0];

	var fileReader = new FileReader();
	fileReader.onload = function(fileLoadedEvent)
	{
		var textFromFileLoaded = fileLoadedEvent.target.result;
		currentQuest = textFromFileLoaded .split("\n");

		currentQuest = currentQuest.filter(checkUndefined);
		currentQuest = currentQuest.filter(checkBlank);

		document.getElementById("inputTextToSave").value = textFromFileLoaded;
		dynamicQuest = currentQuest;
		if (mode == "random") {
			dynamicQuest.sort(function(a, b){return 0.5 - Math.random()});
		}
		document.getElementById("inputTextToSave").value = dynamicQuest;
		question = dynamicQuest[0];
		qs = 0;
		document.getElementById('question').innerHTML = question;
	}
	fileReader.readAsText(fileToLoad, "UTF-8");
	questionsLoaded = true;
	//log += '/n' + question;
}

function nextQuestion() {
		qs += 1;

		n = dynamicQuest.length;
		if (qs >= n-2) {
			dynamicQuest.sort(function(a, b){return 0.5 - Math.random()});
			qs = 0;
		}

		question = dynamicQuest[qs];
		document.getElementById('question').innerHTML = question;
		//log = log + '\n' + question;
	}

	function cycleNext() {
		/*
		if (questionsLoaded) {
			nextQuestion();
		}
		/*
		var i = currentClass.indexOf(up[0])
		xp[i] += Number(xpee);
		dynamicClass.push(up[0] + xp[i]);
		*/
		q++
		up.shift();

		up[3] = dynamicClass[q];

		n = dynamicClass.length;
		if (q >= n-2) {
			dynamicClass.sort(function(a, b){return 0.5 - Math.random()});
			q = 0;
		}
		document.getElementById('up').innerHTML = up[0];
		document.getElementById('next').innerHTML = up[1];
		document.getElementById('then1').innerHTML = up[2];
		document.getElementById('then2').value = up[3];
		//document.getElementById('q').innerHTML = q;

	}

	function cycleThen1() {
		/*
		if (questionsLoaded) {
			nextQuestion();
		}

		var i = currentClass.indexOf(up[0])
		xp[i] += Number(xpee);
		dynamicClass.push(up[0] + xp[i]);
		*/
		q++
		up[0] = up[2];
		up[2] = up[3];
		up[3] = dynamicClass[q];

		n = dynamicClass.length;
		if (q >= n-2) {
			dynamicClass.sort(function(a, b){return 0.5 - Math.random()});
			q = 0;
		}
		document.getElementById('up').innerHTML = up[0];
		document.getElementById('next').innerHTML = up[1];
		document.getElementById('then1').innerHTML = up[2];
		document.getElementById('then2').value = up[3];

		// debug script
		//document.getElementById('q').innerHTML = q;
		/*
		if (up[1] === undefined) {
			cycleNext();
		}
		*/
	}

	function cycleThen2() {
		/*
		if (questionsLoaded) {
			nextQuestion();
		}

		var i = currentClass.indexOf(up[0])
		xp[i] += Number(xpee);
		dynamicClass.push(up[0] + xp[i]);
		*/
		//q++
		up[0] = up[1];
		up[1] = up[2];
		up[2] = up[3];
		up[3] = document.getElementById('then2').value;

		log += up[3] + ", manually added";

		n = dynamicClass.length;
		if (q >= n-2) {
			dynamicClass.sort(function(a, b){return 0.5 - Math.random()});
			q = 0;
		}
		document.getElementById('up').innerHTML = up[0];
		document.getElementById('next').innerHTML = up[1];
		document.getElementById('then1').innerHTML = up[2];
		document.getElementById('then2').value = (up[3] + " successfully added.");
		//document.getElementById('q').innerHTML = q;
		/*
		if (up[1] === undefined) {
			cycleNext();
		}
		*/
	}

	function checkUp(player) {
		return player == up[0];
	}

	function score(pt) {
		if (team1.some(checkUp)) {
			tp[1] += pt;
		} else if (team2.some(checkUp)) {
			tp[2] += pt;
		} else if (team3.some(checkUp)) {
			tp[3] += pt;
		} else if (team4.some(checkUp)) {
			tp[0] += pt;
		}
		/*
		document.getElementById('t1p').innerHTML = tp[1];
		document.getElementById('t2p').innerHTML = tp[2];
		document.getElementById('t3p').innerHTML = tp[3];
		document.getElementById('t4p').innerHTML = tp[0];
		*/
		log += '\n' + up[0] + "," + pt;
		document.getElementById("inputTextToSave").value = log;

		if (pt == 4) {
			nextQuestion();
		}
		if (pt > 1) {
			cycleNext();
		}

	}

	function gameOver() {
		highScore = Math.max(tp[0],tp[1],tp[2],tp[3]);
   		teamN = tp.indexOf(highScore);
		switch(teamN) {
			case 1:
				winners = team1;
				break;
			case 2:
				winners = team2;
				break;
			case 3:
				winners = team3;
				break;
			case 0:
				winners = team4;
				break;
		}
		congrats = "Congratulations " + winners.join(", ") + "!";
		document.getElementById('question').innerHTML = congrats;
		//log += '\n' + congrats;
	}

	function setMode(mod) {
		questMode = mod;
	}
<commit_msg>Update loadStuff.js<commit_after>var d = Date();
var dv = d.valueOf();
var log = d;
var questionsLoaded = false;
function saveTextAsFile()
{
	var textToWrite = log;
	var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
	var fileNameToSaveAs = "classtrisLog" + dv + ".csv";

	var downloadLink = document.createElement("a");
	downloadLink.download = fileNameToSaveAs;
	downloadLink.innerHTML = "Download File";
	if (window.webkitURL != null)
	{
		// Chrome allows the link to be clicked
		// without actually adding it to the DOM.
		downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
	}
	else
	{
		// Firefox requires the link to be added to the DOM
		// before it can be clicked.
		downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
		downloadLink.onclick = destroyClickedElement;
		downloadLink.style.display = "none";
		document.body.appendChild(downloadLink);
	}

	downloadLink.click();
}

function destroyClickedElement(event)
{
	document.body.removeChild(event.target);
}

function checkUndefined(stud) {
    return stud != undefined;
}

function checkBlank(stud) {
    return stud != "";
}

function loadClassList()
{
	var fileToLoad = document.getElementById("fileToLoad").files[0];

	var fileReader = new FileReader();
	fileReader.onload = function(fileLoadedEvent)
	{
		var textFromFileLoaded = fileLoadedEvent.target.result;
		currentClass = textFromFileLoaded .split("\n");

		currentClass = currentClass.filter(checkUndefined);
		currentClass = currentClass.filter(checkBlank);

		document.getElementById("inputTextToSave").value = textFromFileLoaded;
		dynamicClass = currentClass;
		dynamicClass.sort(function(a, b){return 0.5 - Math.random()});
		document.getElementById("inputTextToSave").value = dynamicClass;
		up = [];

		// teams
		team1 = [];
		team2 = [];
		team3 = [];
		team4 = [];

		// team points
		tp = [0,0,0,0];

		var teamN = 0;
		for (i = 0; i < dynamicClass.length; i++) {
			teamN = i%4;
			switch(i%4) {
				case 1:
					team1.push(dynamicClass[i]);
					break;
				case 2:
					team2.push(dynamicClass[i]);
					break;
				case 3:
					team3.push(dynamicClass[i]);
					break;
				case 0:
					team4.push(dynamicClass[i]);
					break;
			}
		}
		/*
		document.getElementById('team1').innerHTML = team1;
		document.getElementById('team2').innerHTML = team2;
		document.getElementById('team3').innerHTML = team3;
		document.getElementById('team4').innerHTML = team4;
		*/

		for (i = 0; i < 4; i++) {
			up[i] = dynamicClass[i];
		}
		q = 0;
		document.getElementById('up').innerHTML = up[0];
		document.getElementById('next').innerHTML = up[1];
		document.getElementById('then1').innerHTML = up[2];
		document.getElementById('then2').value = up[3];

		if (up[1] === undefined) {
			cycleNext();
		}

	}
	fileReader.readAsText(fileToLoad, "UTF-8");
	log += '\n' + Date();
}

function loadQuestions(mode)
{
	var fileToLoad = document.getElementById("questionLoad").files[0];

	var fileReader = new FileReader();
	fileReader.onload = function(fileLoadedEvent)
	{
		var textFromFileLoaded = fileLoadedEvent.target.result;
		currentQuest = textFromFileLoaded .split("\n");

		currentQuest = currentQuest.filter(checkUndefined);
		currentQuest = currentQuest.filter(checkBlank);

		document.getElementById("inputTextToSave").value = textFromFileLoaded;
		dynamicQuest = currentQuest;
		if (mode == "random") {
			dynamicQuest.sort(function(a, b){return 0.5 - Math.random()});
		}
		document.getElementById("inputTextToSave").value = dynamicQuest;
		question = dynamicQuest[0];
		qs = 0;
		document.getElementById('question').innerHTML = question;
	}
	fileReader.readAsText(fileToLoad, "UTF-8");
	questionsLoaded = true;
	//log += '/n' + question;
}

function nextQuestion() {
		qs += 1;

		n = dynamicQuest.length;
		if (qs >= n-2) {
			dynamicQuest.sort(function(a, b){return 0.5 - Math.random()});
			qs = 0;
		}

		question = dynamicQuest[qs];
		document.getElementById('question').innerHTML = question;
		//log = log + '\n' + question;
	}

	function cycleNext() {
		/*
		if (questionsLoaded) {
			nextQuestion();
		}
		/*
		var i = currentClass.indexOf(up[0])
		xp[i] += Number(xpee);
		dynamicClass.push(up[0] + xp[i]);
		*/
		q++
		up.shift();

		up[3] = dynamicClass[q];

		n = dynamicClass.length;
		if (q >= n-2) {
			dynamicClass.sort(function(a, b){return 0.5 - Math.random()});
			q = 0;
		}
		document.getElementById('up').innerHTML = up[0];
		document.getElementById('next').innerHTML = up[1];
		document.getElementById('then1').innerHTML = up[2];
		document.getElementById('then2').value = up[3];
		//document.getElementById('q').innerHTML = q;

	}

	function cycleThen1() {
		/*
		if (questionsLoaded) {
			nextQuestion();
		}

		var i = currentClass.indexOf(up[0])
		xp[i] += Number(xpee);
		dynamicClass.push(up[0] + xp[i]);
		*/
		q++
		up[0] = up[2];
		up[2] = up[3];
		up[3] = dynamicClass[q];

		n = dynamicClass.length;
		if (q >= n-2) {
			dynamicClass.sort(function(a, b){return 0.5 - Math.random()});
			q = 0;
		}
		document.getElementById('up').innerHTML = up[0];
		document.getElementById('next').innerHTML = up[1];
		document.getElementById('then1').innerHTML = up[2];
		document.getElementById('then2').value = up[3];

		// debug script
		//document.getElementById('q').innerHTML = q;
		/*
		if (up[1] === undefined) {
			cycleNext();
		}
		*/
	}

	function cycleThen2() {
		/*
		if (questionsLoaded) {
			nextQuestion();
		}

		var i = currentClass.indexOf(up[0])
		xp[i] += Number(xpee);
		dynamicClass.push(up[0] + xp[i]);
		*/
		//q++
		up[0] = up[1];
		up[1] = up[2];
		up[2] = up[3];
		up[3] = document.getElementById('then2').value;

		log += up[3] + ", manually added";

		n = dynamicClass.length;
		if (q >= n-2) {
			dynamicClass.sort(function(a, b){return 0.5 - Math.random()});
			q = 0;
		}
		document.getElementById('up').innerHTML = up[0];
		document.getElementById('next').innerHTML = up[1];
		document.getElementById('then1').innerHTML = up[2];
		document.getElementById('then2').value = (up[3] + " successfully added.");
		//document.getElementById('q').innerHTML = q;
		/*
		if (up[1] === undefined) {
			cycleNext();
		}
		*/
	}

	function checkUp(player) {
		return player == up[0];
	}

	function score(pt) {
		if (team1.some(checkUp)) {
			tp[1] += pt;
		} else if (team2.some(checkUp)) {
			tp[2] += pt;
		} else if (team3.some(checkUp)) {
			tp[3] += pt;
		} else if (team4.some(checkUp)) {
			tp[0] += pt;
		}
		/*
		document.getElementById('t1p').innerHTML = tp[1];
		document.getElementById('t2p').innerHTML = tp[2];
		document.getElementById('t3p').innerHTML = tp[3];
		document.getElementById('t4p').innerHTML = tp[0];
		*/
		log += '\n' + up[0] + "," + pt;
		document.getElementById("inputTextToSave").value = log;

		if (pt == 4) {
			if (questionsLoaded) {
				nextQuestion();
			}
		}
		if (pt > 1) {
			cycleNext();
		}

	}

	function gameOver() {
		highScore = Math.max(tp[0],tp[1],tp[2],tp[3]);
   		teamN = tp.indexOf(highScore);
		switch(teamN) {
			case 1:
				winners = team1;
				break;
			case 2:
				winners = team2;
				break;
			case 3:
				winners = team3;
				break;
			case 0:
				winners = team4;
				break;
		}
		congrats = "Congratulations " + winners.join(", ") + "!";
		document.getElementById('question').innerHTML = congrats;
		//log += '\n' + congrats;
	}

	function setMode(mod) {
		questMode = mod;
	}
<|endoftext|>


<commit_before>/*globals require */

(function () {
    'use strict';

    var assert = require('chai').assert,
        module = '../src/check-types';

    suite('no setup:', function () {
        test('require does not throw', function () {
            assert.doesNotThrow(function () {
                require(module);
            });
        });

        test('require returns object', function () {
            assert.isObject(require(module));
        });
    });

    suite('require:', function () {
        var types;

        setup(function () {
            types = require(module);
        });

        teardown(function () {
            types = undefined;
        });

        test('quacksLike function is defined', function () {
            assert.isFunction(types.quacksLike);
        });

        test('quacksLike without arguments throws', function () {
            assert.throws(function () {
                types.quacksLike();
            });
        });

        test('quacksLike with two object arguments does not throw', function () {
            assert.doesNotThrow(function () {
                types.quacksLike({}, {});
            });
        });

        test('quacksLike with function first argument throws', function () {
            assert.throws(function () {
                types.quacksLike(function () {}, {});
            });
        });

        test('quacksLike with null first argument throws', function () {
            assert.throws(function () {
                types.quacksLike(null, {});
            });
        });

        test('quacksLike with function second argument throws', function () {
            assert.throws(function () {
                types.quacksLike({}, function () {});
            });
        });

        test('quacksLike with null second argument throws', function () {
            assert.throws(function () {
                types.quacksLike({}, null);
            });
        });

        test('quacksLike with two empty object arguments returns true', function () {
            assert.isTrue(types.quacksLike({}, {}));
        });

        test('quacksLike with foo bar properties returns false', function () {
            assert.isFalse(types.quacksLike({ foo: {} }, { bar: {} }));
        });

        test('quacksLike with foo foo properties returns true', function () {
            assert.isTrue(types.quacksLike({ foo: {} }, { foo: {} }));
        });

        test('quacksLike with bar baz second properties returns false', function () {
            assert.isFalse(types.quacksLike({ foo: {}, bar: {} }, { foo: {}, baz: {} }));
        });

        test('quacksLike with bar bar second properties returns true', function () {
            assert.isTrue(types.quacksLike({ foo: (function () {}), bar: {} }, { foo: (function () {}), bar: {} }));
        });

        test('quacksLike with differently typed bar bar second properties returns false', function () {
            assert.isFalse(types.quacksLike({ foo: (function () {}), bar: {} }, { foo: (function () {}), bar: (function () {}) }));
        });

        test('verifyInstance with new Error and Error does not throw', function () {
            assert.doesNotThrow(function () {
                types.verifyInstance(new Error(), Error);
            });
        });

        test('verifyInstance with object and Error throws', function () {
            assert.throws(function () {
                types.verifyInstance({}, Error);
            });
        });

        test('verifyInstance with null and null throws', function () {
            assert.throws(function () {
                types.verifyInstance(null, null);
            });
        });

        test('verifyInstance with object and Object does not throw', function () {
            assert.doesNotThrow(function () {
                types.verifyInstance({}, Object);
            });
        });

        test('verifyInstance with null and Object throws', function () {
            assert.throws(function () {
                types.verifyInstance(null, Object);
            });
        });

        test('verifyInstance with array and Array does not throw', function () {
            assert.doesNotThrow(function () {
                types.verifyInstance([], Array);
            });
        });

        test('verifyInstance with Object and object throws', function () {
            assert.throws(function () {
                types.verifyInstance(Object, {});
            });
        });

        test('isInstance function is defined', function () {
            assert.isFunction(types.isInstance);
        });

        test('isInstance with new Error and Error returns true', function () {
            assert.isTrue(types.isInstance(new Error(), Error));
        });

        test('isInstance with object and Error returns false', function () {
            assert.isFalse(types.isInstance({}, Error));
        });

        test('isInstance with null and null returns false', function () {
            assert.isFalse(types.isInstance(null, null));
        });

        test('isInstance with object and Object returns true', function () {
            assert.isTrue(types.isInstance({}, Object));
        });

        test('isInstance with null and Object returns false', function () {
            assert.isFalse(types.isInstance(null, Object));
        });

        test('isInstance with array and Array returns true', function () {
            assert.isTrue(types.isInstance([], Array));
        });

        test('isInstance with Object and object returns false', function () {
            assert.isFalse(types.isInstance(Object, {}));
        });

        test('verifyObject function is defined', function () {
            assert.isFunction(types.verifyObject);
        });

        test('verifyObject with object does not throw', function () {
            assert.doesNotThrow(function () {
                types.verifyObject({});
            });
        });

        test('verifyObject with null throws', function () {
            assert.throws(function () {
                types.verifyObject(null);
            });
        });

        test('verifyObject with string throws', function () {
            assert.throws(function () {
                types.verifyObject('[]');
            });
        });

        test('verifyObject with array throws', function () {
            assert.throws(function () {
                types.verifyObject([]);
            });
        });

        test('isObject function is defined', function () {
            assert.isFunction(types.isObject);
        });

        test('isObject with object returns true', function () {
            assert.isTrue(types.isObject({}));
        });

        test('isObject with null returns false', function () {
            assert.isFalse(types.isObject(null));
        });

        test('isObject with string returns false', function () {
            assert.isFalse(types.isObject('{}'));
        });

        test('isObject with array returns false', function () {
            assert.isFalse(types.isObject([]));
        });

        test('verifyArray function is defined', function () {
            assert.isFunction(types.verifyArray);
        });

        test('verifyArray with array does not throw', function () {
            assert.doesNotThrow(function () {
                types.verifyArray([]);
            });
        });

        test('verifyArray with null throws', function () {
            assert.throws(function () {
                types.verifyArray(null);
            });
        });

        test('verifyArray with string throws', function () {
            assert.throws(function () {
                types.verifyArray('[]');
            });
        });

        test('verifyArray with object throws', function () {
            assert.throws(function () {
                types.verifyArray({});
            });
        });

        test('isArray function is defined', function () {
            assert.isFunction(types.isArray);
        });

        test('isArray with array returns true', function () {
            assert.isTrue(types.isArray([]));
        });

        test('isArray with null returns false', function () {
            assert.isFalse(types.isArray(null));
        });

        test('isArray with string returns false', function () {
            assert.isFalse(types.isArray('[]'));
        });

        test('isArray with object returns false', function () {
            assert.isFalse(types.isArray({}));
        });

        test('verifyFunction function is defined', function () {
            assert.isFunction(types.verifyFunction);
        });

        test('verifyFunction with function does not throw', function () {
            assert.doesNotThrow(function () {
                types.verifyFunction(function () {});
            });
        });

        test('verifyFunction with null throws', function () {
            assert.throws(function () {
                types.verifyFunction(null);
            });
        });

        test('verifyFunction with string throws', function () {
            assert.throws(function () {
                types.verifyFunction('[]');
            });
        });

        test('verifyFunction with object throws', function () {
            assert.throws(function () {
                types.verifyFunction({});
            });
        });

        test('verifyFunction with array throws', function () {
            assert.throws(function () {
                types.verifyFunction([]);
            });
        });

        test('isFunction function is defined', function () {
            assert.isFunction(types.isFunction);
        });

        test('isFunction with function returns true', function () {
            assert.isTrue(types.isFunction(function () {}));
        });

        test('isFunction with null returns false', function () {
            assert.isFalse(types.isFunction(null));
        });

        test('isFunction with string returns false', function () {
            assert.isFalse(types.isFunction('function () {}'));
        });

        test('isFunction with object returns false', function () {
            assert.isFalse(types.isFunction({}));
        });

        test('isFunction with array returns false', function () {
            assert.isFalse(types.isFunction([]));
        });

        test('verifyUnemptyString function is defined', function () {
            assert.isFunction(types.verifyUnemptyString);
        });

        test('verifyUnemptyString with string baz does not throw', function () {
            assert.doesNotThrow(function () {
                types.verifyUnemptyString('baz');
            });
        });

        test('verifyUnemptyString with null throws', function () {
            assert.throws(function () {
                types.verifyUnemptyString(null);
            });
        });

        test('verifyUnemptyString with empty string throws', function () {
            assert.throws(function () {
                types.verifyUnemptyString('');
            });
        });

        test('verifyUnemptyString with object throws', function () {
            assert.throws(function () {
                types.verifyUnemptyString({});
            });
        });

        test('verifyUnemptyString with string qux does not throw', function () {
            assert.doesNotThrow(function () {
                types.verifyUnemptyString('qux');
            });
        });

        test('isUnemptyString function is defined', function () {
            assert.isFunction(types.isUnemptyString);
        });

        test('isUnemptyString with string foo returns true', function () {
            assert.isTrue(types.isUnemptyString('foo'));
        });

        test('isUnemptyString with null returns false', function () {
            assert.isFalse(types.isUnemptyString(null));
        });

        test('isUnemptyString with empty string returns false', function () {
            assert.isFalse(types.isUnemptyString(''));
        });

        test('isUnemptyString with object returns false', function () {
            assert.isFalse(types.isUnemptyString({}));
        });

        test('isUnemptyString with string bar returns true', function () {
            assert.isTrue(types.isUnemptyString('bar'));
        });

        test('verifyString function is defined', function () {
            assert.isFunction(types.verifyString);
        });

        test('verifyString with string baz does not throw', function () {
            assert.doesNotThrow(function () {
                types.verifyString('baz');
            });
        });

        test('verifyString with null throws', function () {
            assert.throws(function () {
                types.verifyString(null);
            });
        });

        test('verifyString with empty string does not throw', function () {
            assert.doesNotThrow(function () {
                types.verifyString('');
            });
        });

        test('verifyString with object throws', function () {
            assert.throws(function () {
                types.verifyString({});
            });
        });

        test('isString function is defined', function () {
            assert.isFunction(types.isString);
        });

        test('isString with string foo returns true', function () {
            assert.isTrue(types.isString('foo'));
        });

        test('isString with null returns false', function () {
            assert.isFalse(types.isString(null));
        });

        test('isString with empty string returns true', function () {
            assert.isTrue(types.isString(''));
        });

        test('isString with object returns false', function () {
            assert.isFalse(types.isString({}));
        });

        test('verifyNumber function is defined', function () {
            assert.isFunction(types.verifyNumber);
        });

        test('verifyNumber with whole number does not throw', function () {
            assert.doesNotThrow(function () {
                types.verifyNumber(1);
            });
        });

        test('verifyNumber with decimal number does not throw', function () {
            assert.doesNotThrow(function () {
                types.verifyNumber(1.2);
            });
        });

        test('verifyNumber with Infinity does not throw', function () {
            assert.doesNotThrow(function () {
                types.verifyNumber(Infinity);
            });
        });

        test('verifyNumber with NaN throws', function () {
            assert.throws(function () {
                types.verifyNumber(NaN);
            });
        });

        test('verifyNumber with null throws', function () {
            assert.throws(function () {
                types.verifyNumber(null);
            });
        });

        test('verifyNumber with object throws', function () {
            assert.throws(function () {
                types.verifyNumber({});
            });
        });

        test('isNumber function is defined', function () {
            assert.isFunction(types.isNumber);
        });

        test('isNumber with whole number returns true', function () {
            assert.isTrue(types.isNumber(1));
        });

        test('isNumber with decimal number returns true', function () {
            assert.isTrue(types.isNumber(1.2));
        });

        test('isNumber with Infinity returns true', function () {
            assert.isTrue(types.isNumber(Infinity));
        });

        test('isNumber with NaN returns false', function () {
            assert.isFalse(types.isNumber(NaN));
        });

        test('isNumber with null returns false', function () {
            assert.isFalse(types.isNumber(null));
        });

        test('isNumber with object returns false', function () {
            assert.isFalse(types.isNumber({}));
        });

        test('isNumber with string zero returns false', function () {
            assert.isFalse(types.isNumber('0'));
        });

        test('isNumber with empty string returns false', function () {
            assert.isFalse(types.isNumber(''));
        });
    });
}());

<commit_msg>Couple more tests.<commit_after>/*globals require */

(function () {
    'use strict';

    var assert = require('chai').assert,
        module = '../src/check-types';

    suite('no setup:', function () {
        test('require does not throw', function () {
            assert.doesNotThrow(function () {
                require(module);
            });
        });

        test('require returns object', function () {
            assert.isObject(require(module));
        });
    });

    suite('require:', function () {
        var types;

        setup(function () {
            types = require(module);
        });

        teardown(function () {
            types = undefined;
        });

        test('quacksLike function is defined', function () {
            assert.isFunction(types.quacksLike);
        });

        test('quacksLike without arguments throws', function () {
            assert.throws(function () {
                types.quacksLike();
            });
        });

        test('quacksLike with two object arguments does not throw', function () {
            assert.doesNotThrow(function () {
                types.quacksLike({}, {});
            });
        });

        test('quacksLike with function first argument throws', function () {
            assert.throws(function () {
                types.quacksLike(function () {}, {});
            });
        });

        test('quacksLike with null first argument throws', function () {
            assert.throws(function () {
                types.quacksLike(null, {});
            });
        });

        test('quacksLike with function second argument throws', function () {
            assert.throws(function () {
                types.quacksLike({}, function () {});
            });
        });

        test('quacksLike with null second argument throws', function () {
            assert.throws(function () {
                types.quacksLike({}, null);
            });
        });

        test('quacksLike with two empty object arguments returns true', function () {
            assert.isTrue(types.quacksLike({}, {}));
        });

        test('quacksLike with foo bar properties returns false', function () {
            assert.isFalse(types.quacksLike({ foo: {} }, { bar: {} }));
        });

        test('quacksLike with foo foo properties returns true', function () {
            assert.isTrue(types.quacksLike({ foo: {} }, { foo: {} }));
        });

        test('quacksLike with bar baz second properties returns false', function () {
            assert.isFalse(types.quacksLike({ foo: {}, bar: {} }, { foo: {}, baz: {} }));
        });

        test('quacksLike with bar bar second properties returns true', function () {
            assert.isTrue(types.quacksLike({ foo: (function () {}), bar: {} }, { foo: (function () {}), bar: {} }));
        });

        test('quacksLike with differently typed bar bar second properties returns false', function () {
            assert.isFalse(types.quacksLike({ foo: (function () {}), bar: {} }, { foo: (function () {}), bar: (function () {}) }));
        });

        test('verifyInstance with new Error and Error does not throw', function () {
            assert.doesNotThrow(function () {
                types.verifyInstance(new Error(), Error);
            });
        });

        test('verifyInstance with object and Error throws', function () {
            assert.throws(function () {
                types.verifyInstance({}, Error);
            });
        });

        test('verifyInstance with null and null throws', function () {
            assert.throws(function () {
                types.verifyInstance(null, null);
            });
        });

        test('verifyInstance with object and Object does not throw', function () {
            assert.doesNotThrow(function () {
                types.verifyInstance({}, Object);
            });
        });

        test('verifyInstance with null and Object throws', function () {
            assert.throws(function () {
                types.verifyInstance(null, Object);
            });
        });

        test('verifyInstance with array and Array does not throw', function () {
            assert.doesNotThrow(function () {
                types.verifyInstance([], Array);
            });
        });

        test('verifyInstance with Object and object throws', function () {
            assert.throws(function () {
                types.verifyInstance(Object, {});
            });
        });

        test('isInstance function is defined', function () {
            assert.isFunction(types.isInstance);
        });

        test('isInstance with new Error and Error returns true', function () {
            assert.isTrue(types.isInstance(new Error(), Error));
        });

        test('isInstance with object and Error returns false', function () {
            assert.isFalse(types.isInstance({}, Error));
        });

        test('isInstance with null and null returns false', function () {
            assert.isFalse(types.isInstance(null, null));
        });

        test('isInstance with object and Object returns true', function () {
            assert.isTrue(types.isInstance({}, Object));
        });

        test('isInstance with null and Object returns false', function () {
            assert.isFalse(types.isInstance(null, Object));
        });

        test('isInstance with array and Array returns true', function () {
            assert.isTrue(types.isInstance([], Array));
        });

        test('isInstance with Object and object returns false', function () {
            assert.isFalse(types.isInstance(Object, {}));
        });

        test('verifyObject function is defined', function () {
            assert.isFunction(types.verifyObject);
        });

        test('verifyObject with object does not throw', function () {
            assert.doesNotThrow(function () {
                types.verifyObject({});
            });
        });

        test('verifyObject with null throws', function () {
            assert.throws(function () {
                types.verifyObject(null);
            });
        });

        test('verifyObject with string throws', function () {
            assert.throws(function () {
                types.verifyObject('[]');
            });
        });

        test('verifyObject with array throws', function () {
            assert.throws(function () {
                types.verifyObject([]);
            });
        });

        test('isObject function is defined', function () {
            assert.isFunction(types.isObject);
        });

        test('isObject with object returns true', function () {
            assert.isTrue(types.isObject({}));
        });

        test('isObject with null returns false', function () {
            assert.isFalse(types.isObject(null));
        });

        test('isObject with string returns false', function () {
            assert.isFalse(types.isObject('{}'));
        });

        test('isObject with array returns false', function () {
            assert.isFalse(types.isObject([]));
        });

        test('verifyArray function is defined', function () {
            assert.isFunction(types.verifyArray);
        });

        test('verifyArray with array does not throw', function () {
            assert.doesNotThrow(function () {
                types.verifyArray([]);
            });
        });

        test('verifyArray with null throws', function () {
            assert.throws(function () {
                types.verifyArray(null);
            });
        });

        test('verifyArray with string throws', function () {
            assert.throws(function () {
                types.verifyArray('[]');
            });
        });

        test('verifyArray with object throws', function () {
            assert.throws(function () {
                types.verifyArray({});
            });
        });

        test('isArray function is defined', function () {
            assert.isFunction(types.isArray);
        });

        test('isArray with array returns true', function () {
            assert.isTrue(types.isArray([]));
        });

        test('isArray with null returns false', function () {
            assert.isFalse(types.isArray(null));
        });

        test('isArray with string returns false', function () {
            assert.isFalse(types.isArray('[]'));
        });

        test('isArray with object returns false', function () {
            assert.isFalse(types.isArray({}));
        });

        test('verifyFunction function is defined', function () {
            assert.isFunction(types.verifyFunction);
        });

        test('verifyFunction with function does not throw', function () {
            assert.doesNotThrow(function () {
                types.verifyFunction(function () {});
            });
        });

        test('verifyFunction with null throws', function () {
            assert.throws(function () {
                types.verifyFunction(null);
            });
        });

        test('verifyFunction with string throws', function () {
            assert.throws(function () {
                types.verifyFunction('[]');
            });
        });

        test('verifyFunction with object throws', function () {
            assert.throws(function () {
                types.verifyFunction({});
            });
        });

        test('verifyFunction with array throws', function () {
            assert.throws(function () {
                types.verifyFunction([]);
            });
        });

        test('isFunction function is defined', function () {
            assert.isFunction(types.isFunction);
        });

        test('isFunction with function returns true', function () {
            assert.isTrue(types.isFunction(function () {}));
        });

        test('isFunction with null returns false', function () {
            assert.isFalse(types.isFunction(null));
        });

        test('isFunction with string returns false', function () {
            assert.isFalse(types.isFunction('function () {}'));
        });

        test('isFunction with object returns false', function () {
            assert.isFalse(types.isFunction({}));
        });

        test('isFunction with array returns false', function () {
            assert.isFalse(types.isFunction([]));
        });

        test('verifyUnemptyString function is defined', function () {
            assert.isFunction(types.verifyUnemptyString);
        });

        test('verifyUnemptyString with string baz does not throw', function () {
            assert.doesNotThrow(function () {
                types.verifyUnemptyString('baz');
            });
        });

        test('verifyUnemptyString with null throws', function () {
            assert.throws(function () {
                types.verifyUnemptyString(null);
            });
        });

        test('verifyUnemptyString with empty string throws', function () {
            assert.throws(function () {
                types.verifyUnemptyString('');
            });
        });

        test('verifyUnemptyString with object throws', function () {
            assert.throws(function () {
                types.verifyUnemptyString({});
            });
        });

        test('verifyUnemptyString with string qux does not throw', function () {
            assert.doesNotThrow(function () {
                types.verifyUnemptyString('qux');
            });
        });

        test('isUnemptyString function is defined', function () {
            assert.isFunction(types.isUnemptyString);
        });

        test('isUnemptyString with string foo returns true', function () {
            assert.isTrue(types.isUnemptyString('foo'));
        });

        test('isUnemptyString with null returns false', function () {
            assert.isFalse(types.isUnemptyString(null));
        });

        test('isUnemptyString with empty string returns false', function () {
            assert.isFalse(types.isUnemptyString(''));
        });

        test('isUnemptyString with object returns false', function () {
            assert.isFalse(types.isUnemptyString({}));
        });

        test('isUnemptyString with string bar returns true', function () {
            assert.isTrue(types.isUnemptyString('bar'));
        });

        test('verifyString function is defined', function () {
            assert.isFunction(types.verifyString);
        });

        test('verifyString with string baz does not throw', function () {
            assert.doesNotThrow(function () {
                types.verifyString('baz');
            });
        });

        test('verifyString with null throws', function () {
            assert.throws(function () {
                types.verifyString(null);
            });
        });

        test('verifyString with empty string does not throw', function () {
            assert.doesNotThrow(function () {
                types.verifyString('');
            });
        });

        test('verifyString with object throws', function () {
            assert.throws(function () {
                types.verifyString({});
            });
        });

        test('isString function is defined', function () {
            assert.isFunction(types.isString);
        });

        test('isString with string foo returns true', function () {
            assert.isTrue(types.isString('foo'));
        });

        test('isString with null returns false', function () {
            assert.isFalse(types.isString(null));
        });

        test('isString with empty string returns true', function () {
            assert.isTrue(types.isString(''));
        });

        test('isString with object returns false', function () {
            assert.isFalse(types.isString({}));
        });

        test('verifyNumber function is defined', function () {
            assert.isFunction(types.verifyNumber);
        });

        test('verifyNumber with whole number does not throw', function () {
            assert.doesNotThrow(function () {
                types.verifyNumber(1);
            });
        });

        test('verifyNumber with decimal number does not throw', function () {
            assert.doesNotThrow(function () {
                types.verifyNumber(1.2);
            });
        });

        test('verifyNumber with Infinity does not throw', function () {
            assert.doesNotThrow(function () {
                types.verifyNumber(Infinity);
            });
        });

        test('verifyNumber with NaN throws', function () {
            assert.throws(function () {
                types.verifyNumber(NaN);
            });
        });

        test('verifyNumber with null throws', function () {
            assert.throws(function () {
                types.verifyNumber(null);
            });
        });

        test('verifyNumber with object throws', function () {
            assert.throws(function () {
                types.verifyNumber({});
            });
        });

        test('verifyNumber with string zero throws', function () {
            assert.throws(function () {
                types.verifyNumber('0');
            });
        });

        test('verifyNumber with empty string throws', function () {
            assert.throws(function () {
                types.verifyNumber('');
            });
        });

        test('isNumber function is defined', function () {
            assert.isFunction(types.isNumber);
        });

        test('isNumber with whole number returns true', function () {
            assert.isTrue(types.isNumber(1));
        });

        test('isNumber with decimal number returns true', function () {
            assert.isTrue(types.isNumber(1.2));
        });

        test('isNumber with Infinity returns true', function () {
            assert.isTrue(types.isNumber(Infinity));
        });

        test('isNumber with NaN returns false', function () {
            assert.isFalse(types.isNumber(NaN));
        });

        test('isNumber with null returns false', function () {
            assert.isFalse(types.isNumber(null));
        });

        test('isNumber with object returns false', function () {
            assert.isFalse(types.isNumber({}));
        });

        test('isNumber with string zero returns false', function () {
            assert.isFalse(types.isNumber('0'));
        });

        test('isNumber with empty string returns false', function () {
            assert.isFalse(types.isNumber(''));
        });
    });
}());

<|endoftext|>


<commit_before>'use strict';

var crypto        = require('crypto');
var path          = require('path');
var fs            = require('fs');
var gutil         = require('gulp-util');
var through       = require('through2');
var objectAssign  = require('object-assign');
var file          = require('vinyl-file');

var PLUGIN_NAME   = 'gulp-rails-manifest';

function getHash(str) {
  return crypto.createHash('md5').update(str).digest('hex');
}

function transformFilename(file) {
  file.assetOrigPath  = file.path;
  var hash            = getHash(file.contents);
  var ext             = path.extname(file.path);
  var filename        = path.basename(file.path, ext) + '-' + hash + ext;
  file.path           = path.join(path.dirname(file.path), filename);
}

function addToManifest(manifest, oldName, file) {
  var name = file.path.replace(file.base, '');
  if (name.indexOf('/') == 0) name = name.slice(1);

  manifest.files[name] = {
    'logical_path': oldName,
    'mtime':        new Date(fs.statSync(file.assetOrigPath).mtime).toJSON(),
    'size':         file.contents.length,
    'digest':       getHash(file.contents)
  };
  manifest.assets[oldName] = name;
}

function mergeManifest(oldManifest, manifest) {
  var merged  = {};
  var files   = {};

  merged.assets = objectAssign(oldManifest.assets, manifest.assets);
  files         = objectAssign(oldManifest.files, manifest.files);

  // Remove old keys
  for (var file in files) {
    var key = files[file]['logical_path'];
    if (file != merged.assets[key]) delete files[file];
  }

  merged.files = files;

  return merged;
}

module.exports = function(opts) {
  var opts      = opts || {};
  var files     = {};
  var manifest  = {
    assets: {},
    files: {}
  };

  function processFile(file, enc, cb) {
    if (file.isStream()) {
      cb(new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
      return;
    }

    if (file.isNull() || !file.isBuffer()) {
      cb(null, file);
      return;
    }

    var oldName = file.path.replace(file.base, '');
    transformFilename(file);
    files[oldName] = file;

    cb(null, file);
  }

  function writeManifest(cb) {
    if (!opts.manifest) {
      cb(new gutil.PluginError(PLUGIN_NAME, 'Manifest path not specified'));
      return;
    }

    for (var file in files) addToManifest(manifest, file, files[file]);
    fs.writeFileSync(opts.manifest, JSON.stringify(manifest, null, '  '));
    cb();
  }

  return through.obj(processFile, writeManifest);
};
<commit_msg>A little refactoring<commit_after>'use strict';

var crypto        = require('crypto');
var path          = require('path');
var fs            = require('fs');
var gutil         = require('gulp-util');
var through       = require('through2');
var objectAssign  = require('object-assign');
var file          = require('vinyl-file');

var PLUGIN_NAME   = 'gulp-rails-manifest';

function getHash(str) {
  return crypto.createHash('md5').update(str).digest('hex');
}

function transformFilename(file) {
  file.assetOrigPath  = file.path;
  var hash            = getHash(file.contents);
  var ext             = path.extname(file.path);
  var filename        = path.basename(file.path, ext) + '-' + hash + ext;
  file.path           = path.join(path.dirname(file.path), filename);
}

function addToManifest(manifest, oldName, file) {
  var name = file.path.replace(file.base, '');
  if (name.indexOf('/') == 0) name = name.slice(1);

  manifest.files[name] = {
    'logical_path': oldName,
    'mtime':        new Date(fs.statSync(file.assetOrigPath).mtime).toJSON(),
    'size':         file.contents.length,
    'digest':       getHash(file.contents)
  };
  manifest.assets[oldName] = name;
}

function mergeManifest(oldManifest, manifest) {
  var merged  = {};
  var files   = {};

  merged.assets = objectAssign(oldManifest.assets, manifest.assets);
  files         = objectAssign(oldManifest.files, manifest.files);

  // Remove old keys
  for (var file in files) {
    var key = files[file]['logical_path'];
    if (file != merged.assets[key]) delete files[file];
  }

  merged.files = files;

  return merged;
}

module.exports = function(opts) {
  var opts  = opts || {};
  var files = {};

  function processFile(file, enc, cb) {
    if (file.isStream()) {
      cb(new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
      return;
    }

    if (file.isNull() || !file.isBuffer()) {
      cb(null, file);
      return;
    }

    var oldName = file.path.replace(file.base, '');
    transformFilename(file);
    files[oldName] = file;

    cb(null, file);
  }

  function writeManifest(cb) {
    if (!opts.manifest) {
      cb(new gutil.PluginError(PLUGIN_NAME, 'Manifest path not specified'));
      return;
    }

    var manifest = {assets: {}, files: {}};
    for (var file in files) addToManifest(manifest, file, files[file]);
    fs.writeFileSync(opts.manifest, JSON.stringify(manifest, null, '  '));

    cb();
  }

  return through.obj(processFile, writeManifest);
};
<|endoftext|>