<commit_before>var expect = require('expect.js')
  , ffi = require('../')
  , Pointer = ffi.Pointer

describe('Pointer', function () {

  it('should work with the `new` operator', function () {
    var p = new Pointer(8)
      , test = p instanceof Pointer
    expect(test).to.be.true
  })

  it('should detect the `null` pointer', function () {
    var p = new Pointer(0)
    expect(p.isNull()).to.be.true
  })

  it('should have a valid "allocated" property when malloc()\'d', function () {
    var p = new Pointer(1024)
    expect(p.allocated).to.equal(1024)
  })

  it('should have a valid "address"', function () {
    var p = new Pointer(8)
    expect(p.address).to.be.greaterThan(0)
  })

  describe('seek()', function () {

    it('should have function "seek()"', function () {
      expect(Pointer.prototype).to.have.property('seek')
    })

    it('should return a new Pointer instance', function () {
      var p = new Pointer(8)
        , p2 = p.seek(0)
        , test = p2 instanceof Pointer
      expect(test).to.be.true
      expect(p).to.not.equal(p2)
    })

    it('should return a Pointer with its "address" offset by the specified amount'
    , function () {
      var p = new Pointer(8)
        , p2 = p.seek(32)
      expect(p2.address).to.equal(p.address + 32)
    })

  })

  describe('int8', function () {

    it('should throw on out of bounds values (minimum)', function () {
      var p = new Pointer(8)
        , val = Math.pow(2, 7) + 1
      expect(p.putInt8.bind(p, val)).to.throwException()
    })

    it('should throw on out of bounds values (maximum)', function () {
      var p = new Pointer(8)
        , val = 0 - Math.pow(2, 7) - 1
      expect(p.putInt8.bind(p, val)).to.throwException()
    })

    it('should write an "int8" value properly', function () {
      var p = new Pointer(8)
        , val = 0 - Math.pow(2, 7)
      p.putInt8(val)
      expect(p.getInt8()).to.equal(val)
    })

  })

  describe('uint8', function () {

    it('should throw on out of bounds values (minimum)', function () {
      var p = new Pointer(8)
        , val = -1
      expect(p.putUInt8.bind(p, val)).to.throwException()
    })

    it('should throw on out of bounds values (maximum)', function () {
      var p = new Pointer(8)
        , val = Math.pow(2, 8)
      expect(p.putUInt8.bind(p, val)).to.throwException()
    })

    it('should write a "uint8" value properly', function () {
      var p = new Pointer(8)
        , val = Math.pow(2, 8) - 1
      p.putUInt8(val)
      expect(p.getUInt8()).to.equal(val)
    })

  })

  describe('int16', function () {

    it('should throw on out of bounds values (minimum)', function () {
      var p = new Pointer(8)
        , val = Math.pow(2, 15) + 1
      expect(p.putInt16.bind(p, val)).to.throwException()
    })

    it('should throw on out of bounds values (maximum)', function () {
      var p = new Pointer(8)
        , val = 0 - Math.pow(2, 15) - 1
      expect(p.putInt16.bind(p, val)).to.throwException()
    })

    it('should write an "int16" value properly', function () {
      var p = new Pointer(8)
        , val = 0 - Math.pow(2, 15)
      p.putInt16(val)
      expect(p.getInt16()).to.equal(val)
    })

  })

  describe('uint16', function () {

    it('should throw on out of bounds values (minimum)', function () {
      var p = new Pointer(8)
        , val = -1
      expect(p.putUInt8.bind(p, val)).to.throwException()
    })

    it('should throw on out of bounds values (maximum)', function () {
      var p = new Pointer(8)
        , val = Math.pow(2, 16)
      expect(p.putUInt16.bind(p, val)).to.throwException()
    })

    it('should write a "uint8" value properly', function () {
      var p = new Pointer(8)
        , val = Math.pow(2, 16) - 1
      p.putUInt16(val)
      expect(p.getUInt16()).to.equal(val)
    })

  })

  describe('int64', function () {

    it('should write "int64" values properly', function () {
      var p = new Pointer(1024)
        , val = 0 - Math.pow(2, 63)
      p.putInt64(val)
      expect(p.getInt64()).to.eql(val)
    })

  })

  describe('float', function () {

    it('should write a "float" value properly', function () {
      var p = new Pointer(16)
        , val = 1.5
      p.putFloat(val)
      expect(p.getFloat()).to.equal(val)
    })

  })

  describe('double', function () {

    it('should write a "double" value properly', function () {
      var p = new Pointer(16)
        , val = 1000.005
      p.putDouble(val)
      expect(p.getDouble()).to.equal(val)
    })

  })

  describe('pointer', function () {

    it('should write another Pointer instance properly', function () {
      var p = new Pointer(16)
        , p2 = new Pointer(32)
        , val = 1234.5678
      p2.putDouble(val)
      p.putPointer(p2)
      expect(p.getPointer().address).to.equal(p2.address)
      expect(p.getPointer().getDouble()).to.equal(val)
    })

  })

  describe('string', function () {

    it('should write a C string (char array) properly', function () {
      var p = new Pointer(32)
        , msg = 'Hello World!'
      p.putCString(msg)
      expect(p.getCString()).to.equal(msg)
    })

    // https://github.com/rbranson/node-ffi/issues/27
    it('should write multiple strings properly', function () {
      var p = new Pointer(128)
        , base = p.seek(0)
      p.putCString('one', true)
      p.putCString('two', true)
      p.putCString('three', true)
      expect(base.getCString(true)).to.equal('one')
      expect(base.getCString(true)).to.equal('two')
      expect(base.getCString(true)).to.equal('three')
    })

  })

  describe('Object', function () {

    it('should write a JavaScript Object reference properly', function () {
      var p = new Pointer(32)
        , o = { foo: 'bar' }
      p.putObject(o)
      expect(p.getObject()).to.eql(o)
    })

    it('should write multiple JavaScript Object references properly', function () {
      var p = new Pointer(32)
        , base = p.seek(0)
        , o = { foo: 'bar' }
        , o2 = { test: { equality: true } }
      p.putObject(o, true)
      p.putObject(o2, true)
      expect(base.getObject(true)).to.eql(o)
      expect(base.getObject(true)).to.eql(o2)
    })

  })

  describe('byte', function () {

    it('should write a "byte" properly', function () {
      var p = new Pointer(8)
        , val = 6
      p.putByte(val)
      expect(p.getByte()).to.equal(val)
    })

  })

  describe('char', function () {

    it('should write a "char" properly', function () {
      var p = new Pointer(8)
        , val = 6
      p.putChar(val)
      expect(p.getChar()).to.equal(val)
      val = -6
      p.putChar(val)
      expect(p.getChar()).to.equal(val)
    })

  })

})
<commit_msg>Tests.<commit_after>var expect = require('expect.js')
  , ffi = require('../')
  , Pointer = ffi.Pointer

describe('Pointer', function () {

  it('should work with the `new` operator', function () {
    var p = new Pointer(8)
      , test = p instanceof Pointer
    expect(test).to.be.true
  })

  it('should detect the `null` pointer', function () {
    var p = new Pointer(0)
    expect(p.isNull()).to.be.true
  })

  it('should have a valid "allocated" property when malloc()\'d', function () {
    var p = new Pointer(1024)
    expect(p.allocated).to.equal(1024)
  })

  it('should have a valid "address"', function () {
    var p = new Pointer(8)
    expect(p.address).to.be.greaterThan(0)
  })

  describe('seek()', function () {

    it('should have function "seek()"', function () {
      expect(Pointer.prototype).to.have.property('seek')
      expect(Pointer.prototype.seek).to.be.a('function')
    })

    it('should return a new Pointer instance', function () {
      var p = new Pointer(8)
        , p2 = p.seek(0)
        , test = p2 instanceof Pointer
      expect(test).to.be.true
      expect(p).to.not.equal(p2)
    })

    it('should return a Pointer with its "address" offset by the specified amount'
    , function () {
      var p = new Pointer(8)
        , p2 = p.seek(32)
      expect(p2.address).to.equal(p.address + 32)
    })

  })

  describe('int8', function () {

    it('should throw on out of bounds values (minimum)', function () {
      var p = new Pointer(8)
        , val = Math.pow(2, 7) + 1
      expect(p.putInt8.bind(p, val)).to.throwException()
    })

    it('should throw on out of bounds values (maximum)', function () {
      var p = new Pointer(8)
        , val = 0 - Math.pow(2, 7) - 1
      expect(p.putInt8.bind(p, val)).to.throwException()
    })

    it('should write an "int8" value properly', function () {
      var p = new Pointer(8)
        , val = 0 - Math.pow(2, 7)
      p.putInt8(val)
      expect(p.getInt8()).to.equal(val)
    })

  })

  describe('uint8', function () {

    it('should throw on out of bounds values (minimum)', function () {
      var p = new Pointer(8)
        , val = -1
      expect(p.putUInt8.bind(p, val)).to.throwException()
    })

    it('should throw on out of bounds values (maximum)', function () {
      var p = new Pointer(8)
        , val = Math.pow(2, 8)
      expect(p.putUInt8.bind(p, val)).to.throwException()
    })

    it('should write a "uint8" value properly', function () {
      var p = new Pointer(8)
        , val = Math.pow(2, 8) - 1
      p.putUInt8(val)
      expect(p.getUInt8()).to.equal(val)
    })

  })

  describe('int16', function () {

    it('should throw on out of bounds values (minimum)', function () {
      var p = new Pointer(8)
        , val = Math.pow(2, 15) + 1
      expect(p.putInt16.bind(p, val)).to.throwException()
    })

    it('should throw on out of bounds values (maximum)', function () {
      var p = new Pointer(8)
        , val = 0 - Math.pow(2, 15) - 1
      expect(p.putInt16.bind(p, val)).to.throwException()
    })

    it('should write an "int16" value properly', function () {
      var p = new Pointer(8)
        , val = 0 - Math.pow(2, 15)
      p.putInt16(val)
      expect(p.getInt16()).to.equal(val)
    })

  })

  describe('uint16', function () {

    it('should throw on out of bounds values (minimum)', function () {
      var p = new Pointer(8)
        , val = -1
      expect(p.putUInt8.bind(p, val)).to.throwException()
    })

    it('should throw on out of bounds values (maximum)', function () {
      var p = new Pointer(8)
        , val = Math.pow(2, 16)
      expect(p.putUInt16.bind(p, val)).to.throwException()
    })

    it('should write a "uint8" value properly', function () {
      var p = new Pointer(8)
        , val = Math.pow(2, 16) - 1
      p.putUInt16(val)
      expect(p.getUInt16()).to.equal(val)
    })

  })

  describe('int64', function () {

    it('should write "int64" values properly', function () {
      var p = new Pointer(1024)
        , val = 0 - Math.pow(2, 63)
      p.putInt64(val)
      expect(p.getInt64()).to.eql(val)
    })

  })

  describe('float', function () {

    it('should write a "float" value properly', function () {
      var p = new Pointer(16)
        , val = 1.5
      p.putFloat(val)
      expect(p.getFloat()).to.equal(val)
    })

  })

  describe('double', function () {

    it('should write a "double" value properly', function () {
      var p = new Pointer(16)
        , val = 1000.005
      p.putDouble(val)
      expect(p.getDouble()).to.equal(val)
    })

  })

  describe('pointer', function () {

    it('should write another Pointer instance properly', function () {
      var p = new Pointer(16)
        , p2 = new Pointer(32)
        , val = 1234.5678
      p2.putDouble(val)
      p.putPointer(p2)
      expect(p.getPointer().address).to.equal(p2.address)
      expect(p.getPointer().getDouble()).to.equal(val)
    })

  })

  describe('string', function () {

    it('should write a C string (char array) properly', function () {
      var p = new Pointer(32)
        , msg = 'Hello World!'
      p.putCString(msg)
      expect(p.getCString()).to.equal(msg)
    })

    // https://github.com/rbranson/node-ffi/issues/27
    it('should write multiple strings properly', function () {
      var p = new Pointer(128)
        , base = p.seek(0)
      p.putCString('one', true)
      p.putCString('two', true)
      p.putCString('three', true)
      expect(base.getCString(true)).to.equal('one')
      expect(base.getCString(true)).to.equal('two')
      expect(base.getCString(true)).to.equal('three')
    })

  })

  describe('Object', function () {

    it('should write a JavaScript Object reference properly', function () {
      var p = new Pointer(32)
        , o = { foo: 'bar' }
      p.putObject(o)
      expect(p.getObject()).to.eql(o)
    })

    it('should write multiple JavaScript Object references properly', function () {
      var p = new Pointer(32)
        , base = p.seek(0)
        , o = { foo: 'bar' }
        , o2 = { test: { equality: true } }
      p.putObject(o, true)
      p.putObject(o2, true)
      expect(base.getObject(true)).to.eql(o)
      expect(base.getObject(true)).to.eql(o2)
    })

  })

  describe('byte', function () {

    it('should write a "byte" properly', function () {
      var p = new Pointer(8)
        , val = 6
      p.putByte(val)
      expect(p.getByte()).to.equal(val)
    })

  })

  describe('char', function () {

    it('should write a "char" properly', function () {
      var p = new Pointer(8)
        , val = 6
      p.putChar(val)
      expect(p.getChar()).to.equal(val)
      val = -6
      p.putChar(val)
      expect(p.getChar()).to.equal(val)
    })

  })

})
<|endoftext|>


<commit_before>'use strict'

const assert  = require('chai').assert
const postcss = require('./../src/postcss')

describe('postcss()', function() {

	it('should return an empty string when called without parameters', function() {

		return postcss(null, null, null).then((result) => {

			assert.strictEqual(result, '')

		})

	})

	it('should return an empty string when called with an empty CSS string', function() {

		const input = ``

		return postcss(null, input, null).then((result) => {

			assert.strictEqual(result, '')

		})

	})

	it('should return an error when called with incorrect CSS', function() {

		const input = `test`

		return postcss(null, input, null).then((result) => {

			throw new Error('Returned without error')

		}, (err) => {

			assert.isNotNull(err)

		})

	})

	it('should return CSS with a source map when called with valid CSS', function() {

		const input = `.test { color: black; }`

		return postcss(null, input, null).then((result) => {

			assert.isString(result)
			assert.include(result, 'sourceMappingURL')

		})

	})

	it('should return CSS without a source map when called with valid SASS and optimization enabled', function() {

		const input = `.test { color: black; }`
		const opts  = { optimize: true }

		return postcss(null, input, opts).then((result) => {

			assert.isString(result)
			assert.notInclude(result, 'sourceMappingURL')

		})

	})

})<commit_msg>Test filePath branch<commit_after>'use strict'

const assert  = require('chai').assert
const temp    = require('temp').track()
const postcss = require('./../src/postcss')

describe('postcss()', function() {

	it('should return an empty string when called without parameters', function() {

		return postcss(null, null, null).then((result) => {

			assert.strictEqual(result, '')

		})

	})

	it('should return an empty string when called with an empty CSS string', function() {

		const input = ``

		return postcss(null, input, null).then((result) => {

			assert.strictEqual(result, '')

		})

	})

	it('should return an error when called with incorrect CSS', function() {

		const input = `test`

		return postcss(null, input, null).then((result) => {

			throw new Error('Returned without error')

		}, (err) => {

			assert.isNotNull(err)

		})

	})

	it('should return CSS with a source map when called with valid CSS', function() {

		const input = `.test { color: black; }`

		return postcss(null, input, null).then((result) => {

			assert.isString(result)
			assert.include(result, 'sourceMappingURL')

		})

	})

	it('should return CSS when called with valid CSS and a folderPath', function() {

		const filePath = temp.mkdirSync()
		const input    = `.test { color: black; }`

		return postcss(filePath, input, null).then((result) => {

			assert.isString(result)

		})

	})

	it('should return CSS without a source map when called with valid SASS and optimization enabled', function() {

		const input = `.test { color: black; }`
		const opts  = { optimize: true }

		return postcss(null, input, opts).then((result) => {

			assert.isString(result)
			assert.notInclude(result, 'sourceMappingURL')

		})

	})

})<|endoftext|>


<commit_before>var common = require('./common')
var DHT = require('../')
var test = require('tape')
var ed = require('ed25519-supercop')
var bencode = require('bencode')

test('dht store with salt', function (t) {
  t.plan(3)

  var dht = new DHT({ bootstrap: false, verify: ed.verify })
  t.once('end', function () {
    dht.destroy()
  })
  common.failOnWarningOrError(t, dht)

  dht.listen(function () {
    dht.addNode({ host: '127.0.0.1', port: dht.address().port })
    dht.once('node', ready)
  })

  function ready () {
    var keys = ed.createKeyPair(ed.createSeed())
    var publicKey = keys.publicKey
    var secretKey = keys.secretKey

    var opts = {
      seq: 1,
      v: 'hello world'
    }

    opts.k = publicKey

    var toEncode = { seq: opts.seq, v: opts.v }
    toEncode.salt = 'mysalt'

    var encoded = bencode
      .encode(toEncode)
      .slice(1, -1)
      .toString()

    opts.sig = ed
      .sign(encoded, publicKey, secretKey)

    dht.put(opts, function (_, hash) {
      dht.get(hash, function (err, res) {
        t.ifError(err)

        t.equal(res.v.toString('utf8'), opts.v.toString('utf8'),
          'got back what we put in'
        )

        t.equal(res.seq, 1)
        t.end()
      })
    })
  }
})
<commit_msg>Fixed issues with broken mutable put/get test.<commit_after>var common = require('./common')
var DHT = require('../')
var test = require('tape')
var ed = require('ed25519-supercop')
var bencode = require('bencode')

test('dht store with salt', function (t) {
  t.plan(3)

  var dht = new DHT({ bootstrap: false, verify: ed.verify })
  t.once('end', function () {
    dht.destroy()
  })
  common.failOnWarningOrError(t, dht)

  dht.listen(function () {
    dht.addNode({ host: '127.0.0.1', port: dht.address().port })
    dht.once('node', ready)
  })

  function ready () {
    var keys = ed.createKeyPair(ed.createSeed())
    var publicKey = keys.publicKey
    var secretKey = keys.secretKey

    var opts = {
      seq: 1,
      v: Buffer.from('hello world'),
      salt: Buffer.from('mysalt')
    }

    opts.k = publicKey

    var toEncode = { salt: opts.salt, seq: opts.seq, v: opts.v }

    var encoded = bencode
      .encode(toEncode)
      .slice(1, -1)
      .toString()

    opts.sig = ed
      .sign(encoded, publicKey, secretKey)

    dht.put(opts, function (_, hash) {
      dht.get(hash, function (err, res) {
        t.ifError(err)

        t.equal(res.v.toString('utf8'), opts.v.toString('utf8'),
          'got back what we put in'
        )

        t.equal(res.seq, 1)
        t.end()
      })
    })
  }
})
<|endoftext|>


<commit_before>var assert = require('assert');

var testQuery = function(query, expected, done) {
    filter.query(query, function(err, q) {
        if (err) return done(err);

        try {
            assertObjects(q.toMongo(), expected);
            done();
        } catch (e) {
            done(e);
        }
    });
};

describe('Queries', function(done) {
    it('can convert =', function(done) {
        testQuery("name:Samy", { name: 'Samy' }, done);
    });

    it('can convert = with quotation marks', function(done) {
        testQuery('name:"Samy Pesse"', { name: 'Samy Pesse' }, done);
    });

    it('can convert NOT', function(done) {
        testQuery("NOT name:Samy", { name: { '$ne': 'Samy' } }, done);
    });

    it('can convert NOT (only next condition)', function(done) {
        testQuery("NOT name:Samy followers:10", { name: { '$ne': 'Samy' }, followers: 10 }, done);
    });

    it('can convert >=', function(done) {
        testQuery("followers:>=100", { followers: { '$gte': 100 } }, done);
    });

    it('can convert <=', function(done) {
        testQuery("followers:<=100", { followers: { '$lte': 100 } }, done);
    });

    it('can convert >', function(done) {
        testQuery("followers:>100", { followers: { '$gt': 100 } }, done);
    });

    it('can convert <', function(done) {
        testQuery("followers:<100", { followers: { '$lt': 100 } }, done);
    });

    it('can mix < and >', function(done) {
        testQuery("followers:<100 followers:>50", { followers: { '$lt': 100, '$gt': 50 } }, done);
    });

    it('can convert tags', function(done) {
        testQuery("cat", { tags: { '$in': ["cat"] } }, done);
    });

    it('can convert tags with quotation', function(done) {
        testQuery('"hello world"', { tags: { '$in': ["hello", "world"] } }, done);
    });

    it('can convert multiple tags', function(done) {
        testQuery("cat garfield", { tags: { '$in': ["cat", "garfield"] } }, done);
    });

    it('can invert tags', function(done) {
        testQuery("NOT cat", { tags: { '$nin': ["cat"] } }, done);
    });

    it('can handle tags and inverted tags', function(done) {
        testQuery("dogs NOT cat", { tags: { '$in': ["dogs"], '$nin': ["cat"] } }, done);
    });

    it('can handle multiple tags and inverted tags', function(done) {
        testQuery("dogs rataplan NOT cat NOT garfield", { tags: { '$in': ["dogs", "rataplan"], '$nin': ["cat", "garfield"] } }, done);
    });

    it('can handle tags and comparaison', function(done) {
        testQuery("followers:>10 cats", { followers: { '$gt': 10 }, tags: { '$in': [ 'cats' ] } }, done);
    });

    it('can handle tags and comparaison (2)', function(done) {
        testQuery("cats followers:>10", { tags: { '$in': [ 'cats' ] }, followers: { '$gt': 10 } }, done);
    });

    it('can alias field', function(done) {
        testQuery("mail:samypesse@gmail.com", { email: "samypesse@gmail.com" }, done);
    });

    it("can't accept invalid fields", function(done) {
        testQuery("followers:>=100 invalid:test", { followers: { '$gte': 100 } }, done);
    });

    it('can handle multiples conditions', function(done) {
        testQuery("followers:>=100 stars:<=200", {
            followers: {
                '$gte': 100
            },
            stars: {
                '$lte': 200
            }
        }, done);
    });

    it('can handle multiples conditions and tags', function(done) {
        testQuery("cat NOT dog followers:>=100 stars:<=200", {
            tags: { '$in': [ 'cat' ], '$nin': [ 'dog' ] },
            followers: { '$gte': 100 },
            stars: { '$lte': 200 }
        }, done);
    });

    it('can detect complete queries', function(done) {
        filter.query("followers:>=100", function(err, q) {
            if (err) return done(err);
            if (!q.isComplete()) return done(new Error("Should be completed"));
            done();
        });
    });

    it('can detect non-complete queries', function(done) {
        filter.query("followers:>=100 invalid:test", function(err, q) {
            if (err) return done(err);
            if (q.isComplete()) return done(new Error("Should not be completed"));
            done();
        });
    });

    it('can handle multiple alias for equalities', function(done) {
        testQuery("language:en", {
            '$or': [
                {
                    'settings_language': 'en'
                },
                {
                    'detected_language': 'en'
                }
            ]
        }, done);
    });

    it('can handle multiple alias with other conditions', function(done) {
        testQuery("language:en stars:100", {
            'stars': 100,
            '$or': [
                {
                    'settings_language': 'en'
                },
                {
                    'detected_language': 'en'
                }
            ]
        }, done);
    });

    it('can handle multiple alias for > and <', function(done) {
        testQuery("views:>10", {
            '$or': [
                {
                    'views1': {"$gt": 10}
                },
                {
                    'views2': {"$gt": 10}
                }
            ]
        }, done);
    });

    it('can handle multiple condition for multiple alias for > and <', function(done) {
        testQuery("views:>10 views:<100", {
            '$or': [
                {
                    'views1': {
                        "$gt": 10,
                        "$lt": 100
                    }
                },
                {
                    'views2': {
                        "$gt": 10,
                        "$lt": 100
                    }
                }
            ]
        }, done);
    });

    it('can handle multiple fields with multiple alias', function(done) {
        testQuery("views:>10 language:en",
        {
            "$or":[
                {"views1":{"$gt":10},"settings_language":"en"},
                {"views1":{"$gt":10},"detected_language":"en"},
                {"views2":{"$gt":10},"settings_language":"en"},
                {"views2":{"$gt":10},"detected_language":"en"}
            ]
        }, done);
    });

    it('can handle $in for array', function(done) {
        testQuery("subjects:test",
        {
            "subjects": {
                "$in": ["test"]
            }
        }, done);
    });

    it('can handle $nin for array', function(done) {
        testQuery("NOT subjects:test",
        {
            "subjects": {
                "$nin": ["test"]
            }
        }, done);
    });

    it('can handle values middlewares', function(done) {
        testQuery("cofounder:aaron",
        {
            "associate": "_aaron"
        }, done);
    });

    describe('with inverted operators', function() {

      it('can handle "NOT >"', function(done) {
          testQuery('NOT stars:>10',
          {
            "stars": { "$lte": 10 }
          }, done);
      });

      it('can handle "NOT <"', function(done) {
          testQuery('NOT stars:<10',
          {
            "stars": { "$gte": 10 }
          }, done);
      });

      it('can handle "NOT >="', function(done) {
          testQuery('NOT stars:>=10',
          {
            "stars": { "$lt": 10 }
          }, done);
      });

      it('can handle "NOT <="', function(done) {
          testQuery('NOT stars:<=10',
          {
            "stars": { "$gt": 10 }
          }, done);
      });

    });
});
<commit_msg>Add tests for "is:" operator<commit_after>var assert = require('assert');

var testQuery = function(query, expected, done) {
    filter.query(query, function(err, q) {
        if (err) return done(err);

        try {
            assertObjects(q.toMongo(), expected);
            done();
        } catch (e) {
            done(e);
        }
    });
};

describe('Queries', function(done) {
    it('can convert =', function(done) {
        testQuery("name:Samy", { name: 'Samy' }, done);
    });

    it('can convert = with quotation marks', function(done) {
        testQuery('name:"Samy Pesse"', { name: 'Samy Pesse' }, done);
    });

    it('can convert NOT', function(done) {
        testQuery("NOT name:Samy", { name: { '$ne': 'Samy' } }, done);
    });

    it('can convert NOT (only next condition)', function(done) {
        testQuery("NOT name:Samy followers:10", { name: { '$ne': 'Samy' }, followers: 10 }, done);
    });

    it('can convert >=', function(done) {
        testQuery("followers:>=100", { followers: { '$gte': 100 } }, done);
    });

    it('can convert <=', function(done) {
        testQuery("followers:<=100", { followers: { '$lte': 100 } }, done);
    });

    it('can convert >', function(done) {
        testQuery("followers:>100", { followers: { '$gt': 100 } }, done);
    });

    it('can convert <', function(done) {
        testQuery("followers:<100", { followers: { '$lt': 100 } }, done);
    });

    it('can mix < and >', function(done) {
        testQuery("followers:<100 followers:>50", { followers: { '$lt': 100, '$gt': 50 } }, done);
    });

    it('can convert tags', function(done) {
        testQuery("cat", { tags: { '$in': ["cat"] } }, done);
    });

    it('can convert tags with quotation', function(done) {
        testQuery('"hello world"', { tags: { '$in': ["hello", "world"] } }, done);
    });

    it('can convert multiple tags', function(done) {
        testQuery("cat garfield", { tags: { '$in': ["cat", "garfield"] } }, done);
    });

    it('can invert tags', function(done) {
        testQuery("NOT cat", { tags: { '$nin': ["cat"] } }, done);
    });

    it('can handle tags and inverted tags', function(done) {
        testQuery("dogs NOT cat", { tags: { '$in': ["dogs"], '$nin': ["cat"] } }, done);
    });

    it('can handle multiple tags and inverted tags', function(done) {
        testQuery("dogs rataplan NOT cat NOT garfield", { tags: { '$in': ["dogs", "rataplan"], '$nin': ["cat", "garfield"] } }, done);
    });

    it('can handle tags and comparaison', function(done) {
        testQuery("followers:>10 cats", { followers: { '$gt': 10 }, tags: { '$in': [ 'cats' ] } }, done);
    });

    it('can handle tags and comparaison (2)', function(done) {
        testQuery("cats followers:>10", { tags: { '$in': [ 'cats' ] }, followers: { '$gt': 10 } }, done);
    });

    it('can alias field', function(done) {
        testQuery("mail:samypesse@gmail.com", { email: "samypesse@gmail.com" }, done);
    });

    it("can't accept invalid fields", function(done) {
        testQuery("followers:>=100 invalid:test", { followers: { '$gte': 100 } }, done);
    });

    it('can handle multiples conditions', function(done) {
        testQuery("followers:>=100 stars:<=200", {
            followers: {
                '$gte': 100
            },
            stars: {
                '$lte': 200
            }
        }, done);
    });

    it('can handle multiples conditions and tags', function(done) {
        testQuery("cat NOT dog followers:>=100 stars:<=200", {
            tags: { '$in': [ 'cat' ], '$nin': [ 'dog' ] },
            followers: { '$gte': 100 },
            stars: { '$lte': 200 }
        }, done);
    });

    it('can detect complete queries', function(done) {
        filter.query("followers:>=100", function(err, q) {
            if (err) return done(err);
            if (!q.isComplete()) return done(new Error("Should be completed"));
            done();
        });
    });

    it('can detect non-complete queries', function(done) {
        filter.query("followers:>=100 invalid:test", function(err, q) {
            if (err) return done(err);
            if (q.isComplete()) return done(new Error("Should not be completed"));
            done();
        });
    });

    it('can handle multiple alias for equalities', function(done) {
        testQuery("language:en", {
            '$or': [
                {
                    'settings_language': 'en'
                },
                {
                    'detected_language': 'en'
                }
            ]
        }, done);
    });

    it('can handle multiple alias with other conditions', function(done) {
        testQuery("language:en stars:100", {
            'stars': 100,
            '$or': [
                {
                    'settings_language': 'en'
                },
                {
                    'detected_language': 'en'
                }
            ]
        }, done);
    });

    it('can handle multiple alias for > and <', function(done) {
        testQuery("views:>10", {
            '$or': [
                {
                    'views1': {"$gt": 10}
                },
                {
                    'views2': {"$gt": 10}
                }
            ]
        }, done);
    });

    it('can handle multiple condition for multiple alias for > and <', function(done) {
        testQuery("views:>10 views:<100", {
            '$or': [
                {
                    'views1': {
                        "$gt": 10,
                        "$lt": 100
                    }
                },
                {
                    'views2': {
                        "$gt": 10,
                        "$lt": 100
                    }
                }
            ]
        }, done);
    });

    it('can handle multiple fields with multiple alias', function(done) {
        testQuery("views:>10 language:en",
        {
            "$or":[
                {"views1":{"$gt":10},"settings_language":"en"},
                {"views1":{"$gt":10},"detected_language":"en"},
                {"views2":{"$gt":10},"settings_language":"en"},
                {"views2":{"$gt":10},"detected_language":"en"}
            ]
        }, done);
    });

    it('can handle $in for array', function(done) {
        testQuery("subjects:test",
        {
            "subjects": {
                "$in": ["test"]
            }
        }, done);
    });

    it('can handle $nin for array', function(done) {
        testQuery("NOT subjects:test",
        {
            "subjects": {
                "$nin": ["test"]
            }
        }, done);
    });

    it('can handle values middlewares', function(done) {
        testQuery("cofounder:aaron",
        {
            "associate": "_aaron"
        }, done);
    });

    describe('with inverted operators', function() {

      it('can handle "NOT >"', function(done) {
          testQuery('NOT stars:>10',
          {
            "stars": { "$lte": 10 }
          }, done);
      });

      it('can handle "NOT <"', function(done) {
          testQuery('NOT stars:<10',
          {
            "stars": { "$gte": 10 }
          }, done);
      });

      it('can handle "NOT >="', function(done) {
          testQuery('NOT stars:>=10',
          {
            "stars": { "$lt": 10 }
          }, done);
      });

      it('can handle "NOT <="', function(done) {
          testQuery('NOT stars:<=10',
          {
            "stars": { "$gt": 10 }
          }, done);
      });

    });

    describe('with "is:" operator', function() {

      it('can handle "is:" for Booleans', function(done) {
          testQuery('is:published',
          {
            "published": true
          }, done);
      });

      it('can handle "NOT is:" for Booleans', function(done) {
          testQuery('NOT is:published',
          {
            "published": false
          }, done);
      });

      it('can handle "is:" for Booleans with "alias"', function(done) {
          testQuery('is:admin',
          {
            "isAdmin": true
          }, done);
      });

      it('can handle "NOT is:" for Booleans with "alias"', function(done) {
          testQuery('NOT is:admin',
          {
            "isAdmin": false
          }, done);
      });

      it('can handle "is:" with "query" (String)', function(done) {
          testQuery('is:male',
          {
            "gender": "male"
          }, done);
      });

      it('can handle "NOT is:" with "query" (String)', function(done) {
          testQuery('NOT is:male',
          {
            "gender": { "$ne": "male" }
          }, done);
      });

      it('can handle "is:" with "query" (Number)', function(done) {
          testQuery('is:minor',
          {
            "age": { "$lt": 18 }
          }, done);
      });

      it('can handle "NOT is:" with "query" (Number)', function(done) {
          testQuery('NOT is:minor',
          {
            "age": { "$gte": 18 }
          }, done);
      });

    });
});
<|endoftext|>


<commit_before>const express = require('express');
const bodyParser = require('body-parser');
const variables = require('./variables');

const app = express();
app.use(bodyParser.json());

app.use(express.static('web'));

require('./user-mapping')(app);
require('./sender')(app);

app.listen(variables.port);
console.log('Notifier server started at port ' + variables.port);<commit_msg>Relative path fix<commit_after>const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const variables = require('./variables');

const app = express();
app.use(bodyParser.json());

app.use(express.static(path.join(__dirname, 'web')));

require('./user-mapping')(app);
require('./sender')(app);

app.listen(variables.port);
console.log('Notifier server started at port ' + variables.port);<|endoftext|>


<commit_before>var tape = require("tape")
  , promise = require("bloody-promise")
  , request = require("../")

tape("request.create", function(test){

  var req = request.create("url")
    , req2 = request.create({
        headers: {
          "key" : "value"
        },
        method : "POST",
        url : "url",
        queryString : "foo=bar",
        data : "bar=baz",
        withCredentials : true
      })

  test.equal(req.url, "url", "string is used as url")

  test.equal(req2.url, "url", "url")
  test.equal(req2.headers.key, "value", "headers")
  test.equal(req2.method, "POST", "method")
  test.equal(req2.queryString, "foo=bar", "queryString")
  test.equal(req2.data, "bar=baz", "data")
  test.equal(req2.withCredentials, true, "withCredentials")
  test.end()

})

tape("request._options", function(test){

  var object = {}

  request._options.call(object, "bar", "foo")
  test.equal(object.foo, "bar", "copies prop into object")
  test.end()

})

tape("request._options", function(test){

  var object = {}

  request._options.call(object, "bar", "foo")
  test.equal(object.foo, "bar", "copies prop into object")
  test.end()

})

tape("request._createXHR", function(test){

  test.ok(({}).isPrototypeOf.call(XMLHttpRequest.prototype, request._createXHR()), "returns a new request")
  test.end()

})

tape("request._setHeader", function(test){

  var object = {
    setRequestHeader : function(key, value){
      test.equal(key, "foo", "key")
      test.equal(value, "bar", "value")
      test.end()
    }
  }

  request._setHeader.call(object, "bar", "foo")

})

tape("request._setHeaders", function(test){

  var setRequestHeader = function(key, value){
        this.headers[key] = value
      }
    , getParams = request.create({
        method : "GET",
        headers : null
      })
    , xhrGetParams = {
        headers : {},
        setRequestHeader : setRequestHeader
      }
    , headersGetParams = request.create({
        method : "GET",
        headers : {
          "foo" : "bar"
        }
      })
    , xhrHeadersGetParams = {
        headers : {},
        setRequestHeader : setRequestHeader
      }
    , postParams = request.create({
        method : "POST",
        headers : null
      })
    , xhrPostParams = {
        headers : {},
        setRequestHeader : setRequestHeader
      }
    , headersPostParams = request.create({
        method : "POST",
        headers : {
          "foo" : "bar"
        }
      })
    , xhrHeadersPostParams = {
        headers : {},
        setRequestHeader : setRequestHeader
      }

  getParams._setHeaders(xhrGetParams)
  headersGetParams._setHeaders(xhrHeadersGetParams)
  postParams._setHeaders(xhrPostParams)
  headersPostParams._setHeaders(xhrHeadersPostParams)

  test.deepEqual(xhrGetParams.headers, {}, "get, no headers")
  test.deepEqual(xhrHeadersGetParams.headers, {"foo":"bar"}, "get, headers")
  test.deepEqual(xhrPostParams.headers, {
    "X-Requested-With": "XMLHttpRequest",
    "Content-type": "application/x-www-form-urlencoded"
  }, "post, no headers")
  test.deepEqual(xhrHeadersPostParams.headers, {
    "foo":"bar",
    "X-Requested-With": "XMLHttpRequest",
    "Content-type": "application/x-www-form-urlencoded"
  }, "post, headers")
  test.end()

})

tape("request._createXHRCallback", function(test){

  var xhrPromise = promise.create()
    , xhrCallback = request._createXHRCallback(xhrPromise)
    , obj

  xhrCallback.call({readyState:1})
  xhrCallback.call({readyState:2})
  xhrCallback.call({readyState:3})
  xhrCallback.call(obj = {readyState:4, status:200})

  xhrPromise.then(function(value){
    test.equal(value, obj, "promise is fulfill with 200 status")
    test.end()
  })

})

tape("request._createXHRCallback (failing status)", function(test){

  var xhrPromise = promise.create()
    , xhrCallback = request._createXHRCallback(xhrPromise)
    , obj

  xhrCallback.call({readyState:1})
  xhrCallback.call({readyState:2})
  xhrCallback.call({readyState:3})
  xhrCallback.call(obj = {readyState:4, status:400})

  xhrPromise.then(null, function(value){
    test.equal(value, obj, "promise is rejected with 400 status")
    test.end()
  })

})

tape("request._resolveUrl", function(test){

  test.equal(request._resolveUrl("foo", "bar=baz"), "foo?bar=baz")
  test.equal(request._resolveUrl("foo?", "bar=baz"), "foo?bar=baz")
  test.equal(request._resolveUrl("foo?foo=bar", "bar=baz"), "foo?foo=bar&bar=baz")
  test.end()

})

tape("request.load (url, GET)", function(test){

  test.plan(4)

  var req = request.create("foo")
    , pro = req.load()

  pro.then(function(value){
    test.ok(({}).isPrototypeOf.call(XMLHttpRequest.prototype, value), "passes XMLHttpRequest")
    test.equal(value.responseText, "File not found. :(", "response is right")
    test.equal(value.status, 200, "status is right")
  })
  .then(function(){
    return req.load()
  })
  .then(function(value){
    test.ok(value, "creates a new XHR at .load")
  })

})

tape("request.load (error, POST)", function(test){

  test.plan(3)

  var req = request.create({
        url : "bar",
        method : "POST"
      })
    , pro = req.load()

  pro.then(function(){
    test.fail()
  }, function(value){
    test.ok(({}).isPrototypeOf.call(XMLHttpRequest.prototype, value), "passes XMLHttpRequest")
    test.equal(value.responseText, "", "response is right")
    test.ok(value.status == 405 || value.status == 0 /* local tests */, "status is right")
  })

})<commit_msg>IE, you're a pain in the arse, really<commit_after>var tape = require("tape")
  , promise = require("bloody-promise")
  , request = require("../")

tape("request.create", function(test){

  var req = request.create("url")
    , req2 = request.create({
        headers: {
          "key" : "value"
        },
        method : "POST",
        url : "url",
        queryString : "foo=bar",
        data : "bar=baz",
        withCredentials : true
      })

  test.equal(req.url, "url", "string is used as url")

  test.equal(req2.url, "url", "url")
  test.equal(req2.headers.key, "value", "headers")
  test.equal(req2.method, "POST", "method")
  test.equal(req2.queryString, "foo=bar", "queryString")
  test.equal(req2.data, "bar=baz", "data")
  test.equal(req2.withCredentials, true, "withCredentials")
  test.end()

})

tape("request._options", function(test){

  var object = {}

  request._options.call(object, "bar", "foo")
  test.equal(object.foo, "bar", "copies prop into object")
  test.end()

})

tape("request._options", function(test){

  var object = {}

  request._options.call(object, "bar", "foo")
  test.equal(object.foo, "bar", "copies prop into object")
  test.end()

})

tape("request._createXHR", function(test){

  test.ok(XMLHttpRequest.prototype.isPrototypeOf(request._createXHR()), "returns a new request")
  test.end()

})

tape("request._setHeader", function(test){

  var object = {
    setRequestHeader : function(key, value){
      test.equal(key, "foo", "key")
      test.equal(value, "bar", "value")
      test.end()
    }
  }

  request._setHeader.call(object, "bar", "foo")

})

tape("request._setHeaders", function(test){

  var setRequestHeader = function(key, value){
        this.headers[key] = value
      }
    , getParams = request.create({
        method : "GET",
        headers : null
      })
    , xhrGetParams = {
        headers : {},
        setRequestHeader : setRequestHeader
      }
    , headersGetParams = request.create({
        method : "GET",
        headers : {
          "foo" : "bar"
        }
      })
    , xhrHeadersGetParams = {
        headers : {},
        setRequestHeader : setRequestHeader
      }
    , postParams = request.create({
        method : "POST",
        headers : null
      })
    , xhrPostParams = {
        headers : {},
        setRequestHeader : setRequestHeader
      }
    , headersPostParams = request.create({
        method : "POST",
        headers : {
          "foo" : "bar"
        }
      })
    , xhrHeadersPostParams = {
        headers : {},
        setRequestHeader : setRequestHeader
      }

  getParams._setHeaders(xhrGetParams)
  headersGetParams._setHeaders(xhrHeadersGetParams)
  postParams._setHeaders(xhrPostParams)
  headersPostParams._setHeaders(xhrHeadersPostParams)

  test.deepEqual(xhrGetParams.headers, {}, "get, no headers")
  test.deepEqual(xhrHeadersGetParams.headers, {"foo":"bar"}, "get, headers")
  test.deepEqual(xhrPostParams.headers, {
    "X-Requested-With": "XMLHttpRequest",
    "Content-type": "application/x-www-form-urlencoded"
  }, "post, no headers")
  test.deepEqual(xhrHeadersPostParams.headers, {
    "foo":"bar",
    "X-Requested-With": "XMLHttpRequest",
    "Content-type": "application/x-www-form-urlencoded"
  }, "post, headers")
  test.end()

})

tape("request._createXHRCallback", function(test){

  var xhrPromise = promise.create()
    , xhrCallback = request._createXHRCallback(xhrPromise)
    , obj

  xhrCallback.call({readyState:1})
  xhrCallback.call({readyState:2})
  xhrCallback.call({readyState:3})
  xhrCallback.call(obj = {readyState:4, status:200})

  xhrPromise.then(function(value){
    test.equal(value, obj, "promise is fulfill with 200 status")
    test.end()
  })

})

tape("request._createXHRCallback (failing status)", function(test){

  var xhrPromise = promise.create()
    , xhrCallback = request._createXHRCallback(xhrPromise)
    , obj

  xhrCallback.call({readyState:1})
  xhrCallback.call({readyState:2})
  xhrCallback.call({readyState:3})
  xhrCallback.call(obj = {readyState:4, status:400})

  xhrPromise.then(null, function(value){
    test.equal(value, obj, "promise is rejected with 400 status")
    test.end()
  })

})

tape("request._resolveUrl", function(test){

  test.equal(request._resolveUrl("foo", "bar=baz"), "foo?bar=baz")
  test.equal(request._resolveUrl("foo?", "bar=baz"), "foo?bar=baz")
  test.equal(request._resolveUrl("foo?foo=bar", "bar=baz"), "foo?foo=bar&bar=baz")
  test.end()

})

tape("request.load (url, GET)", function(test){

  test.plan(4)

  var req = request.create("foo")
    , pro = req.load()

  pro.then(function(value){
    test.ok(XMLHttpRequest.prototype.isPrototypeOf(value), "passes XMLHttpRequest")
    test.equal(value.responseText, "File not found. :(", "response is right")
    test.equal(value.status, 200, "status is right")
  })
  .then(function(){
    return req.load()
  })
  .then(function(value){
    test.ok(value, "creates a new XHR at .load")
  })

})

tape("request.load (error, POST)", function(test){

  test.plan(3)

  var req = request.create({
        url : "bar",
        method : "POST"
      })
    , pro = req.load()

  pro.then(function(){
    test.fail()
  }, function(value){
    test.ok(XMLHttpRequest.prototype.isPrototypeOf(value), "passes XMLHttpRequest")
    test.equal(value.responseText, "", "response is right")
    test.ok(value.status == 405 || value.status == 0 /* local tests */, "status is right")
  })

})<|endoftext|>


<commit_before>

var fs = require('fs'),
    path = require('path'),
    winston = require('winston'),
    jitsu = require('../jitsu');

var commands = exports;

//
// Setup the commands organized by resource to be lazy loaded
// when needed. This speeds up load time.
//
commands.commands = {};
fs.readdirSync(path.join(__dirname, 'commands')).forEach(function (cmd) {
  cmd = cmd.replace('.js', '');
  commands.commands.__defineGetter__(cmd, function () {
    return require('./commands/' + cmd);
  });
});

var requireAuth = ['apps', 'databases', 'env', 'logs', 'snapshots', 'install', 'knockout'];

commands.requiresAuth = function (resource) {
  return requireAuth.indexOf(resource) !== -1;
};

//
// ### function run (command, callback)
// #### @command {Array} Command to run
// #### @callback {function} Continuation to pass control to when complete.
// Runs the specified command.
//
commands.run = function (command, callback) {
  var parts = command.slice(0),
      name = parts.shift(),
      action = parts.shift(),
      command, expected, resource;

  //
  // If we have been asked for `help` or `usage`
  // about a particular resource, print the help
  // for that resource.
  //
  if (action === 'help') {
    commands.commands.help.show(name);
    return callback();
  }
  else if (name === 'help' && (!action || action === 'show')) {
    commands.commands.help.show('help');
    return callback();
  }

  if (!commands.commands[name]) {
    return callback(new Error('Cannot run command on unknown resource: ' + name), true);
  }

  if (typeof commands.commands[name] !== 'function') {
    if (!action) {
      winston.error('Action is required to run a command on resource: ' + name.magenta);
      commands.commands.help.show(name);
      return callback(true);
    }

    resource = commands.commands[name];
    if (!resource[action]) {
      winston.error('Unknown action ' + action + ' on resource ' + name.magenta);
      commands.commands.help.show(name);
      return callback(true);
    }

    command = resource[action];
  }
  else {
    if (action) {
      parts.unshift(action);
    }

    command = commands.commands[name];
  }

  //
  // When the command completes, check for an error, and if
  // we are surpressing the err callstack (i.e. it is an **expected** error)
  // then print the usage of the specified command.
  //
  parts.push(function (err, shallow, skip) {
    if (err && shallow && !skip) {
      winston.help('');
      winston.help('Usage:'.cyan.bold.underline);
      command.usage.forEach(function (line) {
        winston.help(line);
      });
      winston.help('');
    }

    callback(err, shallow);
  });

  //
  // Check the arguments length then execute the command.
  //
  expected = command.length;
  if (parts.length > expected) {
    return callback(new Error('Wrong number of arguments: ' + parts.length + ' for ' + expected), true);
  }

  function runCommand() {
    command.apply(resource, parts);
  }

  //
  // If this resource can only be accessed
  // after authenticating with Nodejitsu, do so
  // then run the specified command on the resource
  //
  if (requireAuth.indexOf(name) !== -1) {
    return jitsu.auth(function (err) {
      if (err) {
        return callback(err);
      }

      runCommand();
    });
  }

  runCommand();
};

commands.alias = function (target, source) {
  commands.commands.__defineGetter__(target, function () {
    var resource = commands.commands[source.resource];
    return resource[source.command]
  });

  if (requireAuth.indexOf(source.resource) !== -1) {
    requireAuth.push(target);
  }
};
<commit_msg>[api] jitsu install no longer requires a nodejitsu account<commit_after>

var fs = require('fs'),
    path = require('path'),
    winston = require('winston'),
    jitsu = require('../jitsu');

var commands = exports;

//
// Setup the commands organized by resource to be lazy loaded
// when needed. This speeds up load time.
//
commands.commands = {};
fs.readdirSync(path.join(__dirname, 'commands')).forEach(function (cmd) {
  cmd = cmd.replace('.js', '');
  commands.commands.__defineGetter__(cmd, function () {
    return require('./commands/' + cmd);
  });
});

var requireAuth = ['apps', 'databases', 'env', 'logs', 'snapshots', 'knockout'];

commands.requiresAuth = function (resource) {
  return requireAuth.indexOf(resource) !== -1;
};

//
// ### function run (command, callback)
// #### @command {Array} Command to run
// #### @callback {function} Continuation to pass control to when complete.
// Runs the specified command.
//
commands.run = function (command, callback) {
  var parts = command.slice(0),
      name = parts.shift(),
      action = parts.shift(),
      command, expected, resource;

  //
  // If we have been asked for `help` or `usage`
  // about a particular resource, print the help
  // for that resource.
  //
  if (action === 'help') {
    commands.commands.help.show(name);
    return callback();
  }
  else if (name === 'help' && (!action || action === 'show')) {
    commands.commands.help.show('help');
    return callback();
  }

  if (!commands.commands[name]) {
    return callback(new Error('Cannot run command on unknown resource: ' + name), true);
  }

  if (typeof commands.commands[name] !== 'function') {
    if (!action) {
      winston.error('Action is required to run a command on resource: ' + name.magenta);
      commands.commands.help.show(name);
      return callback(true);
    }

    resource = commands.commands[name];
    if (!resource[action]) {
      winston.error('Unknown action ' + action + ' on resource ' + name.magenta);
      commands.commands.help.show(name);
      return callback(true);
    }

    command = resource[action];
  }
  else {
    if (action) {
      parts.unshift(action);
    }

    command = commands.commands[name];
  }

  //
  // When the command completes, check for an error, and if
  // we are surpressing the err callstack (i.e. it is an **expected** error)
  // then print the usage of the specified command.
  //
  parts.push(function (err, shallow, skip) {
    if (err && shallow && !skip) {
      winston.help('');
      winston.help('Usage:'.cyan.bold.underline);
      command.usage.forEach(function (line) {
        winston.help(line);
      });
      winston.help('');
    }

    callback(err, shallow);
  });

  //
  // Check the arguments length then execute the command.
  //
  expected = command.length;
  if (parts.length > expected) {
    return callback(new Error('Wrong number of arguments: ' + parts.length + ' for ' + expected), true);
  }

  function runCommand() {
    command.apply(resource, parts);
  }

  //
  // If this resource can only be accessed
  // after authenticating with Nodejitsu, do so
  // then run the specified command on the resource
  //
  if (requireAuth.indexOf(name) !== -1) {
    return jitsu.auth(function (err) {
      if (err) {
        return callback(err);
      }

      runCommand();
    });
  }

  runCommand();
};

commands.alias = function (target, source) {
  commands.commands.__defineGetter__(target, function () {
    var resource = commands.commands[source.resource];
    return resource[source.command]
  });

  if (requireAuth.indexOf(source.resource) !== -1) {
    requireAuth.push(target);
  }
};
<|endoftext|>


<commit_before>
//*****************************************************************************************************
// handle sticky sidebar calculations
//*****************************************************************************************************
function SES_IsScrolledTo( elem ) {

    var doc_top     = jQuery( window ).scrollTop(); //num of pixels hidden above current screen
    var doc_bottom  = doc_top + jQuery( window ).height();
    var elem_top    = jQuery( elem ).offset().top; //num of pixels above the elem
    var elem_bottom = elem_top + jQuery( elem ).height();

    // account for Admin Bar if present
    if ( jQuery( '#wpadminbar' ).length ){
        elem_top -= jQuery( '#wpadminbar' ).outerHeight() + parseInt( stickyVars.y_offset, 10 );
    }

    return ( ( elem_top <= doc_top ) );
}

//*****************************************************************************************************
// the core sticky side function
//*****************************************************************************************************
function SES_SideStickyLoader( SES_ScreenSize, stickyID ) {

    // bail on pages without body class
    if ( ! jQuery( 'body' ).hasClass( 'sticky-publish-box' ) ) {
        return;
    }

    // bail if we dont have our wpcontent div ID
    if ( ! jQuery( '#side-sortables' ).length ) {
        return;
    }

    // check the width of our container (since we dont side by side on mobile)
    // and load if we are above the breakpoint
    if ( SES_ScreenSize > stickyVars.breakpoint ) {
        SES_SideSticky( '#side-sortables', stickyID );
    }

	// bail if the box is closed
	if ( jQuery( stickyID ).hasClass( 'closed' ) ) {

		// clear out any stuff
		SES_SideStickyRemoval( '#side-sortables', stickyID );

		// and bail
		return;
	}

    // now do our check again on resize
    jQuery( window ).resize( function() {

        // get our new width
        SES_ScreenSize   = jQuery( window ).width();

        // apply if on tablet or above
        if ( SES_ScreenSize > stickyVars.breakpoint ) {
            SES_SideSticky( '#side-sortables', stickyID );
        } else {
            SES_SideStickyRemoval( '#side-sortables', stickyID );
        }
    });

}

//*****************************************************************************************************
// make the sticky editor sidebar
//*****************************************************************************************************
function SES_SideSticky( stickyWrap, stickyID ) {

    // get our offset
    var offTop          = jQuery( stickyWrap ).offset().top - 50,
        stickyAttach	= jQuery( stickyID );

    // check the position on load
    SES_SideStickyMaybeInit( stickyWrap, stickyAttach, stickyID, offTop );

    // start checking on scroll
    jQuery( window ).scroll( function() {

        // if we hit our mark
        SES_SideStickyMaybeInit( stickyWrap, stickyAttach, stickyID, offTop );

        // if we get back to the top, remove our stuff
        if ( ( offTop + parseInt( stickyVars.y_offset, 10 ) ) > stickyAttach.offset().top ) {
        	SES_SideStickyRemoval( stickyWrap, stickyAttach );
        }
    });
}

//*****************************************************************************************************
// run the actual sticky functionality if need be
//*****************************************************************************************************
function SES_SideStickyMaybeInit( stickyWrap, stickyAttach, stickyID, offTop ) {

    if ( SES_IsScrolledTo( stickyAttach ) && ! jQuery( stickyID ).hasClass( 'closed' ) ) {

        // get our sizes and offsets
        var pubWth  = jQuery( stickyID ).width();
        var offRgt  = ( jQuery( window ).width() - ( jQuery( stickyID ).offset().left + jQuery( stickyID ).outerWidth() ) );

        // add the actual sticky CSS
        stickyAttach.css({
            'width' : pubWth + 'px',
            'position' : 'fixed',
            'top' : offTop + 'px',
            'right' : offRgt + 'px',
            'z-index' : '9999',
        });

        // implement a faux clone so that sidebar items don't jump when we go sticky
        jQuery( '.postbox-container' ).css( 'padding-top', ( parseInt( stickyVars.y_offset, 10 ) + jQuery( stickyVars.stickyid ).outerHeight() ) + 'px' );

        // set the opacity of all the other items
        jQuery( stickyWrap ).find( '.postbox' ).not( stickyAttach ).css( 'opacity', stickyVars.opacity );
    }
}

//*****************************************************************************************************
// the removal function for the stickybox
//*****************************************************************************************************
function SES_SideStickyRemoval( stickyWrap, stickyID ) {

	// remove the sticky CSS
	jQuery( stickyID ).removeAttr( 'style' );

    // remove the opacity of all the other items
    jQuery( stickyWrap ).find( '.postbox' ).not( '.sticky-side-wrapper' ).css( 'opacity', '' );

    // remove our faux clone padding
    jQuery( '.postbox-container' ).css( 'padding-top', '' );
}

//*****************************************************************************************************
// start the engine
//*****************************************************************************************************
jQuery(document).ready( function($) {

//*****************************************************************************************************
// check our screen size on itital load
//*****************************************************************************************************
    var SES_ScreenSize = $( window ).width();

//*****************************************************************************************************
// make the preset box sticky for items we set with the class
//*****************************************************************************************************
    $( window ).load( function() {
    	if ( ! $( stickyVars.stickyid ).hasClass( 'closed' ) ) {
    		SES_SideStickyLoader( SES_ScreenSize, stickyVars.stickyid );
    	}
    });

//*****************************************************************************************************
// check for open / close of metabox and reload sticky
//*****************************************************************************************************
	$( stickyVars.stickyid ).on( 'click', '.handlediv', function() {
    	if ( ! $( stickyVars.stickyid ).hasClass( 'closed' ) ) {
    		SES_SideStickyLoader( SES_ScreenSize, stickyVars.stickyid );
    	} else {
    		SES_SideStickyRemoval( '#side-sortables', stickyVars.stickyid );
    	}
	});

//*****************************************************************************************************
// we are done here. go home
//*****************************************************************************************************
});
<commit_msg>Adding padding-top was too lenient<commit_after>
//*****************************************************************************************************
// handle sticky sidebar calculations
//*****************************************************************************************************
function SES_IsScrolledTo( elem ) {

    var doc_top     = jQuery( window ).scrollTop(); //num of pixels hidden above current screen
    var doc_bottom  = doc_top + jQuery( window ).height();
    var elem_top    = jQuery( elem ).offset().top; //num of pixels above the elem
    var elem_bottom = elem_top + jQuery( elem ).height();

    // account for Admin Bar if present
    if ( jQuery( '#wpadminbar' ).length ){
        elem_top -= jQuery( '#wpadminbar' ).outerHeight() + parseInt( stickyVars.y_offset, 10 );
    }

    return ( ( elem_top <= doc_top ) );
}

//*****************************************************************************************************
// the core sticky side function
//*****************************************************************************************************
function SES_SideStickyLoader( SES_ScreenSize, stickyID ) {

    // bail on pages without body class
    if ( ! jQuery( 'body' ).hasClass( 'sticky-publish-box' ) ) {
        return;
    }

    // bail if we dont have our wpcontent div ID
    if ( ! jQuery( '#side-sortables' ).length ) {
        return;
    }

    // check the width of our container (since we dont side by side on mobile)
    // and load if we are above the breakpoint
    if ( SES_ScreenSize > stickyVars.breakpoint ) {
        SES_SideSticky( '#side-sortables', stickyID );
    }

	// bail if the box is closed
	if ( jQuery( stickyID ).hasClass( 'closed' ) ) {

		// clear out any stuff
		SES_SideStickyRemoval( '#side-sortables', stickyID );

		// and bail
		return;
	}

    // now do our check again on resize
    jQuery( window ).resize( function() {

        // get our new width
        SES_ScreenSize   = jQuery( window ).width();

        // apply if on tablet or above
        if ( SES_ScreenSize > stickyVars.breakpoint ) {
            SES_SideSticky( '#side-sortables', stickyID );
        } else {
            SES_SideStickyRemoval( '#side-sortables', stickyID );
        }
    });

}

//*****************************************************************************************************
// make the sticky editor sidebar
//*****************************************************************************************************
function SES_SideSticky( stickyWrap, stickyID ) {

    // get our offset
    var offTop          = jQuery( stickyWrap ).offset().top - 50,
        stickyAttach	= jQuery( stickyID );

    // check the position on load
    SES_SideStickyMaybeInit( stickyWrap, stickyAttach, stickyID, offTop );

    // start checking on scroll
    jQuery( window ).scroll( function() {

        // if we hit our mark
        SES_SideStickyMaybeInit( stickyWrap, stickyAttach, stickyID, offTop );

        // if we get back to the top, remove our stuff
        if ( ( offTop + parseInt( stickyVars.y_offset, 10 ) ) > stickyAttach.offset().top ) {
        	SES_SideStickyRemoval( stickyWrap, stickyAttach );
        }
    });
}

//*****************************************************************************************************
// run the actual sticky functionality if need be
//*****************************************************************************************************
function SES_SideStickyMaybeInit( stickyWrap, stickyAttach, stickyID, offTop ) {

    if ( SES_IsScrolledTo( stickyAttach ) && ! jQuery( stickyID ).hasClass( 'closed' ) ) {

        // get our sizes and offsets
        var pubWth  = jQuery( stickyID ).width();
        var offRgt  = ( jQuery( window ).width() - ( jQuery( stickyID ).offset().left + jQuery( stickyID ).outerWidth() ) );

        // add the actual sticky CSS
        stickyAttach.css({
            'width' : pubWth + 'px',
            'position' : 'fixed',
            'top' : offTop + 'px',
            'right' : offRgt + 'px',
            'z-index' : '9999',
        });

        // implement a faux clone so that sidebar items don't jump when we go sticky
        jQuery( '#postbox-container-1' ).css( 'padding-top', ( parseInt( stickyVars.y_offset, 10 ) + jQuery( stickyVars.stickyid ).outerHeight() ) + 'px' );

        // set the opacity of all the other items
        jQuery( stickyWrap ).find( '.postbox' ).not( stickyAttach ).css( 'opacity', stickyVars.opacity );
    }
}

//*****************************************************************************************************
// the removal function for the stickybox
//*****************************************************************************************************
function SES_SideStickyRemoval( stickyWrap, stickyID ) {

	// remove the sticky CSS
	jQuery( stickyID ).removeAttr( 'style' );

    // remove the opacity of all the other items
    jQuery( stickyWrap ).find( '.postbox' ).not( '.sticky-side-wrapper' ).css( 'opacity', '' );

    // remove our faux clone padding
    jQuery( '#postbox-container-1' ).css( 'padding-top', '' );
}

//*****************************************************************************************************
// start the engine
//*****************************************************************************************************
jQuery(document).ready( function($) {

//*****************************************************************************************************
// check our screen size on itital load
//*****************************************************************************************************
    var SES_ScreenSize = $( window ).width();

//*****************************************************************************************************
// make the preset box sticky for items we set with the class
//*****************************************************************************************************
    $( window ).load( function() {
    	if ( ! $( stickyVars.stickyid ).hasClass( 'closed' ) ) {
    		SES_SideStickyLoader( SES_ScreenSize, stickyVars.stickyid );
    	}
    });

//*****************************************************************************************************
// check for open / close of metabox and reload sticky
//*****************************************************************************************************
	$( stickyVars.stickyid ).on( 'click', '.handlediv', function() {
    	if ( ! $( stickyVars.stickyid ).hasClass( 'closed' ) ) {
    		SES_SideStickyLoader( SES_ScreenSize, stickyVars.stickyid );
    	} else {
    		SES_SideStickyRemoval( '#side-sortables', stickyVars.stickyid );
    	}
	});

//*****************************************************************************************************
// we are done here. go home
//*****************************************************************************************************
});
<|endoftext|>


<commit_before>/* @flow */

import _ from "lodash";
import * as kernelspecs from "kernelspecs";
import { launchSpec } from "spawnteract";
import { shell } from "electron";

import ZMQKernel from "./zmq-kernel";
import Kernel from "./kernel";

import KernelPicker from "./kernel-picker";
import store from "./store";
import { getEditorDirectory, kernelSpecProvidesGrammar, log } from "./utils";

import type { Connection } from "./zmq-kernel";

export const ks = kernelspecs;

export class KernelManager {
  kernelSpecs: ?Array<Kernelspec> = null;
  kernelPicker: ?KernelPicker;

  startKernelFor(
    grammar: atom$Grammar,
    editor: atom$TextEditor,
    filePath: string,
    onStarted: (kernel: ZMQKernel) => void
  ) {
    this.getKernelSpecForGrammar(grammar).then(kernelSpec => {
      if (!kernelSpec) {
        const message = `No kernel for grammar \`${grammar.name}\` found`;
        const pythonDescription =
          grammar && /python/g.test(grammar.scopeName)
            ? "\n\nTo detect your current Python install you will need to run:
python -m pip install ipykernel\npython -m ipykernel install --user
"
            : "";
        const description = `Check that the language for this file is set in Atom and that you have a Jupyter kernel installed for it.${pythonDescription}`;
        atom.notifications.addError(message, {
          description,
          dismissable: pythonDescription !== ""
        });
        return;
      }

      this.startKernel(kernelSpec, grammar, editor, filePath, onStarted);
    });
  }

  startKernel(
    kernelSpec: Kernelspec,
    grammar: atom$Grammar,
    editor: atom$TextEditor,
    filePath: string,
    onStarted: ?(kernel: ZMQKernel) => void
  ) {
    const displayName = kernelSpec.display_name;

    // if kernel startup already in progress don't start additional kernel
    if (store.startingKernels.get(displayName)) return;

    store.startKernel(displayName);

    let currentPath = getEditorDirectory(editor);
    let projectPath;

    log("KernelManager: startKernel:", displayName);

    switch (atom.config.get("Hydrogen.startDir")) {
      case "firstProjectDir":
        projectPath = atom.project.getPaths()[0];
        break;
      case "projectDirOfFile":
        projectPath = atom.project.relativizePath(currentPath)[0];
        break;
    }

    const kernelStartDir = projectPath != null ? projectPath : currentPath;
    const options = {
      cwd: kernelStartDir,
      stdio: ["ignore", "pipe", "pipe"]
    };

    const transport = new ZMQKernel(kernelSpec, grammar, options, () => {
      const kernel = new Kernel(transport);
      store.newKernel(kernel, filePath, editor, grammar);
      if (onStarted) onStarted(kernel);
    });
  }

  async update() {
    const kernelSpecs = await ks.findAll();
    this.kernelSpecs = _.map(kernelSpecs, "spec");
    return this.kernelSpecs;
  }

  async getAllKernelSpecs(grammar: ?atom$Grammar) {
    if (this.kernelSpecs) return this.kernelSpecs;
    return this.updateKernelSpecs(grammar);
  }

  async getAllKernelSpecsForGrammar(grammar: ?atom$Grammar) {
    if (!grammar) return [];

    const kernelSpecs = await this.getAllKernelSpecs(grammar);
    return kernelSpecs.filter(spec => kernelSpecProvidesGrammar(spec, grammar));
  }

  async getKernelSpecForGrammar(grammar: atom$Grammar) {
    const kernelSpecs = await this.getAllKernelSpecsForGrammar(grammar);
    if (kernelSpecs.length <= 1) {
      return kernelSpecs[0];
    }

    if (this.kernelPicker) {
      this.kernelPicker.kernelSpecs = kernelSpecs;
    } else {
      this.kernelPicker = new KernelPicker(kernelSpecs);
    }

    return new Promise(resolve => {
      if (!this.kernelPicker) return resolve(null);
      this.kernelPicker.onConfirmed = kernelSpec => resolve(kernelSpec);
      this.kernelPicker.toggle();
    });
  }

  async updateKernelSpecs(grammar: ?atom$Grammar) {
    const kernelSpecs = await this.update();

    if (kernelSpecs.length === 0) {
      const message = "No Kernels Installed";

      const options = {
        description:
          "No kernels are installed on your system so you will not be able to execute code in any language.",
        dismissable: true,
        buttons: [
          {
            text: "Install Instructions",
            onDidClick: () =>
              shell.openExternal(
                "https://nteract.gitbooks.io/hydrogen/docs/Installation.html"
              )
          },
          {
            text: "Popular Kernels",
            onDidClick: () => shell.openExternal("https://nteract.io/kernels")
          },
          {
            text: "All Kernels",
            onDidClick: () =>
              shell.openExternal(
                "https://github.com/jupyter/jupyter/wiki/Jupyter-kernels"
              )
          }
        ]
      };
      atom.notifications.addError(message, options);
    } else {
      const message = "Hydrogen Kernels updated:";
      const options = {
        detail: _.map(kernelSpecs, "display_name").join("\n")
      };
      atom.notifications.addInfo(message, options);
    }
    return kernelSpecs;
  }
}

export default new KernelManager();
<commit_msg>kernelspecs sort by display_name<commit_after>/* @flow */

import _ from "lodash";
import * as kernelspecs from "kernelspecs";
import { launchSpec } from "spawnteract";
import { shell } from "electron";

import ZMQKernel from "./zmq-kernel";
import Kernel from "./kernel";

import KernelPicker from "./kernel-picker";
import store from "./store";
import { getEditorDirectory, kernelSpecProvidesGrammar, log } from "./utils";

import type { Connection } from "./zmq-kernel";

export const ks = kernelspecs;

export class KernelManager {
  kernelSpecs: ?Array<Kernelspec> = null;
  kernelPicker: ?KernelPicker;

  startKernelFor(
    grammar: atom$Grammar,
    editor: atom$TextEditor,
    filePath: string,
    onStarted: (kernel: ZMQKernel) => void
  ) {
    this.getKernelSpecForGrammar(grammar).then(kernelSpec => {
      if (!kernelSpec) {
        const message = `No kernel for grammar \`${grammar.name}\` found`;
        const pythonDescription =
          grammar && /python/g.test(grammar.scopeName)
            ? "\n\nTo detect your current Python install you will need to run:
python -m pip install ipykernel\npython -m ipykernel install --user
"
            : "";
        const description = `Check that the language for this file is set in Atom and that you have a Jupyter kernel installed for it.${pythonDescription}`;
        atom.notifications.addError(message, {
          description,
          dismissable: pythonDescription !== ""
        });
        return;
      }

      this.startKernel(kernelSpec, grammar, editor, filePath, onStarted);
    });
  }

  startKernel(
    kernelSpec: Kernelspec,
    grammar: atom$Grammar,
    editor: atom$TextEditor,
    filePath: string,
    onStarted: ?(kernel: ZMQKernel) => void
  ) {
    const displayName = kernelSpec.display_name;

    // if kernel startup already in progress don't start additional kernel
    if (store.startingKernels.get(displayName)) return;

    store.startKernel(displayName);

    let currentPath = getEditorDirectory(editor);
    let projectPath;

    log("KernelManager: startKernel:", displayName);

    switch (atom.config.get("Hydrogen.startDir")) {
      case "firstProjectDir":
        projectPath = atom.project.getPaths()[0];
        break;
      case "projectDirOfFile":
        projectPath = atom.project.relativizePath(currentPath)[0];
        break;
    }

    const kernelStartDir = projectPath != null ? projectPath : currentPath;
    const options = {
      cwd: kernelStartDir,
      stdio: ["ignore", "pipe", "pipe"]
    };

    const transport = new ZMQKernel(kernelSpec, grammar, options, () => {
      const kernel = new Kernel(transport);
      store.newKernel(kernel, filePath, editor, grammar);
      if (onStarted) onStarted(kernel);
    });
  }

  async update() {
    const kernelSpecs = await ks.findAll();
    this.kernelSpecs = _.sortBy(_.map(kernelSpecs, "spec"), spec => spec.display_name);
    return this.kernelSpecs;
  }

  async getAllKernelSpecs(grammar: ?atom$Grammar) {
    if (this.kernelSpecs) return this.kernelSpecs;
    return this.updateKernelSpecs(grammar);
  }

  async getAllKernelSpecsForGrammar(grammar: ?atom$Grammar) {
    if (!grammar) return [];

    const kernelSpecs = await this.getAllKernelSpecs(grammar);
    return kernelSpecs.filter(spec => kernelSpecProvidesGrammar(spec, grammar));
  }

  async getKernelSpecForGrammar(grammar: atom$Grammar) {
    const kernelSpecs = await this.getAllKernelSpecsForGrammar(grammar);
    if (kernelSpecs.length <= 1) {
      return kernelSpecs[0];
    }

    if (this.kernelPicker) {
      this.kernelPicker.kernelSpecs = kernelSpecs;
    } else {
      this.kernelPicker = new KernelPicker(kernelSpecs);
    }

    return new Promise(resolve => {
      if (!this.kernelPicker) return resolve(null);
      this.kernelPicker.onConfirmed = kernelSpec => resolve(kernelSpec);
      this.kernelPicker.toggle();
    });
  }

  async updateKernelSpecs(grammar: ?atom$Grammar) {
    const kernelSpecs = await this.update();

    if (kernelSpecs.length === 0) {
      const message = "No Kernels Installed";

      const options = {
        description:
          "No kernels are installed on your system so you will not be able to execute code in any language.",
        dismissable: true,
        buttons: [
          {
            text: "Install Instructions",
            onDidClick: () =>
              shell.openExternal(
                "https://nteract.gitbooks.io/hydrogen/docs/Installation.html"
              )
          },
          {
            text: "Popular Kernels",
            onDidClick: () => shell.openExternal("https://nteract.io/kernels")
          },
          {
            text: "All Kernels",
            onDidClick: () =>
              shell.openExternal(
                "https://github.com/jupyter/jupyter/wiki/Jupyter-kernels"
              )
          }
        ]
      };
      atom.notifications.addError(message, options);
    } else {
      const message = "Hydrogen Kernels updated:";
      const options = {
        detail: _.map(kernelSpecs, "display_name").join("\n")
      };
      atom.notifications.addInfo(message, options);
    }
    return kernelSpecs;
  }
}

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


<commit_before>import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { faBars } from '@fortawesome/free-solid-svg-icons';

import Box from '../Box';
import VisuallyHidden from '../VisuallyHidden';
import { Media } from '../Media';
import Drawer from '../Drawer';
import Icon from '../Icon';
import Logo from '../Logo';

import MainMenu from './MainMenu';

const Header = ({ mapCenter, children }) => {
  const [isMenuVisible, setIsMenuVisible] = useState(false);

  return (
    <Box
      as="header"
      display="flex"
      alignItems="center"
      px={[3, 4]}
      py={2}
      bg="white"
      minHeight={60}
    >
      <Box flexShrink={0}>
        <Link to="/">
          <Logo />
        </Link>
      </Box>

      <Box as="nav" width="100%" aria-labelledby="menu-main">

          <VisuallyHidden>Main menu</VisuallyHidden>

        <Box as={Media} at="sm" display="flex" justifyContent="flex-end">
          <button
            type="button"
            aria-expanded={isMenuVisible}
            onClick={() => setIsMenuVisible(!isMenuVisible)}
          >
            <VisuallyHidden>Toggle main menu</VisuallyHidden>
            <Icon icon={faBars} size="2x" />
          </button>

          <Drawer visible={isMenuVisible} zIndex={200}>
            <MainMenu
              mapCenter={mapCenter}
              onMenuItemClick={() => setIsMenuVisible(false)}
              children={children}
            />
          </Drawer>
        </Box>

        <Media greaterThan="sm">
          <MainMenu mapCenter={mapCenter} children={children} />
        </Media>
      </Box>
    </Box>
  );
};

export default Header;
<commit_msg>feat: show covid notification<commit_after>import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { faBars, faTimes } from '@fortawesome/free-solid-svg-icons';

import Box from '../Box';
import VisuallyHidden from '../VisuallyHidden';
import { Media } from '../Media';
import Drawer from '../Drawer';
import Icon from '../Icon';
import Logo from '../Logo';
import Text from '../Text';
import Spacer from '../Spacer';

import MainMenu from './MainMenu';

import config from '../../config';

const CovidNotification = ({ onClose }) => (
  <Text fontSize={[14, 16]} color="white">
    <Box
      display="flex"
      justifyContent="center"
      alignItems="center"
      px={[3, 4]}
      py={2}
      bg="primary"
    >

COVID-19:

        Toilets in businesses may not currently be open to non-customers. For
        public toilets, check with local authority websites. Toilets in
        supermarkets, shopping centres, train stations and service stations are
        mostly open.

      <Spacer ml={[2, 4]} />

      <Text fontSize={20}>
        <button type="button" aria-label="Close notification" onClick={onClose}>
          <Icon icon={faTimes} />
        </button>
      </Text>
    </Box>
  </Text>
);

const Header = ({ mapCenter, children }) => {
  const [isMenuVisible, setIsMenuVisible] = useState(false);

  const showCovidNotification =
    config.getSetting('notification', 'covid') !== 'dismissed';

  return (
    <Box as="header">
      {showCovidNotification && (
        <CovidNotification
          onClose={() => {
            config.setSetting('notification', 'covid', 'dismissed');

            // reload window to allow tracking components to check updated local storage values
            window.location.reload();
          }}
        />
      )}

      <Box
        display="flex"
        alignItems="center"
        px={[3, 4]}
        py={2}
        bg="white"
        minHeight={60}
      >
        <Box flexShrink={0}>
          <Link to="/">
            <Logo />
          </Link>
        </Box>

        <Box as="nav" width="100%" aria-labelledby="menu-main">

            <VisuallyHidden>Main menu</VisuallyHidden>

          <Box as={Media} at="sm" display="flex" justifyContent="flex-end">
            <button
              type="button"
              aria-expanded={isMenuVisible}
              onClick={() => setIsMenuVisible(!isMenuVisible)}
            >
              <VisuallyHidden>Toggle main menu</VisuallyHidden>
              <Icon icon={faBars} size="2x" />
            </button>

            <Drawer visible={isMenuVisible} zIndex={200}>
              <MainMenu
                mapCenter={mapCenter}
                onMenuItemClick={() => setIsMenuVisible(false)}
                children={children}
              />
            </Drawer>
          </Box>

          <Media greaterThan="sm">
            <MainMenu mapCenter={mapCenter} children={children} />
          </Media>
        </Box>
      </Box>
    </Box>
  );
};

export default Header;
<|endoftext|>


<commit_before>/**
 * @namespace Lyria
 * Lyria namespace decleration
 */
define('lyria/scene/director', ['root', 'mixin', 'jquery', 'lyria/eventmap', 'lyria/scene', 'lyria/viewport'], function(root, mixin, $, EventMap, Scene, Viewport) {'use strict';

  /**
   * The scene director is the manager for all scenes
   *
   */
  return (function() {

    function SceneDirector(container, parent) {
      mixin(SceneDirector.prototype, new EventMap());

      if ( container instanceof Viewport) {
        this.viewport = container;
      } else {
        this.viewport = new Viewport(container, parent);
      }

      this.sceneList = {};
      this.currentScene = null;
    }

    // Properties
    SceneDirector.prototype.sceneClassName = 'scene';

    // Methods
    SceneDirector.prototype.add = function(scene, options) {

      if (!( scene instanceof Scene)) {
        if (this.precompiledScenes) {
          scene = this.precompiledScenes[scene];
        } else {
          throw 'No valid scene found.';
        }
      }

      scene.parent = this;
      this.sceneList[scene.name] = scene;

      if (this.viewport.$container) {
        if ($('#' + scene.name).length === 0) {
          this.viewport.$container.prepend($(root.document.createElement('div')).attr('id', scene.name).attr('class', SceneDirector.prototype.sceneClassName));

          if (!scene.async) {
            if (scene.content) {
              $('#' + scene.name).html(scene.content);
            }
          }

          // Bind events
          if (scene.events && !$.isEmptyObject(scene.events)) {
            $.each(scene.events, function(key, value) {
              if (( typeof value === 'object') && (key !== 'delegate')) {
                $(scene.events.delegate).on(value, key, {
                  scene: scene
                });
              }
            });
          }

          // Data binding
          if (scene.template.data && !$.isEmptyObject(scene.template.data)) {
            $('#' + scene.name + ' [data-bind]').each(function() {
              var $dataElem = $(this);

              var prop = $dataElem.data('bind');

              scene.template.data.watch(prop, function(id, oldval, newval) {
                if (oldval !== newval) {
                  $dataElem.html(newval);
                }

                return newval;
              });
            });
          }
        }
      }

      return this;
    };

    SceneDirector.prototype.show = function(scene, options, callback) {
      this.trigger('scene:change', scene);

      // More than one scene visible at the same time
      if ($('.' + SceneDirector.prototype.sceneClassName + ':visible')) {
        $('.' + SceneDirector.prototype.sceneClassName).hide();
      }

      if (this.currentScene) {
        if (this.currentScene.transition && this.currentScene.length) {
          $('#' + this.currentScene).hide(this.currentScene.transition.length, function() {
            $('.' + SceneDirector.prototype.sceneClassName).hide();
          });
        } else {
          $('.' + SceneDirector.prototype.sceneClassName).hide();
        }

        this.currentScene.trigger('deactivate', options);
      }

      var self = this;

      $.each(this.sceneList, function(key, value) {
        if (key === scene) {

          if (scene.transition && scene.transition.length) {
            $('#' + scene).show(scene.transition.length);
          } else {
            $('#' + scene).show();
          }

          self.currentScene = value;

          self.currentScene.trigger('active', options);

          if (callback) {
            callback(scene);
          }

          return false;
        }
      });
    };

    SceneDirector.prototype.refresh = function(scene) {
      var sceneObj = (scene) ? this.sceneList[scene] : this.currentScene;

      // Re-compile scene template
      sceneObj.refresh();

      if (sceneObj.content) {
        $('#' + sceneObj.name).html(sceneObj.content);
      }
    };

    SceneDirector.prototype.render = function() {
      this.currentScene.trigger('render');
    };

    SceneDirector.prototype.update = function(dt) {
      this.currentScene.trigger('update', dt);
    };

    return SceneDirector;

  })();
});
<commit_msg>Updated inline documentation in lyria/scene/director<commit_after>/**
 * @module Lyria
 * @submodule Scene
 */
define('lyria/scene/director', ['root', 'mixin', 'jquery', 'lyria/eventmap', 'lyria/scene', 'lyria/viewport'], function(root, mixin, $, EventMap, Scene, Viewport) {'use strict';

  /**
   * The scene director is the manager for all scenes
   *
   */
  return (function() {

    /**
     * The scene director constructor
     * Attaches a scene director to a container, the parent is optional
     *
     * @class Director
     * @constructor
     *
     * @param {Object} container
     * @param {Object} parent
     */
    function SceneDirector(container, parent) {
      mixin(SceneDirector.prototype, new EventMap());

      if ( container instanceof Viewport) {
        this.viewport = container;
      } else {
        this.viewport = new Viewport(container, parent);
      }

      /**
       * All scenes
       *
       * @property sceneList
       * @type {Object}
       */
      this.sceneList = {};

      /**
       * The current scene
       *
       * @property currentScene
       * @type {Scene}
       */
      this.currentScene = null;
    }

    // Properties
    SceneDirector.prototype.sceneClassName = 'scene';

    // Methods

    /**
     * Adds a scene to the scene director
     *
     * @method add
     * @param {Object} scene
     * @param {Object} options
     */
    SceneDirector.prototype.add = function(scene, options) {

      if (!( scene instanceof Scene)) {
        if (this.scenes && !$.isEmptyObject(this.scenes)) {
          scene = this.scenes[scene];
        } else {
          // TODO: Don't throw a string. Throw an error
          throw 'No valid scene found.';
        }
      }

      scene.parent = this;
      this.sceneList[scene.name] = scene;

      if (this.viewport.$element) {
        if ($('#' + scene.name).length === 0) {
          this.viewport.$element.prepend($(root.document.createElement('div')).attr('id', scene.name).attr('class', SceneDirector.prototype.sceneClassName));

          if (!scene.async) {
            if (scene.content) {
              $('#' + scene.name).html(scene.content);
            }
          }

          // Bind events
          if (scene.events && !$.isEmptyObject(scene.events)) {
            $.each(scene.events, function(key, value) {
              if (( typeof value === 'object') && (key !== 'delegate')) {
                $(scene.events.delegate).on(value, key, {
                  scene: scene
                });
              }
            });
          }

          // Data binding
          if (scene.template.data && !$.isEmptyObject(scene.template.data)) {
            $('#' + scene.name + ' [data-bind]').each(function() {
              var $dataElem = $(this);

              var prop = $dataElem.data('bind');

              scene.template.data.watch(prop, function(id, oldval, newval) {
                if (oldval !== newval) {
                  $dataElem.html(newval);
                }

                return newval;
              });
            });
          }
        }
      }

      return this;
    };

    /**
     * Shows a specified scene
     *
     * @method show
     * @param {String} scene
     * @param {Object} options
     * @param {Function} callback
     */
    SceneDirector.prototype.show = function(scene, options, callback) {
      this.trigger('scene:change', scene);

      // More than one scene visible at the same time
      if ($('.' + SceneDirector.prototype.sceneClassName + ':visible')) {
        $('.' + SceneDirector.prototype.sceneClassName).hide();
      }

      if (this.currentScene) {
        if (this.currentScene.transition && this.currentScene.length) {
          $('#' + this.currentScene).hide(this.currentScene.transition.length, function() {
            $('.' + SceneDirector.prototype.sceneClassName).hide();
          });
        } else {
          $('.' + SceneDirector.prototype.sceneClassName).hide();
        }

        this.currentScene.trigger('deactivate', options);
      }

      var self = this;

      $.each(this.sceneList, function(key, value) {
        if (key === scene) {

          if (scene.transition && scene.transition.length) {
            $('#' + scene).show(scene.transition.length);
          } else {
            $('#' + scene).show();
          }

          self.currentScene = value;

          self.currentScene.trigger('active', options);

          if (callback) {
            callback(scene);
          }

          return false;
        }
      });
    };

    /**
     * Refreshes a scene
     *
     * @method refresh
     * @param {String} scene
     */
    SceneDirector.prototype.refresh = function(scene) {
      var sceneObj = (scene) ? this.sceneList[scene] : this.currentScene;

      // Re-compile scene template
      sceneObj.refresh();

      if (sceneObj.content) {
        $('#' + sceneObj.name).html(sceneObj.content);
      }
    };

    /**
     * Triggers the render event of the current scene
     *
     * @method render
     */
    SceneDirector.prototype.render = function() {
      this.currentScene.trigger('render');
    };

    /**
     * Triggers the update event of the current scene
     *
     * @param {Number} dt
     */
    SceneDirector.prototype.update = function(dt) {
      this.currentScene.trigger('update', dt);
    };

    return SceneDirector;

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