<commit_before>var should    = require("should"),
    index     = require("../lib"),
    Publish   = require("../lib/Publish"),
    Subscribe = require("../lib/Subscribe"),
    Group     = require("../lib/Group");

describe("lib/index", function () {
  describe(".errors", function () {
    it("should be an object of error constructors", function () {
      index.errors.should.be.Object;
      index.errors.ContextError.should.be.Function;
    });
  });

  describe(".addError", function () {
    var errorName = "TestError",
        onlyName  = "BadError",
        protoName = "ProtoErrorTest",
        ErrClass  = function () {},
        test;

    index.addError(errorName, ErrClass);
    index.addError(onlyName);
    index.addError(protoName, ErrClass, index.errors.ContextError);
    test = new index.errors[protoName]("default message");

    it("should exist and be a function", function () {
      index.addError.should.be.a.Function;
    });

    it("should not add to .errors if function not given", function () {
      (typeof index.errors[onlyName] === "undefined").should.be.true;
    });

    it("should add the constructor to .errors", function () {
      index.errors[errorName].should.be.a.Function;
    });

    it("should extend the prototype constructor if given one", function () {
      test.should.be.instanceof( index.errors.ContextError );
      test.should.be.instanceof( ErrClass );
    });

    it("should add .type to specify it's constructor's name", function () {
      test.type.should.be.equal(protoName);
    });

    it("should add .failedOn property, initially set to null", function () {
      (test.failedOn === null).should.be.true;
    });
  });

  describe(".subscribe", function () {
    it("should return a new instance of Subscribe", function () {
      index.subscribe().should.be.instanceOf(Subscribe);
    });
    it("should pass on arguments to Subscribe", function () {
      index.subscribe("event:1", "event:2")._sub.eventNames.should.containDeep(["event:1", "event:2"]);
    });
  });

  describe(".group", function () {
    it("should return a new instance of GroupSubscribe", function () {
      index.group().should.be.instanceOf(Group);
    });
    it("should pass on arguments to GroupSubscribe", function () {
      index.group("event:1", "event:2")._group.eventNames.should.containDeep(["event:1", "event:2"]);
    });
  });

  describe(".publish", function () {
    it("should return a new instance of Publish", function () {
      index.publish().should.be.instanceOf(Publish);
    });
    it("should pass on arguments to Publish", function () {
      var name  = "event",
          cxt   = {count:0},
          count = 0,
          pub;

      index.subscribe(name).then(function () {
        // how many times the function has been invoked
        count++;
        // how many times the function has been invoked with a context
        if (typeof this.count === "number") {
          this.count++;
        }
      });

      pub = index.publish(name, cxt, name);

      count.should.equal(2);
      pub._cxt.count.should.equal(1);
    });
  });
});<commit_msg>updated .addError test to include grandparent instanceof<commit_after>var should    = require("should"),
    index     = require("../lib"),
    Publish   = require("../lib/Publish"),
    Subscribe = require("../lib/Subscribe"),
    Group     = require("../lib/Group");

describe("lib/index", function () {
  describe(".errors", function () {
    it("should be an object of error constructors", function () {
      index.errors.should.be.Object;
      index.errors.ContextError.should.be.Function;
    });
  });

  describe(".addError", function () {
    var errorName = "TestError",
        onlyName  = "BadError",
        protoName = "ProtoErrorTest",
        ErrClass  = function () {},
        test;

    index.addError(errorName, ErrClass);
    index.addError(onlyName);
    index.addError(protoName, ErrClass, index.errors.ContextError);
    test = new index.errors[protoName]("default message");

    it("should exist and be a function", function () {
      index.addError.should.be.a.Function;
    });

    it("should not add to .errors if function not given", function () {
      (typeof index.errors[onlyName] === "undefined").should.be.true;
    });

    it("should add the constructor to .errors", function () {
      index.errors[errorName].should.be.a.Function;
    });

    it("should extend the prototype constructor if given one", function () {
      test.should.be.instanceof( index.errors.ContextError );
      test.should.be.instanceof( ErrClass );
      test.should.be.instanceof( Error );
    });

    it("should add .type to specify it's constructor's name", function () {
      test.type.should.be.equal(protoName);
    });

    it("should add .failedOn property, initially set to null", function () {
      (test.failedOn === null).should.be.true;
    });
  });

  describe(".subscribe", function () {
    it("should return a new instance of Subscribe", function () {
      index.subscribe().should.be.instanceOf(Subscribe);
    });
    it("should pass on arguments to Subscribe", function () {
      index.subscribe("event:1", "event:2")._sub.eventNames.should.containDeep(["event:1", "event:2"]);
    });
  });

  describe(".group", function () {
    it("should return a new instance of GroupSubscribe", function () {
      index.group().should.be.instanceOf(Group);
    });
    it("should pass on arguments to GroupSubscribe", function () {
      index.group("event:1", "event:2")._group.eventNames.should.containDeep(["event:1", "event:2"]);
    });
  });

  describe(".publish", function () {
    it("should return a new instance of Publish", function () {
      index.publish().should.be.instanceOf(Publish);
    });
    it("should pass on arguments to Publish", function () {
      var name  = "event",
          cxt   = {count:0},
          count = 0,
          pub;

      index.subscribe(name).then(function () {
        // how many times the function has been invoked
        count++;
        // how many times the function has been invoked with a context
        if (typeof this.count === "number") {
          this.count++;
        }
      });

      pub = index.publish(name, cxt, name);

      count.should.equal(2);
      pub._cxt.count.should.equal(1);
    });
  });
});<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');
var vm = require('vm');
var fs = require('fs');
var path = require('path');

var spawnFile = require.resolve('../');
var spawnSource = fs.readFileSync(spawnFile, 'utf8');

function testSpawn(spawn) {
  var result = spawn("node", [__dirname + '/test-spawn.js'], {input: 'my-output'});
  if (result.exitCode !== 0) {
    console.error(result.stderr.toString());
    process.exit(result.exitCode);
  }
  assert(result.exitCode === 0);
  assert(Buffer.isBuffer(result.stdout));
  assert(Buffer.isBuffer(result.stderr));
  assert(result.stdout.toString() === 'output written');
  assert(result.stderr.toString() === 'error log exists');
  assert(fs.readFileSync(__dirname + '/output.txt', 'utf8') === 'my-output');
  fs.unlinkSync(__dirname + '/output.txt');
  console.log('test pass');
}

var resolve = require.resolve;
function getSpawn(require) {
  require.resolve = resolve;
  var exports = {};
  var context = {
    module: exports,
    exports: exports,
    require: require,
    __dirname: path.dirname(spawnFile),
    console: console,
    process: process
  };
  vm.runInNewContext(spawnSource, context, spawnFile);
  return context.module.exports
}

console.log('# Test native operation');
testSpawn(getSpawn(function (path) {
  if (path === 'child_process') {
    require('execSync');
    throw new Error('child_process shouldn\'t be needed when ffi is available');
  }
  return require(path);
}));

console.log('# Test fallback operation');
testSpawn(getSpawn(function (path) {
  if (path === 'execSync') {
    throw new Error('execSync isn\'t always available');
  }
  return require(path);
}));
<commit_msg>Update tests for 0.11<commit_after>'use strict';

var assert = require('assert');
var vm = require('vm');
var fs = require('fs');
var path = require('path');

var spawnFile = require.resolve('../');
var spawnSource = fs.readFileSync(spawnFile, 'utf8');

function testSpawn(spawn) {
  var result = spawn("node", [__dirname + '/test-spawn.js'], {input: 'my-output'});
  if (result.exitCode !== 0) {
    console.error(result.stderr.toString());
    process.exit(result.exitCode);
  }
  assert(result.exitCode === 0);
  assert(Buffer.isBuffer(result.stdout));
  assert(Buffer.isBuffer(result.stderr));
  assert(result.stdout.toString() === 'output written');
  assert(result.stderr.toString() === 'error log exists');
  assert(fs.readFileSync(__dirname + '/output.txt', 'utf8') === 'my-output');
  fs.unlinkSync(__dirname + '/output.txt');
  console.log('test pass');
}

var resolve = require.resolve;
function getSpawn(require) {
  require.resolve = resolve;
  var exports = {};
  var context = {
    module: exports,
    exports: exports,
    require: require,
    __dirname: path.dirname(spawnFile),
    console: console,
    process: process
  };
  vm.runInNewContext(spawnSource, context, spawnFile);
  return context.module.exports
}

var execSyncAvailable;
try {
  require('execSync');
  execSyncAvailable = true;
} catch (ex) {
  execSyncAvailable = false;
}
if (execSyncAvailable) {
  console.log('# Test native operation');
  testSpawn(getSpawn(function (path) {
    if (path === 'child_process') {
      require('execSync');
      throw new Error('child_process shouldn\'t be needed when ffi is available');
    }
    return require(path);
  }));
} else {
  console.log('# SKIP Test native operation');
}

console.log('# Test fallback operation');
testSpawn(getSpawn(function (path) {
  if (path === 'execSync') {
    throw new Error('execSync isn\'t always available');
  }
  return require(path);
}));
<|endoftext|>


<commit_before>var hapiTest = require('hapi-test')
var Hapi = require('Hapi')
var assert = require('chai').assert
var should = require('chai').should()
var fs = require('fs')

var server = require('../server')

describe("Server Initiation", function(){
  it('Root server can be accessed', function (done) {
      hapiTest({server: server})
          .get('/')
          .assert(200, done)
  })
  it('Root should return the api version number', function(done) {
    hapiTest({server: server})
      .get('/')
      .end(function(result){
        assert.equal(result.payload, "MMA:TCG version: 0.0.1", "call to root returns correct version number")
        done()
    })
  })
})

describe('New Game', function(){
  describe('Get initial deck', function(){
    it('should return a deck array with 3 cards', function(done){
      var expectedDeckJson = fs.readFileSync('../data/deck.json', 'utf8')
        hapiTest({server: server})
          .get('/new')
          .end(function(result){
            //assert.deepEqual(result.payload, expectedDeckJson, 'Api call to /new gives a 3 card deck')
            //console.log(result.payload)
            done()
          })
    })
  })
})

describe('Round', function(){
  describe('One round', function(){
    it('should take a card and return a bout score', function(done){
      hapiTest({server: server})
        .post('/round')
        .send({"name": "Fighter One", "img": "test.jpg" ,"rating": 100})
        .end(function(result){
          console.log(result)
          done()
        })

    })
    it('it should return -1 if the card is invalid')
  })
})

describe('Bout', function(){
  describe('One bout', function(){
    it('should return a winner when the bout is complete')
  })
})
<commit_msg>added test for round<commit_after>var hapiTest = require('hapi-test')
var Hapi = require('Hapi')
var assert = require('chai').assert
var should = require('chai').should()
var fs = require('fs')

var server = require('../server')

describe("Server Initiation", function(){
  it('Root server can be accessed', function (done) {
      hapiTest({server: server})
          .get('/')
          .assert(200, done)
  })
  it('Root should return the api version number', function(done) {
    hapiTest({server: server})
      .get('/')
      .end(function(result){
        assert.equal(result.payload, "MMA:TCG version: 0.0.1", "call to root returns correct version number")
        done()
    })
  })
})

describe('New Game', function(){
  describe('Get initial deck', function(){
    it('should return a deck array with 3 cards', function(done){
      var expectedDeckJson = fs.readFileSync('../data/deck.json', 'utf8')
        hapiTest({server: server})
          .get('/new')
          .end(function(result){
            assert.deepEqual(result.payload, expectedDeckJson, 'Api call to /new gives a 3 card deck')
            done()
          })
    })
  })
})

describe('Round', function(){
  describe('One round', function(){
    it('should take a card and return a bout score', function(done){
      hapiTest({server: server})
        .post('/round', {"name": "Fighter One", "img": "test.jpg" ,"rating": 100})
        .end(function(result){
          console.log(result)
          var scoreObject = result.payload
          var score = scoreObject.playerOne + scoreObject.playerTwo
          assert.equal(score, 1)
          done()
        })

    })
    it('it should return -1 if the card is invalid')
  })
})

describe('Bout', function(){
  describe('One bout', function(){
    it('should return a winner when the bout is complete')
  })
})
<|endoftext|>


<commit_before>import assert from 'assert'
import { map } from 'lodash'
import Promise, { join } from 'bluebird'
import mongoose, { Schema } from 'mongoose'
import patchHistory from '../src'

const CommentSchema = new Schema({ text: String })
CommentSchema.virtual('user').set(function (user) {
  this._user = user
})
CommentSchema.plugin(patchHistory, {
  mongoose,
  name: 'commentPatches',
  removePatches: false,
  includes: {
    user: {
      type: Schema.Types.ObjectId,
      required: true,
      from: '_user'
    }
  }
})

const PostSchema = new Schema({ title: String })
PostSchema.plugin(patchHistory, { mongoose,
  name: 'postPatches',
  transforms: [
    (name) => name.toLowerCase(),
    () => 'post_history'
  ]
})

describe('mongoose-patch-history', () => {
  let Comment, Post, User

  before((done) => {
    Comment = mongoose.model('Comment', CommentSchema)
    Post = mongoose.model('Post', PostSchema)
    User = mongoose.model('User', new Schema())

    mongoose.connect('mongodb://localhost/mongoose-patch-history', () => {
      join(
        Comment.remove(),
        Comment.PatchModel.remove(),
        Post.remove(),
        User.remove()
      )
      .then(() => User.create())
      .then(() => done())
    })
  })

  describe('initialization', () => {
    const name = 'testPatches'
    let TestSchema

    before(() => {
      TestSchema = new Schema()
    })

    it('throws when `mongoose` option is not defined', () => {
      assert.throws(() => TestSchema.plugin(patchHistory, { name }))
    })

    it('throws when `name` option is not defined', () => {
      assert.throws(() => TestSchema.plugin(patchHistory, { mongoose }))
    })

    it('throws when `data` instance method exists', () => {
      const DataSchema = new Schema()
      DataSchema.methods.data = () => {}
      assert.throws(() => DataSchema.plugin(patchHistory, { mongoose, name }))
    })

    it('does not throw with valid parameters', () => {
      assert.doesNotThrow(() => TestSchema.plugin(patchHistory, { mongoose, name }))
    })
  })

  describe('saving a new document', () => {
    it('adds a patch', (done) => {
      join(
        // without referenced user
        Post.create({ title: 'foo' })
          .then((post) => post.patches.find({ ref: post.id }))
          .then((patches) => {
            assert.equal(patches.length, 1)
            assert.deepEqual(patches[0].ops, [
              { value: 'foo', path: '/title', op: 'add' }
            ])
          }),
        // with referenced user
        User.findOne()
          .then((user) => Comment.create({ text: 'wat', user: mongoose.Types.ObjectId() }))
          .then((comment) => comment.patches.find({ ref: comment.id }))
          .then((patches) => {
            assert.equal(patches.length, 1)
            assert.deepEqual(patches[0].ops, [
              { value: 'wat', path: '/text', op: 'add' }
            ])
          })
      ).then(() => done()).catch(done)
    })
  })

  describe('saving an existing document', () => {
    it('with changes: adds a patch', (done) => {
      Post.findOne({ title: 'foo' })
        .then((post) => post.set({ title: 'bar' }).save())
        .then((post) => post.patches.find({ ref: post.id }).sort({ _id: 1 }))
        .then((patches) => {
          assert.equal(patches.length, 2)
          assert.deepEqual(patches[1].ops, [
            { value: 'bar', path: '/title', op: 'replace' }
          ])
        }).then(done).catch(done)
    })

    it('without changes: doesn`t add a patch', (done) => {
      Post.create({ title: 'baz' })
        .then((post) => post.save())
        .then((post) => post.patches.find({ ref: post.id }))
        .then((patches) => {
          assert.equal(patches.length, 1)
        }).then(done).catch(done)
    })
  })

  describe('removing a document', () => {
    it('removes all patches', (done) => {
      Post.findOne({ title: 'bar' })
        .then((post) => post.remove())
        .then((post) => post.patches.find({ ref: post.id }))
        .then((patches) => {
          assert.equal(patches.length, 0)
        }).then(done).catch(done)
    })
    it('doesn\'t remove patches when `removePatches` is false', (done) => {
      Comment.findOne({ text: 'wat' })
        .then((comment) => comment.remove())
        .then((comment) => comment.patches.find({ ref: comment.id }))
        .then((patches) => {
          assert.equal(patches.length, 1)
        }).then(done).catch(done)
    })
  })

  describe('model and collection names', () => {
    const getCollectionNames = () => {
      return new Promise((resolve, reject) => {
        mongoose.connection.db.listCollections().toArray((err, collections) => {
          if (err) return reject(err)
          resolve(map(collections, 'name'))
        })
      })
    }

    it('pascalize for model and decamelize for collection', (done) => {
      join(
        () => assert.ok(!!~mongoose.modelNames().indexOf('CommentPatches')),
        getCollectionNames().then((names) => {
          assert.ok(!!~names.indexOf('comment_patches'))
        })
      ).then(() => done()).catch(done)
    })

    it('uses `transform` option when set', (done) => {
      join(
        () => assert.ok(!!~mongoose.modelNames().indexOf('postpatches')),
        getCollectionNames().then((names) => {
          assert.ok(!!~names.indexOf('post_history'))
        })
      ).then(() => done()).catch(done)
    })
  })
})
<commit_msg>Improve coverage<commit_after>import assert from 'assert'
import { map } from 'lodash'
import Promise, { join } from 'bluebird'
import mongoose, { Schema } from 'mongoose'
import patchHistory from '../src'

const CommentSchema = new Schema({ text: String })
CommentSchema.virtual('user').set(function (user) {
  this._user = user
})
CommentSchema.plugin(patchHistory, {
  mongoose,
  name: 'commentPatches',
  removePatches: false,
  includes: {
    text: {
      type: String
    },
    user: {
      type: Schema.Types.ObjectId,
      required: true,
      from: '_user'
    }
  }
})

const PostSchema = new Schema({ title: String })
PostSchema.plugin(patchHistory, { mongoose,
  name: 'postPatches',
  transforms: [
    (name) => name.toLowerCase(),
    () => 'post_history'
  ]
})

describe('mongoose-patch-history', () => {
  let Comment, Post, User

  before((done) => {
    Comment = mongoose.model('Comment', CommentSchema)
    Post = mongoose.model('Post', PostSchema)
    User = mongoose.model('User', new Schema())

    mongoose.connect('mongodb://localhost/mongoose-patch-history', () => {
      join(
        Comment.remove(),
        Comment.PatchModel.remove(),
        Post.remove(),
        User.remove()
      )
      .then(() => User.create())
      .then(() => done())
    })
  })

  describe('initialization', () => {
    const name = 'testPatches'
    let TestSchema

    before(() => {
      TestSchema = new Schema()
    })

    it('throws when `mongoose` option is not defined', () => {
      assert.throws(() => TestSchema.plugin(patchHistory, { name }))
    })

    it('throws when `name` option is not defined', () => {
      assert.throws(() => TestSchema.plugin(patchHistory, { mongoose }))
    })

    it('throws when `data` instance method exists', () => {
      const DataSchema = new Schema()
      DataSchema.methods.data = () => {}
      assert.throws(() => DataSchema.plugin(patchHistory, { mongoose, name }))
    })

    it('does not throw with valid parameters', () => {
      assert.doesNotThrow(() => TestSchema.plugin(patchHistory, { mongoose, name }))
    })
  })

  describe('saving a new document', () => {
    it('adds a patch', (done) => {
      join(
        // without referenced user
        Post.create({ title: 'foo' })
          .then((post) => post.patches.find({ ref: post.id }))
          .then((patches) => {
            assert.equal(patches.length, 1)
            assert.deepEqual(patches[0].ops, [
              { value: 'foo', path: '/title', op: 'add' }
            ])
          }),
        // with referenced user
        User.findOne()
          .then((user) => Comment.create({ text: 'wat', user: mongoose.Types.ObjectId() }))
          .then((comment) => comment.patches.find({ ref: comment.id }))
          .then((patches) => {
            assert.equal(patches.length, 1)
            assert.deepEqual(patches[0].ops, [
              { value: 'wat', path: '/text', op: 'add' }
            ])
          })
      ).then(() => done()).catch(done)
    })
  })

  describe('saving an existing document', () => {
    it('with changes: adds a patch', (done) => {
      Post.findOne({ title: 'foo' })
        .then((post) => post.set({ title: 'bar' }).save())
        .then((post) => post.patches.find({ ref: post.id }).sort({ _id: 1 }))
        .then((patches) => {
          assert.equal(patches.length, 2)
          assert.deepEqual(patches[1].ops, [
            { value: 'bar', path: '/title', op: 'replace' }
          ])
        }).then(done).catch(done)
    })

    it('without changes: doesn`t add a patch', (done) => {
      Post.create({ title: 'baz' })
        .then((post) => post.save())
        .then((post) => post.patches.find({ ref: post.id }))
        .then((patches) => {
          assert.equal(patches.length, 1)
        }).then(done).catch(done)
    })
  })

  describe('removing a document', () => {
    it('removes all patches', (done) => {
      Post.findOne({ title: 'bar' })
        .then((post) => post.remove())
        .then((post) => post.patches.find({ ref: post.id }))
        .then((patches) => {
          assert.equal(patches.length, 0)
        }).then(done).catch(done)
    })
    it('doesn\'t remove patches when `removePatches` is false', (done) => {
      Comment.findOne({ text: 'wat' })
        .then((comment) => comment.remove())
        .then((comment) => comment.patches.find({ ref: comment.id }))
        .then((patches) => {
          assert.equal(patches.length, 1)
        }).then(done).catch(done)
    })
  })

  describe('model and collection names', () => {
    const getCollectionNames = () => {
      return new Promise((resolve, reject) => {
        mongoose.connection.db.listCollections().toArray((err, collections) => {
          if (err) return reject(err)
          resolve(map(collections, 'name'))
        })
      })
    }

    it('pascalize for model and decamelize for collection', (done) => {
      join(
        () => assert.ok(!!~mongoose.modelNames().indexOf('CommentPatches')),
        getCollectionNames().then((names) => {
          assert.ok(!!~names.indexOf('comment_patches'))
        })
      ).then(() => done()).catch(done)
    })

    it('uses `transform` option when set', (done) => {
      join(
        () => assert.ok(!!~mongoose.modelNames().indexOf('postpatches')),
        getCollectionNames().then((names) => {
          assert.ok(!!~names.indexOf('post_history'))
        })
      ).then(() => done()).catch(done)
    })
  })
})
<|endoftext|>


<commit_before>var Timer = require('../lib/timer');
var expect = require('expect.js');

suite('timer.js', function(){
  var timer;

  suite('#constructor', function(){
    test('proper initialization', function(){
      expect(function(){
        timer = new Timer();
      }).not.to.throwException();
    });

    test('expected attributes', function(){
      expect(timer.currentDuration).to.be(0);
      expect(timer.initialDuration).to.be(0);
    });
  });

  suite('#on', function(){
    test('basics', function(){
      expect(timer.events).to.be.an('object');
      expect(timer.events).to.be.empty();
    });

    test('assigning functions', function(){
      expect(function(){
        timer.on('stuff', function doStuff(){
          return 'stuffDone';
        });
      }).not.to.throwException(TypeError);

      timer.on('stuff', function doStuff2(){});
      timer.on('interval', function doInterval(){});

      expect(timer.events.stuff.length).to.be(2);
      expect(timer.events.stuff[0]()).to.be('stuffDone');
      expect(timer.events.interval.length).to.be(1);
    });
  });

  suite('#emits', function(){

  });

  suite('#on', function(){

  });

  suite('#start', function(){

  });

  suite('#pause', function(){

  });

  suite('#reset', function(){

  });

  suite('#stop', function(){

  });

  suite('#toggle', function(){

  });

  suite('#setDuration', function(){

  });

  suite('#onInterval', function(){

  });

  suite('#sanitizeDuration', function(){

  });
});<commit_msg>`.emit` method<commit_after>var Timer = require('../lib/timer');
var expect = require('expect.js');

suite('timer.js', function(){
  var timer;

  suite('#constructor', function(){
    test('proper initialization', function(){
      expect(function(){
        timer = new Timer();
      }).not.to.throwException();
    });

    test('expected attributes', function(){
      expect(timer.currentDuration).to.be(0);
      expect(timer.initialDuration).to.be(0);
    });
  });

  suite('#on', function(){
    test('basics', function(){
      expect(timer.events).to.be.an('object');
      expect(timer.events).to.be.empty();
    });

    test('assigning functions', function(){
      expect(function(){
        timer.on('stuff', function doStuff(){
          return 'stuffDone';
        });
      }).not.to.throwException(TypeError);

      timer.on('stuff', function doStuff2(){});
      timer.on('interval', function doInterval(){});

      expect(timer.events.stuff.length).to.be(2);
      expect(timer.events.stuff[0]()).to.be('stuffDone');
      expect(timer.events.interval.length).to.be(1);
    });
  });

  suite('#emits', function(){
    test('existing event', function(done){
      timer = new Timer();

      timer.on('interval', function(){
        expect(timer.events.interval.length).to.be(1);
        done();
      });

      timer.emit('interval');
    });

    test('unexisting event', function(){
      expect(function(){
        timer.emit('foobar');
      }).not.to.throwException();
    });
  });

  suite('#start', function(){

  });

  suite('#pause', function(){

  });

  suite('#reset', function(){

  });

  suite('#stop', function(){

  });

  suite('#toggle', function(){

  });

  suite('#setDuration', function(){

  });

  suite('#onInterval', function(){

  });

  suite('#sanitizeDuration', function(){

  });
});<|endoftext|>


<commit_before>var request = require('supertest');
var logger = require('../superagent-logger');

function doPost(endpoint, method, body, callback, forceQuerystring) {
    var useQuerystring = forceQuerystring || process.env.PREFER_QUERYSTRING;
    var req = request(endpoint).post(method);

    if (body) {
        if (useQuerystring) {
            req.query(body);
        }
        else {
            req.set('Content-Type', 'application/json');
            req.send(body);
        }
    }

    if (process.env.VERBOSE_HTTP)
        req.use(logger({outgoing: true}));

    req.end(function(err, response) {
        if (err) return callback(err);
        if (response.text && (!response.body || !Object.keys(response.body).length)) {
            response.body = JSON.parse(response.text);
        }
        callback(null, response.body);
    });
}

exports.post = doPost;

exports.get = function(endpoint, method, body, callback) {
    if (process.env.POST_ALWAYS)
        return doPost(endpoint, method, body, callback, true);

    var req = request(endpoint).get(method);

    if (body) {
        req.query(body);
    }
    // No request body on gets!

    if (process.env.VERBOSE_HTTP)
        req.use(logger({outgoing: true}));

    req.end(function(err, response) {
        if (err) return callback(err);
        if (response.text && (!response.body || !Object.keys(response.body).length)) {
            response.body = JSON.parse(response.text);
        }
        callback(null, response.body);
    });
}

<commit_msg>- utils.js Changes<commit_after>var request = require('supertest');
var logger = require('../superagent-logger');
var qs = require('qs');

function doPost(endpoint, method, body, callback, forceQuerystring) {
    var useQuerystring = forceQuerystring || process.env.PREFER_QUERYSTRING;
    var req = request(endpoint).post(method);

    if (body) {
        if (useQuerystring) {
            req.query(qs.stringify(body));
        }
        else {
            req.set('Content-Type', 'application/json');
            req.send(body);
        }
    }

    if (process.env.VERBOSE_HTTP)
        req.use(logger({outgoing: true}));

    req.end(function(err, response) {
        if (err) return callback(err);
        if (response.text && (!response.body || !Object.keys(response.body).length)) {
            response.body = JSON.parse(response.text);
        }
        callback(null, response.body);
    });
}

exports.post = doPost;

exports.get = function(endpoint, method, body, callback) {
    if (process.env.POST_ALWAYS)
        return doPost(endpoint, method, body, callback, true);

    var req = request(endpoint).get(method);

    if (body) {
        req.query(body);
    }
    // No request body on gets!

    if (process.env.VERBOSE_HTTP)
        req.use(logger({outgoing: true}));

    req.end(function(err, response) {
        if (err) return callback(err);
        if (response.text && (!response.body || !Object.keys(response.body).length)) {
            response.body = JSON.parse(response.text);
        }
        callback(null, response.body);
    });
}

<|endoftext|>


<commit_before>/*global describe, it, beforeEach, afterEach*/
var expect = require('unexpected');

describe('inter', function () {
    var inter = require('../build/en_us');

    describe('#renderDate()', function () {
        var d = new Date(2013, 11, 6, 10, 54, 10);

        it('should format a date according to the mediumDateTime format', function () {
            expect(inter.renderDate(d, 'mediumDateTime'), 'to equal', 'Dec 6, 2013, 10:54:10 am');
        });

        it('should use the fullDateTime format if the formatId parameter is omitted', function () {
            var timeZoneOffsetStr = d.toTimeString().match(/GMT([-+]\d\d\d\d)/)[1].replace(/(\d\d)$/, ':$1');
            expect(inter.renderDate(d), 'to equal', 'Friday, December 6, 2013 at 10:54:10 am ' + timeZoneOffsetStr);
        });

        describe('with a negative time zone offset (GMT-02:00)', function () {
            var originalGetTimezoneOffset = Date.prototype.getTimezoneOffset;
            beforeEach(function () {
                Date.prototype.getTimezoneOffset = function () {
                    return 120; // This is a bit of a wtf, I would expect it to return -120, but it doesn't
                };
            });
            afterEach(function () {
                Date.prototype.getTimezoneOffset = originalGetTimezoneOffset;
            });

            it('should render the time zone offset correctly', function () {
                expect(inter.renderDate(new Date(2016, 0, 15, 11, 30), 'fullDateTime'), 'to equal', 'Friday, January 15, 2016 at 11:30:00 am -02:00');
            });
        });

        describe('with a positive time zone offset (GMT+02:00)', function () {
            var originalGetTimezoneOffset = Date.prototype.getTimezoneOffset;
            beforeEach(function () {
                Date.prototype.getTimezoneOffset = function () {
                    return -120; // This is a bit of a wtf, I would expect it to return 120, but it doesn't
                };
            });
            afterEach(function () {
                Date.prototype.getTimezoneOffset = originalGetTimezoneOffset;
            });

            it('should render the time zone offset correctly', function () {
                expect(inter.renderDate(new Date(2016, 0, 15, 11, 30), 'fullDateTime'), 'to equal', 'Friday, January 15, 2016 at 11:30:00 am +02:00');
            });
        });

        it('should accept a number (epoch milliseconds) instead of a Date instance', function () {
            expect(inter.renderDate(5000, 'shortDate'), 'to equal', '1/1/1970');
        });

        it('should accept a parsable date string instead of a Date instance', function () {
            expect(inter.renderDate('Nov 18 2014 18:00', 'shortDate'), 'to equal', '11/18/2014');
        });

        it('should use the regular month format when using the L format character', function () {
            expect(require('../build/fi').renderDateFormat(new Date('Nov 18 2014 18:00'), 'MMMM'), 'to equal', 'marraskuuta');
        });

        it('should use the standalone month format when using the L format character', function () {
            expect(require('../build/fi').renderDateFormat(new Date('Nov 18 2014 18:00'), 'LLLL'), 'to equal', 'marraskuu');
        });
    });

    describe('#renderList()', function () {
        it('should should render a list according to the unitNarrow pattern', function () {
            expect(inter.renderList(['foo', 'bar', 'quux'], 'unitNarrow'), 'to equal', 'foo bar quux');
        });

        it('should use the default format when the type parameter is omitted', function () {
            expect(inter.renderList(['foo', 'bar', 'quux']), 'to equal', 'foo, bar, and quux');
        });
    });

    describe('#renderNumber', function () {
        it('should render a number in the Indian English locale (#11)', function () {
            expect(require('../build/en_in').renderNumber(10000000.23), 'to equal', '10,000,000.23');
        });

        it('should render a number in the Danish locale (#11)', function () {
            expect(require('../build/da').renderNumber(10000000.23), 'to equal', '10.000.000,23');
        });
    });

    describe('#renderPercentage', function () {
        it('should accept the number of decimals as the second parameter', function () {
            expect(require('../build/da').renderPercentage(12.345678, 2), 'to equal', '1.234,57\xa0%');
        });

        it('should accept the number system as the third parameter', function () {
            expect(require('../build/da').renderPercentage(12.345678, 2, 'mlym'), 'to equal', '൧.൨൩൪,൫൭\xa0%');
        });
    });

    describe('#renderUnit', function () {
        it('should render a singular number of units', function () {
            expect(inter.renderUnit(1, 'durationWeek'), 'to equal', '1 week');
        });

        it('should render a plural number of units', function () {
            expect(inter.renderUnit(2, 'durationWeek'), 'to equal', '2 weeks');
        });

        it('should render in the narrow format', function () {
            expect(inter.renderUnit(1, 'durationWeek', 'narrow'), 'to equal', '1w');
        });
    });

    describe('#renderCurrencyShort', function () {
        it('should render a float with a currency', function () {
            expect(inter.renderCurrencyShort(134.40, 'USD'), 'to equal', '$134.40');
        });

        it('should render a float with a currency, with a different amount of decimals', function () {
            expect(inter.renderCurrencyShort(134.40, 'USD', 'latn', 1), 'to equal', '$134.4');
        });

        it('should render a number in the Dutch locale', function () {
            expect(require('../build/nl').renderCurrencyShort(134.40, 'EUR'), 'to equal', '€ 134,40');
        });
    });

    describe('#renderCurrencyLong', function () {
        it('should render a float with a currency', function () {
            expect(inter.renderCurrencyLong(134.40, 'USD'), 'to equal', 'USD\xa0134.40');
        });

        it('should render a float with a currency, with a different amount of decimals', function () {
            expect(inter.renderCurrencyLong(134.40, 'USD', 'latn', 1), 'to equal', 'USD\xa0134.4');
        });

        it('should render a number in the Dutch locale', function () {
            expect(require('../build/nl').renderCurrencyLong(134.40, 'EUR'), 'to equal', 'EUR\xa0134,40');
        });
    });

    describe('#makeUnitRenderer', function () {
        it('should render in the narrow format', function () {
            expect(inter.makeUnitRenderer('durationWeek', 'narrow')(1), 'to equal', '1w');
        });
    });

    describe('#adaptICUFormat', function () {
        it('should adapt a pattern that uses L correctly when the format id uses M', function () {
            expect(require('../build/fi').adaptICUFormat('LLL', 'MMMM'), 'to equal', 'LLLL');
        });
    });
});
<commit_msg>Fixed test when invoked west of GMT+00:00 (Travis).<commit_after>/*global describe, it, beforeEach, afterEach*/
var expect = require('unexpected');

describe('inter', function () {
    var inter = require('../build/en_us');

    describe('#renderDate()', function () {
        var d = new Date(2013, 11, 6, 10, 54, 10);

        it('should format a date according to the mediumDateTime format', function () {
            expect(inter.renderDate(d, 'mediumDateTime'), 'to equal', 'Dec 6, 2013, 10:54:10 am');
        });

        it('should use the fullDateTime format if the formatId parameter is omitted', function () {
            expect(inter.renderDate(d), 'to match', /^Friday, December 6, 2013 at 10:54:10 am [+-]/);
        });

        describe('with a negative time zone offset (GMT-02:00)', function () {
            var originalGetTimezoneOffset = Date.prototype.getTimezoneOffset;
            beforeEach(function () {
                Date.prototype.getTimezoneOffset = function () {
                    return 120; // This is a bit of a wtf, I would expect it to return -120, but it doesn't
                };
            });
            afterEach(function () {
                Date.prototype.getTimezoneOffset = originalGetTimezoneOffset;
            });

            it('should render the time zone offset correctly', function () {
                expect(inter.renderDate(new Date(2016, 0, 15, 11, 30), 'fullDateTime'), 'to equal', 'Friday, January 15, 2016 at 11:30:00 am -02:00');
            });
        });

        describe('with a positive time zone offset (GMT+02:00)', function () {
            var originalGetTimezoneOffset = Date.prototype.getTimezoneOffset;
            beforeEach(function () {
                Date.prototype.getTimezoneOffset = function () {
                    return -120; // This is a bit of a wtf, I would expect it to return 120, but it doesn't
                };
            });
            afterEach(function () {
                Date.prototype.getTimezoneOffset = originalGetTimezoneOffset;
            });

            it('should render the time zone offset correctly', function () {
                expect(inter.renderDate(new Date(2016, 0, 15, 11, 30), 'fullDateTime'), 'to equal', 'Friday, January 15, 2016 at 11:30:00 am +02:00');
            });
        });

        it('should accept a number (epoch milliseconds) instead of a Date instance', function () {
            expect(inter.renderDate(5000, 'shortDate'), 'to equal', '1/1/1970');
        });

        it('should accept a parsable date string instead of a Date instance', function () {
            expect(inter.renderDate('Nov 18 2014 18:00', 'shortDate'), 'to equal', '11/18/2014');
        });

        it('should use the regular month format when using the L format character', function () {
            expect(require('../build/fi').renderDateFormat(new Date('Nov 18 2014 18:00'), 'MMMM'), 'to equal', 'marraskuuta');
        });

        it('should use the standalone month format when using the L format character', function () {
            expect(require('../build/fi').renderDateFormat(new Date('Nov 18 2014 18:00'), 'LLLL'), 'to equal', 'marraskuu');
        });
    });

    describe('#renderList()', function () {
        it('should should render a list according to the unitNarrow pattern', function () {
            expect(inter.renderList(['foo', 'bar', 'quux'], 'unitNarrow'), 'to equal', 'foo bar quux');
        });

        it('should use the default format when the type parameter is omitted', function () {
            expect(inter.renderList(['foo', 'bar', 'quux']), 'to equal', 'foo, bar, and quux');
        });
    });

    describe('#renderNumber', function () {
        it('should render a number in the Indian English locale (#11)', function () {
            expect(require('../build/en_in').renderNumber(10000000.23), 'to equal', '10,000,000.23');
        });

        it('should render a number in the Danish locale (#11)', function () {
            expect(require('../build/da').renderNumber(10000000.23), 'to equal', '10.000.000,23');
        });
    });

    describe('#renderPercentage', function () {
        it('should accept the number of decimals as the second parameter', function () {
            expect(require('../build/da').renderPercentage(12.345678, 2), 'to equal', '1.234,57\xa0%');
        });

        it('should accept the number system as the third parameter', function () {
            expect(require('../build/da').renderPercentage(12.345678, 2, 'mlym'), 'to equal', '൧.൨൩൪,൫൭\xa0%');
        });
    });

    describe('#renderUnit', function () {
        it('should render a singular number of units', function () {
            expect(inter.renderUnit(1, 'durationWeek'), 'to equal', '1 week');
        });

        it('should render a plural number of units', function () {
            expect(inter.renderUnit(2, 'durationWeek'), 'to equal', '2 weeks');
        });

        it('should render in the narrow format', function () {
            expect(inter.renderUnit(1, 'durationWeek', 'narrow'), 'to equal', '1w');
        });
    });

    describe('#renderCurrencyShort', function () {
        it('should render a float with a currency', function () {
            expect(inter.renderCurrencyShort(134.40, 'USD'), 'to equal', '$134.40');
        });

        it('should render a float with a currency, with a different amount of decimals', function () {
            expect(inter.renderCurrencyShort(134.40, 'USD', 'latn', 1), 'to equal', '$134.4');
        });

        it('should render a number in the Dutch locale', function () {
            expect(require('../build/nl').renderCurrencyShort(134.40, 'EUR'), 'to equal', '€ 134,40');
        });
    });

    describe('#renderCurrencyLong', function () {
        it('should render a float with a currency', function () {
            expect(inter.renderCurrencyLong(134.40, 'USD'), 'to equal', 'USD\xa0134.40');
        });

        it('should render a float with a currency, with a different amount of decimals', function () {
            expect(inter.renderCurrencyLong(134.40, 'USD', 'latn', 1), 'to equal', 'USD\xa0134.4');
        });

        it('should render a number in the Dutch locale', function () {
            expect(require('../build/nl').renderCurrencyLong(134.40, 'EUR'), 'to equal', 'EUR\xa0134,40');
        });
    });

    describe('#makeUnitRenderer', function () {
        it('should render in the narrow format', function () {
            expect(inter.makeUnitRenderer('durationWeek', 'narrow')(1), 'to equal', '1w');
        });
    });

    describe('#adaptICUFormat', function () {
        it('should adapt a pattern that uses L correctly when the format id uses M', function () {
            expect(require('../build/fi').adaptICUFormat('LLL', 'MMMM'), 'to equal', 'LLLL');
        });
    });
});
<|endoftext|>


<commit_before>export const getRandomString = () => {
  return Math.random().toString(36).slice(2)
}
<commit_msg>fix(test utils): more predictable random string<commit_after>export const getRandomString = () => {
  return Math.random().toString(36).substring(2,12)
}
<|endoftext|>


<commit_before>/**
 * Created by guillermo on 18/05/2014.
 */
'use strict';

/*
 * Modified from https://github.com/elliotf/mocha-Mongoose
 */

var config = require('../src/backend/config');
var Mongoose = require('Mongoose');

// ensure the NODE_ENV is set to 'test'
// this is helpful when you would like to change behavior when testing
process.env.NODE_ENV = 'test';

beforeEach(function (done) {
    function doneRemovingConnection() {}
    function clearDB() {
        for (var i in Mongoose.connection.collections) {
            Mongoose.connection.collections[i].remove(doneRemovingConnection);
        }

        return done();
    }

    function reconnect() {
        Mongoose.connect(config.db.test, function (err) {
            if (err) {
                throw err;
            }

            return clearDB();
        });
    }

    function checkState() {
        switch (Mongoose.connection.readyState) {
            case 0:
                reconnect();
                break;
            case 1:
                clearDB();
                break;
            default:
                process.nextTick(checkState);
        }
    }

    checkState();
});

afterEach(function (done) {
    Mongoose.connection.db.dropDatabase(function(err, results) {
        console.log('dropped database');
    });
    Mongoose.disconnect();
    return done();
});<commit_msg>fixed load dependency mongoose<commit_after>/**
 * Created by guillermo on 18/05/2014.
 */
'use strict';

/*
 * Modified from https://github.com/elliotf/mocha-Mongoose
 */

var config = require('../src/backend/config');
var Mongoose = require('mongoose');

// ensure the NODE_ENV is set to 'test'
// this is helpful when you would like to change behavior when testing
process.env.NODE_ENV = 'test';

beforeEach(function (done) {
    function doneRemovingConnection() {}
    function clearDB() {
        for (var i in Mongoose.connection.collections) {
            Mongoose.connection.collections[i].remove(doneRemovingConnection);
        }

        return done();
    }

    function reconnect() {
        Mongoose.connect(config.db.test, function (err) {
            if (err) {
                throw err;
            }

            return clearDB();
        });
    }

    function checkState() {
        switch (Mongoose.connection.readyState) {
            case 0:
                reconnect();
                break;
            case 1:
                clearDB();
                break;
            default:
                process.nextTick(checkState);
        }
    }

    checkState();
});

afterEach(function (done) {
    Mongoose.connection.db.dropDatabase(function(err, results) {
        console.log('dropped database');
    });
    Mongoose.disconnect();
    return done();
});<|endoftext|>


<commit_before>var personaArguments = {
    siteName: 'Where Is My Fox?',
};

function renderDeviceTable(devices) {
    if (devices.length) {
        devices[0].first = true;
    }

    var table = Mustache.render($('#device-list-template').html(), {
        devices: devices,
        mapsURL: "https://maps.google.com/maps?q="
    });

    $("#devices").html(table);
    $("#devices button").click(function() {
        var select = $(this).parent().prev().children("select"),
        options = select.children("option"),
        idx = select.get(0).selectedIndex,
        trigger = $(options[idx]).attr("data-trigger");

        $.post(trigger);
    });
}

function updateDevices() {
    $("#devices").html("Fetching list...");

    function failedToFetchDevices() {
        $("#devices").html("Failed to fetch your devices!");
    }

    $.getJSON('/device').then(function(list) {
        var deviceRequests = list.map(function(url) {
            return $.getJSON(url);
        });

        $.when.apply(null, deviceRequests).then(function() {
            var devices = [];

            if (deviceRequests.length == 1) {
                devices.push(arguments[0]);
            } else {
                for (var i = 0; i < arguments.length; i++) {
                    devices.push(arguments[i][0]);
                }
            }

            var commandRequests = devices.map(function(device) {
                return $.getJSON('/device/' + device.Id + '/command');
            });

            $.when.apply(null, commandRequests).then(function() {
                for (var i = 0; i < devices.length; i++) {
                    devices[i].commands = arguments[i];
                    devices[i].id = i;
                }

                renderDeviceTable(devices);
            });

        }, failedToFetchDevices);
    }, failedToFetchDevices);
}

$("document").ready(function(){

    $("#persona-logout").hide();
    $("#devices").hide();

    function loggedIn(email){
        $("#persona-login").hide();
        $("#persona-logout").show();

        $("#devices").show();
        updateDevices();
    }

    function loggedOut(){
        $("#persona-logout").hide();
        $("#persona-login").show();
        $("#devices").hide();
    }

    $("#persona-login").on("click", function(e) {
        e.preventDefault();
        navigator.id.get(mailVerified, personaArguments);
    });

    $("#persona-logout").on("click", function(e) {
        e.preventDefault();
        $.get('/auth/logout', loggedOut);
    });

    function mailVerified(assertion){
        $.ajax({
            type: 'POST',
            url: '/auth/login',
            data: {assertion: assertion},
            success: function(res, status, xhr) {
                loggedIn(JSON.parse(res).email);
            },
            error: function(xhr, status, err) {
                alert("Login failure: " + err);
            }
        });
    }

    $.get('/auth/check', function (res) {
        if (res === "") {
            loggedOut();
        } else {
            loggedIn(res);
        }
    });
});

<commit_msg>Fix action menu issue. Fixes #18 properly.<commit_after>var personaArguments = {
    siteName: 'Where Is My Fox?',
};

function renderDeviceTable(devices) {
    if (devices.length) {
        devices[0].first = true;
    }

    var table = Mustache.render($('#device-list-template').html(), {
        devices: devices,
        mapsURL: "https://maps.google.com/maps?q="
    });

    $("#devices").html(table);
    $("#devices button").click(function() {
        var select = $(this).parent().prev().children("select"),
        options = select.children("option"),
        idx = select.get(0).selectedIndex,
        trigger = $(options[idx]).attr("data-trigger");

        $.post(trigger);
    });
}

/*
 * Takes an array of jQuery XHR requests, and returns a Promise that resolves
 * when all of then succeed and rejects when any of them fails. The Promise
 * resolves to an array, each element being the result of each request in the
 * order they were passed.
 *
 * NOTE: jQuery.when() when called with just one promise (e.g. in the case
 * where the user has only one device registered), passes the result of that
 * promise to the associated callback, while for multiple devices, it passes
 * a list.  This is stupid behaviour for our case.
 *
 */
function URLs_every(deferreds) {
    return $.when.apply(null, deferreds).then(function() {
        if (deferreds.length == 1) {
            return [arguments[0][0]];
        } else {
            return Array.prototype.slice.call(arguments).map(function(jqXHRResult) { return jqXHRResult[0]; });
        }
    });
}

function updateDevices() {
    $("#devices").html("Fetching list...");

    function failedToFetchDevices() {
        $("#devices").html("Failed to fetch your devices!");
    }

    $.getJSON('/device').then(function(list) {
        var deviceRequests = list.map(function(url) {
            return $.getJSON(url);
        });

        URLs_every(deviceRequests).then(function(devices) {
            var commandRequests = devices.map(function(device) {
                return $.getJSON('/device/' + device.Id + '/command');
            });

            URLs_every(commandRequests).then(function(commands) {
                for (var i = 0; i < devices.length; i++) {
                    devices[i].commands = commands[i];
                    devices[i].id = i;
                }
                console.log(devices);
                renderDeviceTable(devices);
            });

        }, failedToFetchDevices);
    }, failedToFetchDevices);
}

$("document").ready(function(){

    $("#persona-logout").hide();
    $("#devices").hide();

    function loggedIn(email){
        $("#persona-login").hide();
        $("#persona-logout").show();

        $("#devices").show();
        updateDevices();
    }

    function loggedOut(){
        $("#persona-logout").hide();
        $("#persona-login").show();
        $("#devices").hide();
    }

    $("#persona-login").on("click", function(e) {
        e.preventDefault();
        navigator.id.get(mailVerified, personaArguments);
    });

    $("#persona-logout").on("click", function(e) {
        e.preventDefault();
        $.get('/auth/logout', loggedOut);
    });

    function mailVerified(assertion){
        $.ajax({
            type: 'POST',
            url: '/auth/login',
            data: {assertion: assertion},
            success: function(res, status, xhr) {
                loggedIn(JSON.parse(res).email);
            },
            error: function(xhr, status, err) {
                alert("Login failure: " + err);
            }
        });
    }

    $.get('/auth/check', function (res) {
        if (res === "") {
            loggedOut();
        } else {
            loggedIn(res);
        }
    });
});

<|endoftext|>


<commit_before>var gridster;
var scout_cal_html = '';
var stock_widget_html = '

';
var gmail_widget_html = '
<button id="authorize-button" style="visibility: hidden">Authorize</button><div id="gmail_data_anchor_<%= data.widget_num %>">

';
var qlink_data = {qlinks: [
    {name: 'cs colorgame', url: 'http://cs-interview-questions.herokuapp.com/static/color_game.html'}
    //, {name: '', url: ''}
]};

function bitcoin_price() {
    bitcoinprices.init({
        // Where we get bitcoinaverage data
        url: "https://api.bitcoinaverage.com/ticker/all",

        // Which of bitcoinaverages value we use to present prices
        marketRateVariable: "24h_avg",
        // Which currencies are in shown to the user
        //currencies: ["BTC", "USD", "EUR", "CNY"],
        currencies: ["USD"],
        // Special currency symbol artwork
        symbols: {
            "BTC": ""
        },
        // Which currency we show user by the default if
        // no currency is selected
        defaultCurrency: "USD",
        // How the user is able to interact with the prices
        ux : {
            // Make everything with data-btc-price HTML attribute clickable
            clickPrices : true,
            // Build Bootstrap dropdown menu for currency switching
            menu : false,
            // Allow user to cycle through currency choices in currency:
            clickableCurrencySymbol:  false
        },

        // Allows passing the explicit jQuery version to bitcoinprices.
        // This is useful if you are using modular javascript (AMD/UMD/require()),
        // but for most normal usage you don't need this
        jQuery: jQuery,
        // Price source data attribute
        priceAttribute: "data-btc-price",
        // Price source currency for data-btc-price attribute.
        // E.g. if your shop prices are in USD
        // but converted to BTC when you do Bitcoin
        // checkout, put USD here.
        priceOrignalCurrency: "BTC"
    });
};
function generate_stock_widget(symbol_csv) {
    var price_template = $('script#stock_template').html();
    var url = 'https://query.yahooapis.com/v1/public/yql';
    var data = encodeURIComponent("select * from yahoo.finance.quotes where symbol in ('" + symbol_csv + "')");
    $.getJSON(url, 'q=' + data + "&format=json&diagnostics=true&env=http://datatables.org/alltables.env").done(function (data) {
        var compiled_template = _.template(price_template);
        var sorted_results = _.sortBy(data.query.results.quote, function(result) {
            //return -1 * parseFloat(result.PercentChange);
            return result.PercentChange.substring(1);
        });
        var template_data = compiled_template({results: sorted_results.reverse()});
        $("div#stock_data_anchor").append(template_data);

        bitcoin_price();
    }).fail(function (jqxhr, textStatus, error) {
        var err = textStatus + ", " + error;
        console.log('Request failed: ' + err);
    });
}
function wrap_with_header(title, html) {
    return ""+title+""+html;
}
function wrap_with_li(html) {
    return "
" + html + "
";
}

function fill_email_widget(email, num) {
    $.get("/api/imap/"+email, function(email_data) {
        var gmail_template = $('script#gmail_template').html();
        var compiled_template = _.template(gmail_template);
        var data = {
            count: email_data.emails.length,
            widget_num: num,
            emails: email_data.emails
        };

        var template_data = compiled_template({data: data});
        $("div#gmail_data_anchor_"+num).append(template_data);
    });
}
function init_email_widget(email, num) {
    // compile widget template
    var widget_data = {
        user_id: email,
        widget_num: num
    }
    var compiled_template = _.template(gmail_widget_html);
    var finished_template = compiled_template({data: widget_data});

    return [wrap_with_li(wrap_with_header(widget_data.user_id, finished_template)), 2, 1];
}
function create_email_widgets(cb) {
    $.get("/api/imap/list", function(data) {
        var widget_templates = _.map(data.emails, init_email_widget);
        return cb(null, widget_templates, data.emails);
    });
}

function create_quicklink_widget(qlinks) {
    var qlink_template = $('script#qlink_template').html();
    var compiled_template = _.template(qlink_template);
    var finished_template = compiled_template({data: qlinks});

    return [wrap_with_li(wrap_with_header('quicklinks', finished_template)), 1, 1];
}

function create_stock_widget(widget_html) {
    return [wrap_with_li(wrap_with_header("Ticker Data", widget_html)), 1, 2];
}

function create_calendar_widget(widget_html) {
    return [wrap_with_li(wrap_with_header("Scout Calendar", widget_html)), 1, 1];
}

$(function first_render(){
    gridster = $(".gridster > ul").gridster({
        widget_margins: [2, 2],
        widget_base_dimensions: [450, 250],
        //max_cols: 10,
        extra_rows: 1,
        draggable: {
            handle: 'header'
        }
    }).data('gridster');

    create_email_widgets(function(err, email_widgets, emails) {
        if (err) {
            $('body').append(JSON.stringify(err));
            return console.log(err);
        }
        // init widgets
        var widgets = email_widgets;

        widgets.push(create_stock_widget(stock_widget_html));
        widgets.push(create_calendar_widget(scout_cal_html));

        widgets.push(create_quicklink_widget(qlink_data));

        // add widgets to page
        $.each(widgets, function(i, widget){
            gridster.add_widget.apply(gridster, widget)
        });

        // fill widgets with dat
        var symbols = ['IBM',"BAC","AIZ","UHAL","AEG","LL","LUKOY","XOM","KRFT"];
        generate_stock_widget(symbols);
        _.each(emails, fill_email_widget);
    });
});
<commit_msg>fixed comment typo<commit_after>var gridster;
var scout_cal_html = '';
var stock_widget_html = '

';
var gmail_widget_html = '
<button id="authorize-button" style="visibility: hidden">Authorize</button><div id="gmail_data_anchor_<%= data.widget_num %>">

';
var qlink_data = {qlinks: [
    {name: 'cs colorgame', url: 'http://cs-interview-questions.herokuapp.com/static/color_game.html'}
    //, {name: '', url: ''}
]};

function bitcoin_price() {
    bitcoinprices.init({
        // Where we get bitcoinaverage data
        url: "https://api.bitcoinaverage.com/ticker/all",

        // Which of bitcoinaverages value we use to present prices
        marketRateVariable: "24h_avg",
        // Which currencies are in shown to the user
        //currencies: ["BTC", "USD", "EUR", "CNY"],
        currencies: ["USD"],
        // Special currency symbol artwork
        symbols: {
            "BTC": ""
        },
        // Which currency we show user by the default if
        // no currency is selected
        defaultCurrency: "USD",
        // How the user is able to interact with the prices
        ux : {
            // Make everything with data-btc-price HTML attribute clickable
            clickPrices : true,
            // Build Bootstrap dropdown menu for currency switching
            menu : false,
            // Allow user to cycle through currency choices in currency:
            clickableCurrencySymbol:  false
        },

        // Allows passing the explicit jQuery version to bitcoinprices.
        // This is useful if you are using modular javascript (AMD/UMD/require()),
        // but for most normal usage you don't need this
        jQuery: jQuery,
        // Price source data attribute
        priceAttribute: "data-btc-price",
        // Price source currency for data-btc-price attribute.
        // E.g. if your shop prices are in USD
        // but converted to BTC when you do Bitcoin
        // checkout, put USD here.
        priceOrignalCurrency: "BTC"
    });
};
function generate_stock_widget(symbol_csv) {
    var price_template = $('script#stock_template').html();
    var url = 'https://query.yahooapis.com/v1/public/yql';
    var data = encodeURIComponent("select * from yahoo.finance.quotes where symbol in ('" + symbol_csv + "')");
    $.getJSON(url, 'q=' + data + "&format=json&diagnostics=true&env=http://datatables.org/alltables.env").done(function (data) {
        var compiled_template = _.template(price_template);
        var sorted_results = _.sortBy(data.query.results.quote, function(result) {
            //return -1 * parseFloat(result.PercentChange);
            return result.PercentChange.substring(1);
        });
        var template_data = compiled_template({results: sorted_results.reverse()});
        $("div#stock_data_anchor").append(template_data);

        bitcoin_price();
    }).fail(function (jqxhr, textStatus, error) {
        var err = textStatus + ", " + error;
        console.log('Request failed: ' + err);
    });
}
function wrap_with_header(title, html) {
    return ""+title+""+html;
}
function wrap_with_li(html) {
    return "
" + html + "
";
}

function fill_email_widget(email, num) {
    $.get("/api/imap/"+email, function(email_data) {
        var gmail_template = $('script#gmail_template').html();
        var compiled_template = _.template(gmail_template);
        var data = {
            count: email_data.emails.length,
            widget_num: num,
            emails: email_data.emails
        };

        var template_data = compiled_template({data: data});
        $("div#gmail_data_anchor_"+num).append(template_data);
    });
}
function init_email_widget(email, num) {
    // compile widget template
    var widget_data = {
        user_id: email,
        widget_num: num
    }
    var compiled_template = _.template(gmail_widget_html);
    var finished_template = compiled_template({data: widget_data});

    return [wrap_with_li(wrap_with_header(widget_data.user_id, finished_template)), 2, 1];
}
function create_email_widgets(cb) {
    $.get("/api/imap/list", function(data) {
        var widget_templates = _.map(data.emails, init_email_widget);
        return cb(null, widget_templates, data.emails);
    });
}

function create_quicklink_widget(qlinks) {
    var qlink_template = $('script#qlink_template').html();
    var compiled_template = _.template(qlink_template);
    var finished_template = compiled_template({data: qlinks});

    return [wrap_with_li(wrap_with_header('quicklinks', finished_template)), 1, 1];
}

function create_stock_widget(widget_html) {
    return [wrap_with_li(wrap_with_header("Ticker Data", widget_html)), 1, 2];
}

function create_calendar_widget(widget_html) {
    return [wrap_with_li(wrap_with_header("Scout Calendar", widget_html)), 1, 1];
}

$(function first_render(){
    gridster = $(".gridster > ul").gridster({
        widget_margins: [2, 2],
        widget_base_dimensions: [450, 250],
        //max_cols: 10,
        extra_rows: 1,
        draggable: {
            handle: 'header'
        }
    }).data('gridster');

    create_email_widgets(function(err, email_widgets, emails) {
        if (err) {
            $('body').append(JSON.stringify(err));
            return console.log(err);
        }
        // init widgets
        var widgets = email_widgets;

        widgets.push(create_stock_widget(stock_widget_html));
        widgets.push(create_calendar_widget(scout_cal_html));

        widgets.push(create_quicklink_widget(qlink_data));

        // add widgets to page
        $.each(widgets, function(i, widget){
            gridster.add_widget.apply(gridster, widget)
        });

        // fill widgets with data
        var symbols = ['IBM',"BAC","AIZ","UHAL","AEG","LL","LUKOY","XOM","KRFT"];
        generate_stock_widget(symbols);
        _.each(emails, fill_email_widget);
    });
});
<|endoftext|>


<commit_before>"use strict";

var samples = 2;

function send(path, data, callback) {
    var result = document.getElementById("result");

    result.textContent = "Running...";

    var request = new XMLHttpRequest();
    request.open("POST", path, true);
    request.setRequestHeader("Content-Type", "application/json");
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            var json;

            try {
                json = JSON.parse(request.response);
            } catch (e) {
                console.log("JSON.parse(): " + e);
            }

            if (request.status == 200) {
                callback(json);
            } else {
                result.textContent = "connection failure";
            }
        }
    }
    request.timeout = 10000;
    request.ontimeout = function() {
        result.textContent = "connection timed out"
    }
    request.send(JSON.stringify(data));
}

function evaluate(result, code, version, optimize) {
    send("/evaluate.json", {code: code, version: version, optimize: optimize},
         function(object) {
          result.textContent = object["result"];

          var div = document.createElement("div");
          div.className = "message";
          div.textContent = "Program ended.";
          result.appendChild(div);
    });
}

function compile(emit, result, code, version, optimize) {
    send("/compile.json", {emit: emit, code: code, version: version, optimize: optimize,
                           highlight: true},
         function(object) {
          if ("error" in object) {
              result.textContent = object["error"];
          } else {
              result.innerHTML = object["result"];
          }
    });
}

function format(result, session, version) {
    send("/format.json", {code: session.getValue(), version: version}, function(object) {
          if ("error" in object) {
              result.textContent = object["error"];
          } else {
              result.textContent = "";
              session.setValue(object["result"]);
          }
    });
}

function share(result, version, code) {
    var playurl = "http://play.rust-lang.org?code=" + encodeURIComponent(code);
    if (version != "master") {
        playurl += "&version=" + encodeURIComponent(version);
    }
    if (playurl.length > 5000) {
        result.textContent = "resulting URL above character limit for sharing. " +
            "Length: " + playurl.length + "; Maximum: 5000";
        return;
    }

    var url = "http://is.gd/create.php?format=json&url=" + encodeURIComponent(playurl);

    var request = new XMLHttpRequest();
    request.open("GET", url, true);

    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {
                setResponse(JSON.parse(request.responseText)['shorturl']);
            } else {
                result.textContent = "connection failure";
            }
        }
    }

    request.send();

    function setResponse(shorturl) {
        while(result.firstChild) {
            result.removeChild(result.firstChild);
        }

        var link = document.createElement("a");
        link.href = link.textContent = shorturl;

        result.textContent = "short url: ";
        result.appendChild(link);
    }
}

function getQueryParameters() {
    var a = window.location.search.substr(1).split('&');
    if (a == "") return {};
    var b = {};
    for (var i = 0; i < a.length; i++) {
        var p = a[i].split('=');
        if (p.length != 2) continue;
        b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }
    return b;
}

function set_keyboard(editor, mode) {
    if (mode == "Emacs") {
        editor.setKeyboardHandler("ace/keyboard/emacs");
    } else if (mode == "Vim") {
        editor.setKeyboardHandler("ace/keyboard/vim");
    } else {
        editor.setKeyboardHandler(null);
    }
}

addEventListener("DOMContentLoaded", function() {
    var evaluateButton = document.getElementById("evaluate");
    var asmButton = document.getElementById("asm");
    var irButton = document.getElementById("ir");
    var formatButton = document.getElementById("format");
    var shareButton = document.getElementById("share");
    var result = document.getElementById("result");
    var optimize = document.getElementById("optimize");
    var version = document.getElementById("version");
    var keyboard = document.getElementById("keyboard");
    var editor = ace.edit("editor");
    var session = editor.getSession();

    editor.setTheme("ace/theme/github");
    session.setMode("ace/mode/rust");

    var mode = localStorage.getItem("keyboard");
    if (mode !== null) {
        set_keyboard(editor, mode);
        keyboard.value = mode;
    }

    var query = getQueryParameters();
    if ("code" in query) {
        session.setValue(query["code"]);
    } else {
        var code = localStorage.getItem("code");
        if (code !== null) {
            session.setValue(code);
        }
    }

    if ("version" in query) {
        version.value = query["version"];
    }

    if (query["run"] === "1") {
        evaluate(result, session.getValue(), version.options[version.selectedIndex].text,
                 optimize.options[optimize.selectedIndex].value);
    }

    session.on("change", function() {
        localStorage.setItem("code", session.getValue());
    });

    keyboard.onchange = function() {
        var mode = keyboard.options[keyboard.selectedIndex].value;
        localStorage.setItem("keyboard", mode);
        set_keyboard(editor, mode);
    }

    evaluateButton.onclick = function() {
        evaluate(result, session.getValue(), version.options[version.selectedIndex].text,
                 optimize.options[optimize.selectedIndex].value);
    };

    asmButton.onclick = function() {
        compile("asm", result, session.getValue(), version.options[version.selectedIndex].text,
                 optimize.options[optimize.selectedIndex].value);
    };

    irButton.onclick = function() {
        compile("ir", result, session.getValue(), version.options[version.selectedIndex].text,
                 optimize.options[optimize.selectedIndex].value);
    };

    formatButton.onclick = function() {
        format(result, session, version.options[version.selectedIndex].text);
    };

    shareButton.onclick = function() {
        share(result, version.value, session.getValue());
    };
}, false);
<commit_msg>Add keybinding for evaluating code.<commit_after>"use strict";

var samples = 2;

function send(path, data, callback) {
    var result = document.getElementById("result");

    result.textContent = "Running...";

    var request = new XMLHttpRequest();
    request.open("POST", path, true);
    request.setRequestHeader("Content-Type", "application/json");
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            var json;

            try {
                json = JSON.parse(request.response);
            } catch (e) {
                console.log("JSON.parse(): " + e);
            }

            if (request.status == 200) {
                callback(json);
            } else {
                result.textContent = "connection failure";
            }
        }
    }
    request.timeout = 10000;
    request.ontimeout = function() {
        result.textContent = "connection timed out"
    }
    request.send(JSON.stringify(data));
}

function evaluate(result, code, version, optimize) {
    send("/evaluate.json", {code: code, version: version, optimize: optimize},
         function(object) {
          result.textContent = object["result"];

          var div = document.createElement("div");
          div.className = "message";
          div.textContent = "Program ended.";
          result.appendChild(div);
    });
}

function compile(emit, result, code, version, optimize) {
    send("/compile.json", {emit: emit, code: code, version: version, optimize: optimize,
                           highlight: true},
         function(object) {
          if ("error" in object) {
              result.textContent = object["error"];
          } else {
              result.innerHTML = object["result"];
          }
    });
}

function format(result, session, version) {
    send("/format.json", {code: session.getValue(), version: version}, function(object) {
          if ("error" in object) {
              result.textContent = object["error"];
          } else {
              result.textContent = "";
              session.setValue(object["result"]);
          }
    });
}

function share(result, version, code) {
    var playurl = "http://play.rust-lang.org?code=" + encodeURIComponent(code);
    if (version != "master") {
        playurl += "&version=" + encodeURIComponent(version);
    }
    if (playurl.length > 5000) {
        result.textContent = "resulting URL above character limit for sharing. " +
            "Length: " + playurl.length + "; Maximum: 5000";
        return;
    }

    var url = "http://is.gd/create.php?format=json&url=" + encodeURIComponent(playurl);

    var request = new XMLHttpRequest();
    request.open("GET", url, true);

    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {
                setResponse(JSON.parse(request.responseText)['shorturl']);
            } else {
                result.textContent = "connection failure";
            }
        }
    }

    request.send();

    function setResponse(shorturl) {
        while(result.firstChild) {
            result.removeChild(result.firstChild);
        }

        var link = document.createElement("a");
        link.href = link.textContent = shorturl;

        result.textContent = "short url: ";
        result.appendChild(link);
    }
}

function getQueryParameters() {
    var a = window.location.search.substr(1).split('&');
    if (a == "") return {};
    var b = {};
    for (var i = 0; i < a.length; i++) {
        var p = a[i].split('=');
        if (p.length != 2) continue;
        b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }
    return b;
}

function set_keyboard(editor, mode) {
    if (mode == "Emacs") {
        editor.setKeyboardHandler("ace/keyboard/emacs");
    } else if (mode == "Vim") {
        editor.setKeyboardHandler("ace/keyboard/vim");
    } else {
        editor.setKeyboardHandler(null);
    }
}

addEventListener("DOMContentLoaded", function() {
    var evaluateButton = document.getElementById("evaluate");
    var asmButton = document.getElementById("asm");
    var irButton = document.getElementById("ir");
    var formatButton = document.getElementById("format");
    var shareButton = document.getElementById("share");
    var result = document.getElementById("result");
    var optimize = document.getElementById("optimize");
    var version = document.getElementById("version");
    var keyboard = document.getElementById("keyboard");
    var editor = ace.edit("editor");
    var session = editor.getSession();

    editor.setTheme("ace/theme/github");
    session.setMode("ace/mode/rust");

    var mode = localStorage.getItem("keyboard");
    if (mode !== null) {
        set_keyboard(editor, mode);
        keyboard.value = mode;
    }

    var query = getQueryParameters();
    if ("code" in query) {
        session.setValue(query["code"]);
    } else {
        var code = localStorage.getItem("code");
        if (code !== null) {
            session.setValue(code);
        }
    }

    if ("version" in query) {
        version.value = query["version"];
    }

    if (query["run"] === "1") {
        evaluate(result, session.getValue(), version.options[version.selectedIndex].text,
                 optimize.options[optimize.selectedIndex].value);
    }

    session.on("change", function() {
        localStorage.setItem("code", session.getValue());
    });

    keyboard.onchange = function() {
        var mode = keyboard.options[keyboard.selectedIndex].value;
        localStorage.setItem("keyboard", mode);
        set_keyboard(editor, mode);
    }

    evaluateButton.onclick = function() {
        evaluate(result, session.getValue(), version.options[version.selectedIndex].text,
                 optimize.options[optimize.selectedIndex].value);
    };

    editor.commands.addCommand({
        name: "evaluate",
        exec: evaluateButton.onclick,
        bindKey: {win: "Ctrl-Enter", mac: "Ctrl-Enter"}
    });

    asmButton.onclick = function() {
        compile("asm", result, session.getValue(), version.options[version.selectedIndex].text,
                 optimize.options[optimize.selectedIndex].value);
    };

    irButton.onclick = function() {
        compile("ir", result, session.getValue(), version.options[version.selectedIndex].text,
                 optimize.options[optimize.selectedIndex].value);
    };

    formatButton.onclick = function() {
        format(result, session, version.options[version.selectedIndex].text);
    };

    shareButton.onclick = function() {
        share(result, version.value, session.getValue());
    };
}, false);
<|endoftext|>


<commit_before>"use strict";

var samples = 2;
var themelist = ace.require("ace/ext/themelist");

function build_themes() {
    // Load all ace themes, sorted by their proper name.
    var themes = themelist.themes;
    themes.sort(function (a, b) {
        if (a.caption < b.caption) {
            return -1
        } else if (a.caption > b.caption) {
            return 1;
        } else {
            return 0;
        }
    });

    var themecur,
        themeopt,
        themefrag = document.createDocumentFragment();
    for (var i=0; i < themes.length; i++) {
        themecur = themelist.themes[i];
        themeopt = document.createElement('option');
        themeopt.setAttribute('val', themecur.theme);
        themeopt.textContent = themecur.caption;
        themefrag.appendChild(themeopt);
    }
    document.getElementById('themes').appendChild(themefrag);
}

function send(path, data, callback) {
    var result = document.getElementById("result");

    result.textContent = "Running...";

    var request = new XMLHttpRequest();
    request.open("POST", path, true);
    request.setRequestHeader("Content-Type", "application/json");
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            var json;

            try {
                json = JSON.parse(request.response);
            } catch (e) {
                console.log("JSON.parse(): " + e);
            }

            if (request.status == 200) {
                callback(json);
            } else {
                result.textContent = "connection failure";
            }
        }
    }
    request.timeout = 10000;
    request.ontimeout = function() {
        result.textContent = "connection timed out"
    }
    request.send(JSON.stringify(data));
}

function evaluate(result, code, version, optimize) {
    send("/evaluate.json", {code: code, version: version, optimize: optimize},
         function(object) {
          result.textContent = object["result"];

          var div = document.createElement("div");
          div.className = "message";
          div.textContent = "Program ended.";
          result.appendChild(div);
    });
}

function compile(emit, result, code, version, optimize) {
    send("/compile.json", {emit: emit, code: code, version: version, optimize: optimize,
                           highlight: true},
         function(object) {
          if ("error" in object) {
              result.textContent = object["error"];
          } else {
              result.innerHTML = object["result"];
          }
    });
}

function format(result, session, version) {
    send("/format.json", {code: session.getValue(), version: version}, function(object) {
          if ("error" in object) {
              result.textContent = object["error"];
          } else {
              result.textContent = "";
              session.setValue(object["result"]);
          }
    });
}

function share(result, version, code) {
    var playurl = "https://play.rust-lang.org?code=" + encodeURIComponent(code);
    if (version != "master") {
        playurl += "&version=" + encodeURIComponent(version);
    }
    if (playurl.length > 5000) {
        result.textContent = "resulting URL above character limit for sharing. " +
            "Length: " + playurl.length + "; Maximum: 5000";
        return;
    }

    var url = "https://is.gd/create.php?format=json&url=" + encodeURIComponent(playurl);

    var request = new XMLHttpRequest();
    request.open("GET", url, true);

    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {
                setResponse(JSON.parse(request.responseText)['shorturl']);
            } else {
                result.textContent = "connection failure";
            }
        }
    }

    request.send();

    function setResponse(shorturl) {
        while(result.firstChild) {
            result.removeChild(result.firstChild);
        }

        var link = document.createElement("a");
        link.href = link.textContent = shorturl;

        result.textContent = "short url: ";
        result.appendChild(link);
    }
}

function getQueryParameters() {
    var a = window.location.search.substr(1).split('&');
    if (a == "") return {};
    var b = {};
    for (var i = 0; i < a.length; i++) {
        var p = a[i].split('=');
        if (p.length != 2) continue;
        b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }
    return b;
}

function set_keyboard(editor, mode) {
    if (mode == "Emacs") {
        editor.setKeyboardHandler("ace/keyboard/emacs");
    } else if (mode == "Vim") {
        editor.setKeyboardHandler("ace/keyboard/vim");
    } else {
        editor.setKeyboardHandler(null);
    }
}

function set_theme(editor, theme) {
    var themes = document.getElementById("themes");
    var i = 0,
        themelen = themes.options.length;

    for (i; i < themelen; i++) {
        if (themes.options[i].text == theme) {
            if (themes.selectedIndex !== i) {
                themes.selectedIndex = i;
            }
            editor.setTheme(themes.options[i].getAttribute("val"));
            localStorage.setItem("theme", themes.options[i].text);
            return;
        }
    }
}

addEventListener("DOMContentLoaded", function() {
    var evaluateButton = document.getElementById("evaluate");
    var asmButton = document.getElementById("asm");
    var irButton = document.getElementById("llvm-ir");
    var formatButton = document.getElementById("format");
    var shareButton = document.getElementById("share");
    var result = document.getElementById("result");
    var optimize = document.getElementById("optimize");
    var version = document.getElementById("version");
    var keyboard = document.getElementById("keyboard");
    var themes = document.getElementById("themes");
    var editor = ace.edit("editor");
    var session = editor.getSession();
    build_themes();

    var theme = localStorage.getItem("theme");
    if (theme === null) {
        set_theme(editor, "GitHub");
    } else {
        set_theme(editor, theme);
    }

    session.setMode("ace/mode/rust");

    var mode = localStorage.getItem("keyboard");
    if (mode !== null) {
        set_keyboard(editor, mode);
        keyboard.value = mode;
    }

    var query = getQueryParameters();
    if ("code" in query) {
        session.setValue(query["code"]);
    } else {
        var code = localStorage.getItem("code");
        if (code !== null) {
            session.setValue(code);
        }
    }

    if ("version" in query) {
        version.value = query["version"];
    }

    if (query["run"] === "1") {
        evaluate(result, session.getValue(), version.options[version.selectedIndex].text,
                 optimize.options[optimize.selectedIndex].value);
    }

    session.on("change", function() {
        localStorage.setItem("code", session.getValue());
    });

    keyboard.onchange = function() {
        var mode = keyboard.options[keyboard.selectedIndex].value;
        localStorage.setItem("keyboard", mode);
        set_keyboard(editor, mode);
    }

    evaluateButton.onclick = function() {
        evaluate(result, session.getValue(), version.options[version.selectedIndex].text,
                 optimize.options[optimize.selectedIndex].value);
    };

    editor.commands.addCommand({
        name: "evaluate",
        exec: evaluateButton.onclick,
        bindKey: {win: "Ctrl-Enter", mac: "Ctrl-Enter"}
    });

    asmButton.onclick = function() {
        compile("asm", result, session.getValue(), version.options[version.selectedIndex].text,
                 optimize.options[optimize.selectedIndex].value);
    };

    irButton.onclick = function() {
        compile("llvm-ir", result, session.getValue(), version.options[version.selectedIndex].text,
                 optimize.options[optimize.selectedIndex].value);
    };

    formatButton.onclick = function() {
        format(result, session, version.options[version.selectedIndex].text);
    };

    shareButton.onclick = function() {
        share(result, version.value, session.getValue());
    };

    themes.onchange = function () {
        set_theme(editor, themes.selectedOptions[0].text);
    }

}, false);
<commit_msg>Enhance theme list speed and code style.<commit_after>"use strict";

var samples = 2;

function build_themes(themelist) {
    // Load all ace themes, sorted by their proper name.
    var themes = themelist.themes;
    themes.sort(function (a, b) {
        if (a.caption < b.caption) {
            return -1
        } else if (a.caption > b.caption) {
            return 1;
        }
        return 0;
    });

    var themeopt,
        themefrag = document.createDocumentFragment();
    for (var i=0; i < themes.length; i++) {
        themeopt = document.createElement("option");
        themeopt.setAttribute("val", themes[i].theme);
        themeopt.textContent = themes[i].caption;
        themefrag.appendChild(themeopt);
    }
    document.getElementById("themes").appendChild(themefrag);
}

function send(path, data, callback) {
    var result = document.getElementById("result");

    result.textContent = "Running...";

    var request = new XMLHttpRequest();
    request.open("POST", path, true);
    request.setRequestHeader("Content-Type", "application/json");
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            var json;

            try {
                json = JSON.parse(request.response);
            } catch (e) {
                console.log("JSON.parse(): " + e);
            }

            if (request.status == 200) {
                callback(json);
            } else {
                result.textContent = "connection failure";
            }
        }
    }
    request.timeout = 10000;
    request.ontimeout = function() {
        result.textContent = "connection timed out"
    }
    request.send(JSON.stringify(data));
}

function evaluate(result, code, version, optimize) {
    send("/evaluate.json", {code: code, version: version, optimize: optimize},
         function(object) {
          result.textContent = object["result"];

          var div = document.createElement("div");
          div.className = "message";
          div.textContent = "Program ended.";
          result.appendChild(div);
    });
}

function compile(emit, result, code, version, optimize) {
    send("/compile.json", {emit: emit, code: code, version: version, optimize: optimize,
                           highlight: true},
         function(object) {
          if ("error" in object) {
              result.textContent = object["error"];
          } else {
              result.innerHTML = object["result"];
          }
    });
}

function format(result, session, version) {
    send("/format.json", {code: session.getValue(), version: version}, function(object) {
          if ("error" in object) {
              result.textContent = object["error"];
          } else {
              result.textContent = "";
              session.setValue(object["result"]);
          }
    });
}

function share(result, version, code) {
    var playurl = "https://play.rust-lang.org?code=" + encodeURIComponent(code);
    if (version != "master") {
        playurl += "&version=" + encodeURIComponent(version);
    }
    if (playurl.length > 5000) {
        result.textContent = "resulting URL above character limit for sharing. " +
            "Length: " + playurl.length + "; Maximum: 5000";
        return;
    }

    var url = "https://is.gd/create.php?format=json&url=" + encodeURIComponent(playurl);

    var request = new XMLHttpRequest();
    request.open("GET", url, true);

    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {
                setResponse(JSON.parse(request.responseText)['shorturl']);
            } else {
                result.textContent = "connection failure";
            }
        }
    }

    request.send();

    function setResponse(shorturl) {
        while(result.firstChild) {
            result.removeChild(result.firstChild);
        }

        var link = document.createElement("a");
        link.href = link.textContent = shorturl;

        result.textContent = "short url: ";
        result.appendChild(link);
    }
}

function getQueryParameters() {
    var a = window.location.search.substr(1).split('&');
    if (a == "") return {};
    var b = {};
    for (var i = 0; i < a.length; i++) {
        var p = a[i].split('=');
        if (p.length != 2) continue;
        b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }
    return b;
}

function set_keyboard(editor, mode) {
    if (mode == "Emacs") {
        editor.setKeyboardHandler("ace/keyboard/emacs");
    } else if (mode == "Vim") {
        editor.setKeyboardHandler("ace/keyboard/vim");
    } else {
        editor.setKeyboardHandler(null);
    }
}

function set_theme(editor, themelist, theme) {
    var themes = document.getElementById("themes");
    var themepath = null,
        i = 0,
        themelen = themelist.themes.length;
    if (themes.options[themes.selectedIndex].textContent === theme) {
        console.log('using option value: ' + themes.options[themes.selectedIndex].textContent);
        themepath = themes.options[themes.selectedIndex].getAttribute("val");
    } else {
        for (i; i < themelen; i++) {
            if (themelist.themes[i].caption == theme) {
                console.log('found theme: ' + themelist.themes[i].caption);
                themes.selectedIndex = i;
                themepath = themelist.themes[i].theme;
                break;
            }
        }
    }
    if (themepath !== null) {
        editor.setTheme(themepath);
        localStorage.setItem("theme", theme);
        console.log('saved theme: ' + theme);
    }
}

addEventListener("DOMContentLoaded", function() {
    var evaluateButton = document.getElementById("evaluate");
    var asmButton = document.getElementById("asm");
    var irButton = document.getElementById("llvm-ir");
    var formatButton = document.getElementById("format");
    var shareButton = document.getElementById("share");
    var result = document.getElementById("result");
    var optimize = document.getElementById("optimize");
    var version = document.getElementById("version");
    var keyboard = document.getElementById("keyboard");
    var themes = document.getElementById("themes");
    var editor = ace.edit("editor");
    var session = editor.getSession();
    var themelist = ace.require("ace/ext/themelist");

    build_themes(themelist);

    var theme = localStorage.getItem("theme");
    if (theme === null) {
        set_theme(editor, themelist, "GitHub");
    } else {
        set_theme(editor, themelist, theme);
    }

    session.setMode("ace/mode/rust");

    var mode = localStorage.getItem("keyboard");
    if (mode !== null) {
        set_keyboard(editor, mode);
        keyboard.value = mode;
    }

    var query = getQueryParameters();
    if ("code" in query) {
        session.setValue(query["code"]);
    } else {
        var code = localStorage.getItem("code");
        if (code !== null) {
            session.setValue(code);
        }
    }

    if ("version" in query) {
        version.value = query["version"];
    }

    if (query["run"] === "1") {
        evaluate(result, session.getValue(), version.options[version.selectedIndex].text,
                 optimize.options[optimize.selectedIndex].value);
    }

    session.on("change", function() {
        localStorage.setItem("code", session.getValue());
    });

    keyboard.onchange = function() {
        var mode = keyboard.options[keyboard.selectedIndex].value;
        localStorage.setItem("keyboard", mode);
        set_keyboard(editor, mode);
    }

    evaluateButton.onclick = function() {
        evaluate(result, session.getValue(), version.options[version.selectedIndex].text,
                 optimize.options[optimize.selectedIndex].value);
    };

    editor.commands.addCommand({
        name: "evaluate",
        exec: evaluateButton.onclick,
        bindKey: {win: "Ctrl-Enter", mac: "Ctrl-Enter"}
    });

    asmButton.onclick = function() {
        compile("asm", result, session.getValue(), version.options[version.selectedIndex].text,
                 optimize.options[optimize.selectedIndex].value);
    };

    irButton.onclick = function() {
        compile("llvm-ir", result, session.getValue(), version.options[version.selectedIndex].text,
                 optimize.options[optimize.selectedIndex].value);
    };

    formatButton.onclick = function() {
        format(result, session, version.options[version.selectedIndex].text);
    };

    shareButton.onclick = function() {
        share(result, version.value, session.getValue());
    };

    themes.onchange = function () {
        set_theme(editor, themelist, themes.selectedOptions[0].text);
    }

}, false);
<|endoftext|>