<commit_before>'use strict';

const Discord = require('../');
const request = require('superagent');
const fs = require('fs');

const client = new Discord.Client({ fetchAllMembers: false, apiRequestMethod: 'sequential' });

const { email, password, token, usertoken, song } = require('./auth.json');

client.login(token).then(atoken => console.log('logged in with token ' + atoken)).catch(console.error);

client.ws.on('send', console.log);

client.on('ready', () => {
  console.log('ready!');
});

client.on('userUpdate', (o, n) => {
  console.log(o.username, n.username);
});

client.on('guildMemberAdd', (g, m) => console.log(`${m.user.username} joined ${g.name}`));

client.on('channelCreate', channel => {
  console.log(`made ${channel.name}`);
});

client.on('error', m => console.log('debug', m));
client.on('reconnecting', m => console.log('debug', m));

client.on('message', message => {
  if (true) {
    if (message.content === 'makechann') {
      if (message.channel.guild) {
        message.channel.guild.createChannel('hi', 'text').then(console.log);
      }
    }

    if (message.content === 'imma queue pls') {
      let count = 0;
      let ecount = 0;
      for(let x = 0; x < 4000; x++) {
        message.channel.sendMessage(`this is message ${x} of 3999`)
          .then(m => {
            count++;
            console.log('reached', count, ecount);
          })
          .catch(m => {
            console.error(m);
            ecount++;
            console.log('reached', count, ecount);
          });
      }
    }

    if (message.content === 'myperms?') {
      message.channel.sendMessage('Your permissions are:\n' +
        JSON.stringify(message.channel.permissionsFor(message.author).serialize(), null, 4));
    }

    if (message.content === 'delchann') {
      message.channel.delete().then(chan => console.log('selfDelChann', chan.name));
    }

    if (message.content.startsWith('setname')) {
      message.channel.setName(message.content.substr(8));
    }

    if (message.content.startsWith('botname')) {
      client.user.setUsername(message.content.substr(8));
    }

    if (message.content.startsWith('botavatar')) {
      request
        .get('url')
        .end((err, res) => {
          client.user.setAvatar(res.body).catch(console.error)
            .then(user => message.channel.sendMessage('Done!'));
        });
    }

    if (message.content.startsWith('gn')) {
      message.guild.setName(message.content.substr(3))
        .then(guild => console.log('guild updated to', guild.name))
        .catch(console.error);
    }

    if (message.content === 'leave') {
      message.guild.leave().then(guild => console.log('left guild', guild.name)).catch(console.error);
    }

    if (message.content === 'stats') {
      let m = '';
      m += `I am aware of ${message.guild.channels.size} channels\n`;
      m += `I am aware of ${message.guild.members.size} members\n`;
      m += `I am aware of ${client.channels.size} channels overall\n`;
      m += `I am aware of ${client.guilds.size} guilds overall\n`;
      m += `I am aware of ${client.users.size} users overall\n`;
      message.channel.sendMessage(m).then(msg => msg.edit('nah')).catch(console.error);
    }

    if (message.content === 'messageme!') {
      message.author.sendMessage('oh, hi there!').catch(e => console.log(e.stack));
    }

    if (message.content === 'don\'t dm me') {
      message.author.deleteDM();
    }

    if (message.content.startsWith('kick')) {
      message.guild.member(message.mentions[0]).kick().then(member => {
        console.log(member);
        message.channel.sendMessage('Kicked!' + member.user.username);
      }).catch(console.error);
    }

    if (message.content === 'ratelimittest') {
      let i = 1;
      while (i <= 20) {
        message.channel.sendMessage(`Testing my rates, item ${i} of 20`);
        i++;
      }
    }

    if (message.content === 'makerole') {
      message.guild.createRole().then(role => {
        message.channel.sendMessage(`Made role ${role.name}`);
      }).catch(console.error);
    }
  }
});

function nameLoop(user) {
  // user.setUsername(user.username + 'a').then(nameLoop).catch(console.error);
}

function chanLoop(channel) {
  channel.setName(channel.name + 'a').then(chanLoop).catch(console.error);
}

client.on('message', msg => {
  if (msg.content.startsWith('?raw')) {
    msg.channel.sendMessage('```' + msg.content + '```');
  }

  if (msg.content.startsWith('#eval') && msg.author.id === '66564597481480192') {
    try {
      const com = eval(msg.content.split(" ").slice(1).join(" "));
      msg.channel.sendMessage('```\n' + com + '```');
    } catch(e) {
      msg.channel.sendMessage('```\n' + e + '```');
    }
  }
});

const ytdl = require('ytdl-core');

let disp, con;

client.on('message', msg => {
  if (msg.content.startsWith('/play')) {
    console.log('I am now going to play', msg.content);
    const chan = msg.content.split(' ').slice(1).join(' ');
    con.playStream(ytdl(chan, {filter : 'audioonly'}), { passes : 4 });
  }
  if (msg.content.startsWith('/join')) {
    const chan = msg.content.split(' ').slice(1).join(' ');
    msg.channel.guild.channels.get(chan).join()
      .then(conn => {
        con = conn;
        msg.reply('done');
        disp = conn.playStream(ytdl(song, {filter:'audioonly'}), { passes : 3 });
        conn.player.on('debug', console.log);
        conn.player.on('error', err => console.log(123, err));
      })
      .catch(console.error);
  }
})
<commit_msg>fix docs<commit_after>'use strict';

const Discord = require('../');
const request = require('superagent');
const fs = require('fs');

const client = new Discord.Client({ fetchAllMembers: false, apiRequestMethod: 'sequential' });

const { email, password, token, usertoken, song } = require('./auth.json');

client.login(token).then(atoken => console.log('logged in with token ' + atoken)).catch(console.error);

client.ws.on('send', console.log);

client.on('ready', () => {
  console.log('ready');
});

client.on('userUpdate', (o, n) => {
  console.log(o.username, n.username);
});

client.on('guildMemberAdd', (g, m) => console.log(`${m.user.username} joined ${g.name}`));

client.on('channelCreate', channel => {
  console.log(`made ${channel.name}`);
});

client.on('error', m => console.log('debug', m));
client.on('reconnecting', m => console.log('debug', m));

client.on('message', message => {
  if (true) {
    if (message.content === 'makechann') {
      if (message.channel.guild) {
        message.channel.guild.createChannel('hi', 'text').then(console.log);
      }
    }

    if (message.content === 'imma queue pls') {
      let count = 0;
      let ecount = 0;
      for(let x = 0; x < 4000; x++) {
        message.channel.sendMessage(`this is message ${x} of 3999`)
          .then(m => {
            count++;
            console.log('reached', count, ecount);
          })
          .catch(m => {
            console.error(m);
            ecount++;
            console.log('reached', count, ecount);
          });
      }
    }

    if (message.content === 'myperms?') {
      message.channel.sendMessage('Your permissions are:\n' +
        JSON.stringify(message.channel.permissionsFor(message.author).serialize(), null, 4));
    }

    if (message.content === 'delchann') {
      message.channel.delete().then(chan => console.log('selfDelChann', chan.name));
    }

    if (message.content.startsWith('setname')) {
      message.channel.setName(message.content.substr(8));
    }

    if (message.content.startsWith('botname')) {
      client.user.setUsername(message.content.substr(8));
    }

    if (message.content.startsWith('botavatar')) {
      request
        .get('url')
        .end((err, res) => {
          client.user.setAvatar(res.body).catch(console.error)
            .then(user => message.channel.sendMessage('Done!'));
        });
    }

    if (message.content.startsWith('gn')) {
      message.guild.setName(message.content.substr(3))
        .then(guild => console.log('guild updated to', guild.name))
        .catch(console.error);
    }

    if (message.content === 'leave') {
      message.guild.leave().then(guild => console.log('left guild', guild.name)).catch(console.error);
    }

    if (message.content === 'stats') {
      let m = '';
      m += `I am aware of ${message.guild.channels.size} channels\n`;
      m += `I am aware of ${message.guild.members.size} members\n`;
      m += `I am aware of ${client.channels.size} channels overall\n`;
      m += `I am aware of ${client.guilds.size} guilds overall\n`;
      m += `I am aware of ${client.users.size} users overall\n`;
      message.channel.sendMessage(m).then(msg => msg.edit('nah')).catch(console.error);
    }

    if (message.content === 'messageme!') {
      message.author.sendMessage('oh, hi there!').catch(e => console.log(e.stack));
    }

    if (message.content === 'don\'t dm me') {
      message.author.deleteDM();
    }

    if (message.content.startsWith('kick')) {
      message.guild.member(message.mentions[0]).kick().then(member => {
        console.log(member);
        message.channel.sendMessage('Kicked!' + member.user.username);
      }).catch(console.error);
    }

    if (message.content === 'ratelimittest') {
      let i = 1;
      while (i <= 20) {
        message.channel.sendMessage(`Testing my rates, item ${i} of 20`);
        i++;
      }
    }

    if (message.content === 'makerole') {
      message.guild.createRole().then(role => {
        message.channel.sendMessage(`Made role ${role.name}`);
      }).catch(console.error);
    }
  }
});

function nameLoop(user) {
  // user.setUsername(user.username + 'a').then(nameLoop).catch(console.error);
}

function chanLoop(channel) {
  channel.setName(channel.name + 'a').then(chanLoop).catch(console.error);
}

client.on('message', msg => {
  if (msg.content.startsWith('?raw')) {
    msg.channel.sendMessage('```' + msg.content + '```');
  }

  if (msg.content.startsWith('#eval') && msg.author.id === '66564597481480192') {
    try {
      const com = eval(msg.content.split(" ").slice(1).join(" "));
      msg.channel.sendMessage('```\n' + com + '```');
    } catch(e) {
      msg.channel.sendMessage('```\n' + e + '```');
    }
  }
});

const ytdl = require('ytdl-core');

let disp, con;

client.on('message', msg => {
  if (msg.content.startsWith('/play')) {
    console.log('I am now going to play', msg.content);
    const chan = msg.content.split(' ').slice(1).join(' ');
    con.playStream(ytdl(chan, {filter : 'audioonly'}), { passes : 4 });
  }
  if (msg.content.startsWith('/join')) {
    const chan = msg.content.split(' ').slice(1).join(' ');
    msg.channel.guild.channels.get(chan).join()
      .then(conn => {
        con = conn;
        msg.reply('done');
        disp = conn.playStream(ytdl(song, {filter:'audioonly'}), { passes : 3 });
        conn.player.on('debug', console.log);
        conn.player.on('error', err => console.log(123, err));
      })
      .catch(console.error);
  }
})
<|endoftext|>


<commit_before>$(document).ready(function() {

  var router = null;
  var location = null;
  var lastRoute = null;
  var lastArgs = [];

  function onRoute(router, route, args) {
    lastRoute = route;
    lastArgs = args;
  }

  var Location = function(href) {
    this.replace(href);
  };

  _.extend(Location.prototype, {

    replace: function(href) {
      _.extend(this, _.pick($('', {href: href})[0],
        'href',
        'hash',
        'search',
        'fragment',
        'pathname'
      ));
      // In IE, anchor.pathname does not contain a leading slash though
      // window.location.pathname does.
      if (!/^\//.test(this.pathname)) this.pathname = '/' + this.pathname;
    },

    toString: function() {
      return this.href;
    }

  });

  module("Backbone.Router", {

    setup: function() {
      location = new Location('http://example.com');
      Backbone.history = new Backbone.History({location: location});
      router = new Router({testing: 101});
      Backbone.history.interval = 9;
      Backbone.history.start({pushState: false});
      lastRoute = null;
      lastArgs = [];
      Backbone.history.on('route', onRoute);
    },

    teardown: function() {
      Backbone.history.stop();
      Backbone.history.off('route', onRoute);
    }

  });

  var Router = Backbone.Router.extend({

    count: 0,

    routes: {
      "noCallback":                 "noCallback",
      "counter":                    "counter",
      "search/:query":              "search",
      "search/:query/p:page":       "search",
      "contacts":                   "contacts",
      "contacts/new":               "newContact",
      "contacts/:id":               "loadContact",
      "splat/*args/end":            "splat",
      "*first/complex-:part/*rest": "complex",
      ":entity?*args":              "query",
      "*anything":                  "anything"
    },

    initialize : function(options) {
      this.testing = options.testing;
      this.route('implicit', 'implicit');
    },

    counter: function() {
      this.count++;
    },

    implicit: function() {
      this.count++;
    },

    search : function(query, page) {
      this.query = query;
      this.page = page;
    },

    contacts: function(){
      this.contact = 'index';
    },

    newContact: function(){
      this.contact = 'new';
    },

    loadContact: function(){
      this.contact = 'load';
    },

    splat : function(args) {
      this.args = args;
    },

    complex : function(first, part, rest) {
      this.first = first;
      this.part = part;
      this.rest = rest;
    },

    query : function(entity, args) {
      this.entity    = entity;
      this.queryArgs = args;
    },

    anything : function(whatever) {
      this.anything = whatever;
    }

  });

  test("Router: initialize", 1, function() {
    equal(router.testing, 101);
  });

  test("Router: routes (simple)", 4, function() {
    location.replace('http://example.com#search/news');
    Backbone.history.checkUrl();
    equal(router.query, 'news');
    equal(router.page, undefined);
    equal(lastRoute, 'search');
    equal(lastArgs[0], 'news');
  });

  test("Router: routes (two part)", 2, function() {
    location.replace('http://example.com#search/nyc/p10');
    Backbone.history.checkUrl();
    equal(router.query, 'nyc');
    equal(router.page, '10');
  });

  test("Router: routes via navigate", 2, function() {
    Backbone.history.navigate('search/manhattan/p20', {trigger: true});
    equal(router.query, 'manhattan');
    equal(router.page, '20');
  });

  test("Router: routes via navigate for backwards-compatibility", 2, function() {
    Backbone.history.navigate('search/manhattan/p20', true);
    equal(router.query, 'manhattan');
    equal(router.page, '20');
  });

  test("Router: route precedence via navigate", 6, function(){
    // check both 0.9.x and backwards-compatibility options
    _.each([ { trigger: true }, true ], function( options ){
      Backbone.history.navigate('contacts', options);
      equal(router.contact, 'index');
      Backbone.history.navigate('contacts/new', options);
      equal(router.contact, 'new');
      Backbone.history.navigate('contacts/foo', options);
      equal(router.contact, 'load');
    });
  });

  test("loadUrl is not called for identical routes.", 0, function() {
    Backbone.history.loadUrl = function(){ ok(false); };
    location.replace('http://example.com#route');
    Backbone.history.navigate('route');
    Backbone.history.navigate('/route');
    Backbone.history.navigate('/route');
  });

  test("Router: use implicit callback if none provided", 1, function() {
    router.count = 0;
    router.navigate('implicit', {trigger: true});
    equal(router.count, 1);
  });

  test("Router: routes via navigate with {replace: true}", 1, function() {
    location.replace('http://example.com#start_here');
    Backbone.history.checkUrl();
    location.replace = function(href) {
      strictEqual(href, new Location('http://example.com#end_here').href);
    };
    Backbone.history.navigate('end_here', {replace: true});
  });

  test("Router: routes (splats)", 1, function() {
    location.replace('http://example.com#splat/long-list/of/splatted_99args/end');
    Backbone.history.checkUrl();
    equal(router.args, 'long-list/of/splatted_99args');
  });

  test("Router: routes (complex)", 3, function() {
    location.replace('http://example.com#one/two/three/complex-part/four/five/six/seven');
    Backbone.history.checkUrl();
    equal(router.first, 'one/two/three');
    equal(router.part, 'part');
    equal(router.rest, 'four/five/six/seven');
  });

  test("Router: routes (query)", 5, function() {
    location.replace('http://example.com#mandel?a=b&c=d');
    Backbone.history.checkUrl();
    equal(router.entity, 'mandel');
    equal(router.queryArgs, 'a=b&c=d');
    equal(lastRoute, 'query');
    equal(lastArgs[0], 'mandel');
    equal(lastArgs[1], 'a=b&c=d');
  });

  test("Router: routes (anything)", 1, function() {
    location.replace('http://example.com#doesnt-match-a-route');
    Backbone.history.checkUrl();
    equal(router.anything, 'doesnt-match-a-route');
  });

  test("Router: fires event when router doesn't have callback on it", 1, function() {
    router.on("route:noCallback", function(){ ok(true); });
    location.replace('http://example.com#noCallback');
    Backbone.history.checkUrl();
  });

  test("#933, #908 - leading slash", 2, function() {
    location.replace('http://example.com/root/foo');

    Backbone.history.stop();
    Backbone.history = new Backbone.History({location: location});
    Backbone.history.start({root: '/root', hashChange: false, silent: true});
    strictEqual(Backbone.history.getFragment(), 'foo');

    Backbone.history.stop();
    Backbone.history = new Backbone.History({location: location});
    Backbone.history.start({root: '/root/', hashChange: false, silent: true});
    strictEqual(Backbone.history.getFragment(), 'foo');
  });

  test("#1003 - History is started before navigate is called", 1, function() {
    var history = new Backbone.History();
    history.navigate = function(){
      ok(Backbone.History.started);
    };
    Backbone.history.stop();
    history.start();
    // If this is not an old IE navigate will not be called.
    if (!history.iframe) ok(true);
  });

  test("Router: route callback gets passed non-decoded values", 3, function() {
    var route = 'has%2Fslash/complex-has%23hash/has%20space';
    Backbone.history.navigate(route, {trigger: true});
    equal(router.first, 'has%2Fslash');
    equal(router.part, 'has%23hash');
    equal(router.rest, 'has%20space');
  });

  test("Router: correctly handles URLs with % (#868)", 3, function() {
    location.replace('http://example.com#search/fat%3A1.5%25');
    Backbone.history.checkUrl();
    location.replace('http://example.com#search/fat');
    Backbone.history.checkUrl();
    equal(router.query, 'fat');
    equal(router.page, undefined);
    equal(lastRoute, 'search');
  });

  test("#1185 - Use pathname when hashChange is not wanted.", 1, function() {
    Backbone.history.stop();
    location.replace('http://example.com/path/name#hash');
    Backbone.history = new Backbone.History({location: location});
    Backbone.history.start({hashChange: false});
    var fragment = Backbone.history.getFragment();
    strictEqual(fragment, location.pathname.replace(/^\//, ''));
  });

  test("#1206 - Strip leading slash before location.assign.", 1, function() {
    Backbone.history.stop();
    location.replace('http://example.com/root/');
    Backbone.history = new Backbone.History({location: location});
    Backbone.history.start({hashChange: false, root: '/root/'});
    location.assign = function(pathname) {
      strictEqual(pathname, '/root/fragment');
    };
    Backbone.history.navigate('/fragment');
  });

  test("#1387 - Root fragment without trailing slash.", 1, function() {
    Backbone.history.stop();
    location.replace('http://example.com/root');
    Backbone.history = new Backbone.History({location: location});
    Backbone.history.start({hashChange: false, root: '/root/', silent: true});
    strictEqual(Backbone.history.getFragment(), '');
  });

  test("#1366 - History does not prepend root to fragment.", 2, function() {
    Backbone.history.stop();
    location.replace('http://example.com/root/');
    Backbone.history = new Backbone.History({
      location: location,
      history: {
        pushState: function(state, title, url) {
          strictEqual(url, '/root/x');
        }
      }
    });
    Backbone.history.start({
      root: '/root/',
      pushState: true,
      hashChange: false
    });
    Backbone.history.navigate('x');
    strictEqual(Backbone.history.fragment, 'x');
  });

});
<commit_msg>updating tests<commit_after>$(document).ready(function() {

  var router = null;
  var location = null;
  var lastRoute = null;
  var lastArgs = [];

  function onRoute(router, route, args) {
    lastRoute = route;
    lastArgs = args;
  }

  var Location = function(href) {
    this.replace(href);
  };

  _.extend(Location.prototype, {

    replace: function(href) {
      _.extend(this, _.pick($('', {href: href})[0],
        'href',
        'hash',
        'search',
        'fragment',
        'pathname'
      ));
      // In IE, anchor.pathname does not contain a leading slash though
      // window.location.pathname does.
      if (!/^\//.test(this.pathname)) this.pathname = '/' + this.pathname;
    },

    toString: function() {
      return this.href;
    }

  });

  module("Backbone.Router", {

    setup: function() {
      location = new Location('http://example.com');
      Backbone.history = new Backbone.History({location: location});
      router = new Router({testing: 101});
      Backbone.history.interval = 9;
      Backbone.history.start({pushState: false});
      lastRoute = null;
      lastArgs = [];
      Backbone.history.on('route', onRoute);
    },

    teardown: function() {
      Backbone.history.stop();
      Backbone.history.off('route', onRoute);
    }

  });

  var Router = Backbone.Router.extend({

    count: 0,

    routes: {
      "noCallback":                 "noCallback",
      "counter":                    "counter",
      "search/:query":              "search",
      "search/:query/p:page":       "search",
      "contacts":                   "contacts",
      "contacts/new":               "newContact",
      "contacts/:id":               "loadContact",
      "splat/*args/end":            "splat",
      "*first/complex-:part/*rest": "complex",
      ":entity?*args":              "query",
      "*anything":                  "anything"
    },

    initialize : function(options) {
      this.testing = options.testing;
      this.route('implicit', 'implicit');
    },

    counter: function() {
      this.count++;
    },

    implicit: function() {
      this.count++;
    },

    search : function(query, page) {
      this.query = query;
      this.page = page;
    },

    contacts: function(){
      this.contact = 'index';
    },

    newContact: function(){
      this.contact = 'new';
    },

    loadContact: function(){
      this.contact = 'load';
    },

    splat : function(args) {
      this.args = args;
    },

    complex : function(first, part, rest) {
      this.first = first;
      this.part = part;
      this.rest = rest;
    },

    query : function(entity, args) {
      this.entity    = entity;
      this.queryArgs = args;
    },

    anything : function(whatever) {
      this.anything = whatever;
    }

  });

  test("Router: initialize", 1, function() {
    equal(router.testing, 101);
  });

  test("Router: routes (simple)", 4, function() {
    location.replace('http://example.com#search/news');
    Backbone.history.checkUrl();
    equal(router.query, 'news');
    equal(router.page, undefined);
    equal(lastRoute, 'search');
    equal(lastArgs[0], 'news');
  });

  test("Router: routes (two part)", 2, function() {
    location.replace('http://example.com#search/nyc/p10');
    Backbone.history.checkUrl();
    equal(router.query, 'nyc');
    equal(router.page, '10');
  });

  test("Router: routes via navigate", 2, function() {
    Backbone.history.navigate('search/manhattan/p20', {trigger: true});
    equal(router.query, 'manhattan');
    equal(router.page, '20');
  });

  test("Router: routes via navigate for backwards-compatibility", 2, function() {
    Backbone.history.navigate('search/manhattan/p20', true);
    equal(router.query, 'manhattan');
    equal(router.page, '20');
  });

  test("Router: route precedence via navigate", 6, function(){
    // check both 0.9.x and backwards-compatibility options
    _.each([ { trigger: true }, true ], function( options ){
      Backbone.history.navigate('contacts', options);
      equal(router.contact, 'index');
      Backbone.history.navigate('contacts/new', options);
      equal(router.contact, 'new');
      Backbone.history.navigate('contacts/foo', options);
      equal(router.contact, 'load');
    });
  });

  test("loadUrl is not called for identical routes.", 0, function() {
    Backbone.history.loadUrl = function(){ ok(false); };
    location.replace('http://example.com#route');
    Backbone.history.navigate('route');
    Backbone.history.navigate('/route');
    Backbone.history.navigate('/route');
  });

  test("Router: use implicit callback if none provided", 1, function() {
    router.count = 0;
    router.navigate('implicit', {trigger: true});
    equal(router.count, 1);
  });

  test("Router: routes via navigate with {replace: true}", 1, function() {
    location.replace('http://example.com#start_here');
    Backbone.history.checkUrl();
    location.replace = function(href) {
      strictEqual(href, new Location('http://example.com#end_here').href);
    };
    Backbone.history.navigate('end_here', {replace: true});
  });

  test("Router: routes (splats)", 1, function() {
    location.replace('http://example.com#splat/long-list/of/splatted_99args/end');
    Backbone.history.checkUrl();
    equal(router.args, 'long-list/of/splatted_99args');
  });

  test("Router: routes (complex)", 3, function() {
    location.replace('http://example.com#one/two/three/complex-part/four/five/six/seven');
    Backbone.history.checkUrl();
    equal(router.first, 'one/two/three');
    equal(router.part, 'part');
    equal(router.rest, 'four/five/six/seven');
  });

  test("Router: routes (query)", 5, function() {
    location.replace('http://example.com#mandel?a=b&c=d');
    Backbone.history.checkUrl();
    equal(router.entity, 'mandel');
    equal(router.queryArgs, 'a=b&c=d');
    equal(lastRoute, 'query');
    equal(lastArgs[0], 'mandel');
    equal(lastArgs[1], 'a=b&c=d');
  });

  test("Router: routes (anything)", 1, function() {
    location.replace('http://example.com#doesnt-match-a-route');
    Backbone.history.checkUrl();
    equal(router.anything, 'doesnt-match-a-route');
  });

  test("Router: fires event when router doesn't have callback on it", 1, function() {
    router.on("route:noCallback", function(){ ok(true); });
    location.replace('http://example.com#noCallback');
    Backbone.history.checkUrl();
  });

  test("#933, #908 - leading slash", 2, function() {
    location.replace('http://example.com/root/foo');

    Backbone.history.stop();
    Backbone.history = new Backbone.History({location: location});
    Backbone.history.start({root: '/root', hashChange: false, silent: true});
    strictEqual(Backbone.history.getFragment(), 'foo');

    Backbone.history.stop();
    Backbone.history = new Backbone.History({location: location});
    Backbone.history.start({root: '/root/', hashChange: false, silent: true});
    strictEqual(Backbone.history.getFragment(), 'foo');
  });

  test("#1003 - History is started before navigate is called", 1, function() {
    var history = new Backbone.History();
    history.navigate = function(){
      ok(Backbone.History.started);
    };
    Backbone.history.stop();
    history.start();
    // If this is not an old IE navigate will not be called.
    if (!history.iframe) ok(true);
  });

  test("Router: route callback gets passed decoded values", 3, function() {
    var route = 'has%2Fslash/complex-has%23hash/has%20space';
    Backbone.history.navigate(route, {trigger: true});
    equal(router.first, 'has/slash');
    equal(router.part, 'has#hash');
    equal(router.rest, 'has space');
  });

  test("Router: correctly handles URLs with % (#868)", 3, function() {
    location.replace('http://example.com#search/fat%3A1.5%25');
    Backbone.history.checkUrl();
    location.replace('http://example.com#search/fat');
    Backbone.history.checkUrl();
    equal(router.query, 'fat');
    equal(router.page, undefined);
    equal(lastRoute, 'search');
  });

  test("#1185 - Use pathname when hashChange is not wanted.", 1, function() {
    Backbone.history.stop();
    location.replace('http://example.com/path/name#hash');
    Backbone.history = new Backbone.History({location: location});
    Backbone.history.start({hashChange: false});
    var fragment = Backbone.history.getFragment();
    strictEqual(fragment, location.pathname.replace(/^\//, ''));
  });

  test("#1206 - Strip leading slash before location.assign.", 1, function() {
    Backbone.history.stop();
    location.replace('http://example.com/root/');
    Backbone.history = new Backbone.History({location: location});
    Backbone.history.start({hashChange: false, root: '/root/'});
    location.assign = function(pathname) {
      strictEqual(pathname, '/root/fragment');
    };
    Backbone.history.navigate('/fragment');
  });

  test("#1387 - Root fragment without trailing slash.", 1, function() {
    Backbone.history.stop();
    location.replace('http://example.com/root');
    Backbone.history = new Backbone.History({location: location});
    Backbone.history.start({hashChange: false, root: '/root/', silent: true});
    strictEqual(Backbone.history.getFragment(), '');
  });

  test("#1366 - History does not prepend root to fragment.", 2, function() {
    Backbone.history.stop();
    location.replace('http://example.com/root/');
    Backbone.history = new Backbone.History({
      location: location,
      history: {
        pushState: function(state, title, url) {
          strictEqual(url, '/root/x');
        }
      }
    });
    Backbone.history.start({
      root: '/root/',
      pushState: true,
      hashChange: false
    });
    Backbone.history.navigate('x');
    strictEqual(Backbone.history.fragment, 'x');
  });

});
<|endoftext|>


<commit_before>var netif = require('../build/Debug/netif');

for (var i = 0; i < Number.MAX_VALUE; i++){
  process.nextTick(foo);
}

function foo() {
  netif.getIFMacAddress('en1');
}
<commit_msg>More messing around.<commit_after>var netif = require('../build/Debug/netif');

var i = 0;

for (; i < 1000000; i++) {
  netif.getIFMacAddress('en1');
}

console.log("ran " + i + " times.");
<|endoftext|>


<commit_before>const tokens = require("./setupenv"); // setupenv has to be imported before app
const app = require("../app");
const chai = require("chai");
const chaiHttp = require("chai-http");
const { addBasicCase } = require("./cases");
const chaiHelpers = require("./helpers");
const should = chai.should();
chai.use(chaiHttp);
chai.use(chaiHelpers);

describe("Search", () => {
  describe("get first 20 cases", () => {
    it("finds 20 case titles and ids", async () => {
      const res = await chai
        .getJSON("/search/getAllForType?objType=case&page=1")
        .send({});
      res.should.have.status(200);
      should.equal(Object.keys(res.body).length, 20);
    });
  });
  describe.only("confirm query tokenizing", () => {
    let { tokenize } = require("../api/helpers/search");
    it("simple and", () => {
      [...tokenize("first and second")].should.deep.equal([
        "",
        "first",
        "&",
        "",
        "second"
      ]);
    });
    it("simple or", () => {
      [...tokenize("first or second")].should.deep.equal([
        "",
        "first",
        "|",
        "",
        "second"
      ]);
    });
    it("simple not", () => {
      [...tokenize("first not second")].should.deep.equal([
        "",
        "first",
        "!",
        "",
        "second"
      ]);
    });
    it("parentheses", () => {
      [...tokenize("first or (second and third)")].should.deep.equal([
        "",
        "first",
        "|",
        "",
        "(",
        "",
        "second",
        "&",
        "",
        "third",
        ")"
      ]);
    });
    it("quoted string", () => {
      [...tokenize('first and "second third"')].should.deep.equal([
        "",
        "first",
        "&",
        "",
        "",
        "second",
        "<->",
        "third"
      ]);
    });
    it("handle whitespace", () => {
      [...tokenize('first second "third fourth" fifth')].should.deep.equal([
        "",
        "first",
        "&",
        "second",
        "&",
        "",
        "third",
        "<->",
        "fourth",
        "&",
        "fifth"
      ]);
    });
    it("drop punctuation, etc.", () => {
      [
        ...tokenize("first 123, inject's some ;drop table *bs")
      ].should.deep.equal([
        "",
        "first",
        "&",
        "inject",
        "&",
        "s",
        "&",
        "some",
        "&",
        "drop",
        "&",
        "table",
        "&",
        "bs"
      ]);
    });
    it("complex query", () => {
      [
        ...tokenize('first and (second or third) and ("fourth fifth" or sixth)')
      ].should.deep.equal([
        "",
        "first",
        "&",
        "",
        "(",
        "",
        "second",
        "|",
        "",
        "third",
        ")",
        "&",
        "",
        "(",
        "",
        "",
        "fourth",
        "<->",
        "fifth",
        "|",
        "",
        "sixth",
        ")"
      ]);
    });
  });
  describe.only("confirm query parsing", () => {
    let { preparse_query } = require("../api/helpers/search");
    it("simple and", () => {
      preparse_query("first and second").should.equal("first&second");
    });
    it("simple or", () => {
      preparse_query("first or second").should.equal("first|second");
    });
    it("simple not", () => {
      preparse_query("first not second").should.equal("first!second");
    });
    it("parentheses", () => {
      preparse_query("first or (second and third)").should.equal(
        "first|(second&third)"
      );
    });
    it("quoted string", () => {
      preparse_query('first and "second third"').should.equal(
        "first&second<->third"
      );
    });
    it("handle whitespace", () => {
      preparse_query('first second "third fourth" fifth').should.equal(
        "first&second&third<->fourth&fifth"
      );
    });
    it("drop punctuation, etc.", () => {
      preparse_query("first 123, inject's some ;drop table *bs").should.equal(
        "first&inject&s&some&drop&table&bs"
      );
    });
    it("complex query", () => {
      preparse_query(
        'first and (second or third) and ("fourth fifth" or sixth)'
      ).should.equal("first&(second|third)&(fourth<->fifth|sixth)");
    });
  });
  describe("get first 20 methods", () => {
    it("finds 20 method titles and ids", async () => {
      const res = await chai
        .getJSON("/search/getAllForType?objType=method&page=1")
        .send({});
      res.should.have.status(200);
      should.equal(Object.keys(res.body).length, 20);
    });
  });
  describe("get first 20 organizations", () => {
    it("finds 20 organization titles and ids", async () => {
      const res = await chai
        .getJSON("/search/getAllForType?objType=organization&page=1")
        .send({});
      res.should.have.status(200);
      should.equal(Object.keys(res.body).length, 20);
    });
  });
  describe("get organizations in Canada", () => {
    it("finds all Organizations with the term Canada", async () => {
      const res = await chai
        .getJSON("/search?query=Canada&selectedCategory=Organizations")
        .send({});
      res.should.have.status(200);
      res.body.OK.should.equal(true);
      res.body.results.should.have.lengthOf(20);
      res.body.results.forEach(obj => obj.type.should.equal("organization"));
    });
  });
  describe("get cases tagged 'nuclear'", () => {
    it("finds all Cases with the word nuclear", async () => {
      const res = await chai
        .getJSON("/search?query=nuclear&selectedCategory=Cases")
        .send({});
      res.should.have.status(200);
      res.body.OK.should.equal(true);
      res.body.results.should.have.lengthOf(13);
      res.body.results[0].type.should.equal("case");
    });
  });
  describe("Test search with multi-word tags", () => {
    it("finds everything with the words animal welfare", async () => {
      const res = await chai.getJSON("/search?query=animal%20welfare").send({});
      res.should.have.status(200);
      res.body.OK.should.equal(true);
      res.body.results.should.have.lengthOf(6);
      // more testing
    });
  });
  describe("Test full-text search", () => {
    it("single-word search", async () => {
      const res = await chai.getJSON("/search?query=Budget").send({});
      res.should.have.status(200);
      res.body.results.should.have.lengthOf(20);
      const item = res.body.results[0];
      item.title.should.be.a("string");
      item.body.should.be.a("string");
      item.id.should.be.a("number");
      item.type.should.be.a("string");
      item.updated_date.should.be.a("string");
      item.bookmarked.should.be.a("boolean");
      item.should.have.property("images");
    });
    it("multi-word search", async () => {
      const res = await chai
        .getJSON("/search?query=Budget%20Participatory")
        .send({});
      res.should.have.status(200);
      res.body.results.should.have.lengthOf(20);
    });
  });
  describe("Test cacheing", () => {
    it("Will only be correct if cache is cleared", async () => {
      const res1 = await chai.getJSON("/search").send({});
      res1.should.have.status(200);
      res1.body.results.should.have.lengthOf(20);
      const res2 = await addBasicCase();
      const theCase = res2.body.object;
      await chai
        .putJSON("/case/" + theCase.id)
        .set("Authorization", "Bearer " + tokens.user_token)
        .send({ featured: true });
      const res3 = await chai.getJSON("/search").send({});
      // If the cache was cleared by adding and editing an object, the new object should
      // now be in the featured search results (the default search)
      const searchResultIds = res3.body.results.map(x => x.id);
      theCase.id.should.be.oneOf(searchResultIds);
    });
  });
  describe("Test hidden results", () => {
    it("Hiding an element removes it from featured (default) search", async () => {
      const res1 = await chai.getJSON("/search").send({});
      res1.should.have.status(200);
      res1.should.be.json;
      res1.body.results.should.have.lengthOf(20);
      const res2 = await addBasicCase();
      const theCase = res2.body.object;
      await chai
        .putJSON("/case/" + theCase.id)
        .set("Authorization", "Bearer " + tokens.user_token)
        .send({ featured: true });
      const res3 = await chai.getJSON("/search").send({});
      const searchResultIds = res3.body.results.map(x => x.id);
      theCase.id.should.be.oneOf(searchResultIds);
      await chai
        .putJSON("/case/" + theCase.id)
        .set("Authorization", "Bearer " + tokens.user_token)
        .send({ hidden: true });
      const res4 = await chai.getJSON("/search").send({});
      const searchResultIds2 = res4.body.results.map(x => x.id);
      theCase.id.should.not.be.oneOf(searchResultIds2);
    });
    it("Hiding an element removes it from full-text search results", async () => {
      const res1 = await chai.getJSON("/search").send({});
      // const body = JSON.parse(res1.text);
      res1.should.have.status(200);
      res1.should.be.json;
      res1.body.results.should.have.lengthOf(20);
      const res2 = await addBasicCase();
      const theCase = res2.body.object;
      await chai
        .putJSON("/case/" + theCase.id)
        .set("Authorization", "Bearer " + tokens.user_token)
        .send({ tags: ["albino", "tiger"] });
      const res3 = await chai.getJSON("/search?query=albino%20tiger").send({});
      res3.body.results.should.have.lengthOf(1);
      res3.body.results[0].id.should.equal(theCase.id);
      await chai
        .putJSON("/case/" + theCase.id)
        .set("Authorization", "Bearer " + tokens.user_token)
        .send({ hidden: true });
      const res4 = await chai.getJSON("/search?query=albino%20tiger").send({});
      res4.body.results.should.have.lengthOf(0);
    });
  });
});
<commit_msg>fixed tests<commit_after>const tokens = require("./setupenv"); // setupenv has to be imported before app
const app = require("../app");
const chai = require("chai");
const chaiHttp = require("chai-http");
const { addBasicCase } = require("./cases");
const chaiHelpers = require("./helpers");
const should = chai.should();
chai.use(chaiHttp);
chai.use(chaiHelpers);

describe("Search", () => {
  describe("get first 20 cases", () => {
    it("finds 20 case titles and ids", async () => {
      const res = await chai
        .getJSON("/search/getAllForType?objType=case&page=1")
        .send({});
      res.should.have.status(200);
      should.equal(Object.keys(res.body).length, 20);
    });
  });
  describe("confirm query tokenizing", () => {
    let { tokenize } = require("../api/helpers/search");
    it("simple and", () => {
      [...tokenize("first and second")].should.deep.equal([
        "",
        "first",
        "&",
        "",
        "second"
      ]);
    });
    it("simple or", () => {
      [...tokenize("first or second")].should.deep.equal([
        "",
        "first",
        "|",
        "",
        "second"
      ]);
    });
    it("simple not", () => {
      [...tokenize("first not second")].should.deep.equal([
        "",
        "first",
        "&",
        "!",
        "",
        "second"
      ]);
    });
    it("parentheses", () => {
      [...tokenize("first or (second and third)")].should.deep.equal([
        "",
        "first",
        "|",
        "",
        "(",
        "",
        "second",
        "&",
        "",
        "third",
        ")"
      ]);
    });
    it("quoted string", () => {
      [...tokenize('first and "second third"')].should.deep.equal([
        "",
        "first",
        "&",
        "",
        "",
        "second",
        "<->",
        "third"
      ]);
    });
    it("handle whitespace", () => {
      [...tokenize('first second "third fourth" fifth')].should.deep.equal([
        "",
        "first",
        "&",
        "second",
        "&",
        "",
        "third",
        "<->",
        "fourth",
        "&",
        "fifth"
      ]);
    });
    it("drop punctuation, etc.", () => {
      [
        ...tokenize("first 123, inject's some ;drop table *bs")
      ].should.deep.equal([
        "",
        "first",
        "&",
        "inject",
        "&",
        "s",
        "&",
        "some",
        "&",
        "drop",
        "&",
        "table",
        "&",
        "bs"
      ]);
    });
    it("complex query", () => {
      [
        ...tokenize('first and (second or third) and ("fourth fifth" or sixth)')
      ].should.deep.equal([
        "",
        "first",
        "&",
        "",
        "(",
        "",
        "second",
        "|",
        "",
        "third",
        ")",
        "&",
        "",
        "(",
        "",
        "",
        "fourth",
        "<->",
        "fifth",
        "|",
        "",
        "sixth",
        ")"
      ]);
    });
  });
  describe("confirm query parsing", () => {
    let { preparse_query } = require("../api/helpers/search");
    it("simple and", () => {
      preparse_query("first and second").should.equal("first&second");
    });
    it("simple or", () => {
      preparse_query("first or second").should.equal("first|second");
    });
    it("simple not", () => {
      preparse_query("first not second").should.equal("first&!second");
    });
    it("parentheses", () => {
      preparse_query("first or (second and third)").should.equal(
        "first|(second&third)"
      );
    });
    it("quoted string", () => {
      preparse_query('first and "second third"').should.equal(
        "first&second<->third"
      );
    });
    it("handle whitespace", () => {
      preparse_query('first second "third fourth" fifth').should.equal(
        "first&second&third<->fourth&fifth"
      );
    });
    it("drop punctuation, etc.", () => {
      preparse_query("first 123, inject's some ;drop table *bs").should.equal(
        "first&inject&s&some&drop&table&bs"
      );
    });
    it("complex query", () => {
      preparse_query(
        'first and (second or third) and ("fourth fifth" or sixth)'
      ).should.equal("first&(second|third)&(fourth<->fifth|sixth)");
    });
  });
  describe("get first 20 methods", () => {
    it("finds 20 method titles and ids", async () => {
      const res = await chai
        .getJSON("/search/getAllForType?objType=method&page=1")
        .send({});
      res.should.have.status(200);
      should.equal(Object.keys(res.body).length, 20);
    });
  });
  describe("get first 20 organizations", () => {
    it("finds 20 organization titles and ids", async () => {
      const res = await chai
        .getJSON("/search/getAllForType?objType=organization&page=1")
        .send({});
      res.should.have.status(200);
      should.equal(Object.keys(res.body).length, 20);
    });
  });
  describe("get organizations in Canada", () => {
    it("finds all Organizations with the term Canada", async () => {
      const res = await chai
        .getJSON("/search?query=Canada&selectedCategory=Organizations")
        .send({});
      res.should.have.status(200);
      res.body.OK.should.equal(true);
      res.body.results.should.have.lengthOf(20);
      res.body.results.forEach(obj => obj.type.should.equal("organization"));
    });
  });
  describe("get cases tagged 'nuclear'", () => {
    it("finds all Cases with the word nuclear", async () => {
      const res = await chai
        .getJSON("/search?query=nuclear&selectedCategory=Cases")
        .send({});
      res.should.have.status(200);
      res.body.OK.should.equal(true);
      res.body.results.should.have.lengthOf(13);
      res.body.results[0].type.should.equal("case");
    });
  });
  describe("Test search with multi-word tags", () => {
    it("finds everything with the words animal welfare", async () => {
      const res = await chai.getJSON("/search?query=animal%20welfare").send({});
      res.should.have.status(200);
      res.body.OK.should.equal(true);
      res.body.results.should.have.lengthOf(6);
      // more testing
    });
  });
  describe("Test full-text search", () => {
    it("single-word search", async () => {
      const res = await chai.getJSON("/search?query=Budget").send({});
      res.should.have.status(200);
      res.body.results.should.have.lengthOf(20);
      const item = res.body.results[0];
      item.title.should.be.a("string");
      item.body.should.be.a("string");
      item.id.should.be.a("number");
      item.type.should.be.a("string");
      item.updated_date.should.be.a("string");
      item.bookmarked.should.be.a("boolean");
      item.should.have.property("images");
    });
    it("multi-word search", async () => {
      const res = await chai
        .getJSON("/search?query=Budget%20Participatory")
        .send({});
      res.should.have.status(200);
      res.body.results.should.have.lengthOf(20);
    });
  });
  describe("Test cacheing", () => {
    it("Will only be correct if cache is cleared", async () => {
      const res1 = await chai.getJSON("/search").send({});
      res1.should.have.status(200);
      res1.body.results.should.have.lengthOf(20);
      const res2 = await addBasicCase();
      const theCase = res2.body.object;
      await chai
        .putJSON("/case/" + theCase.id)
        .set("Authorization", "Bearer " + tokens.user_token)
        .send({ featured: true });
      const res3 = await chai.getJSON("/search").send({});
      // If the cache was cleared by adding and editing an object, the new object should
      // now be in the featured search results (the default search)
      const searchResultIds = res3.body.results.map(x => x.id);
      theCase.id.should.be.oneOf(searchResultIds);
    });
  });
  describe("Test hidden results", () => {
    it("Hiding an element removes it from featured (default) search", async () => {
      const res1 = await chai.getJSON("/search").send({});
      res1.should.have.status(200);
      res1.should.be.json;
      res1.body.results.should.have.lengthOf(20);
      const res2 = await addBasicCase();
      const theCase = res2.body.object;
      await chai
        .putJSON("/case/" + theCase.id)
        .set("Authorization", "Bearer " + tokens.user_token)
        .send({ featured: true });
      const res3 = await chai.getJSON("/search").send({});
      const searchResultIds = res3.body.results.map(x => x.id);
      theCase.id.should.be.oneOf(searchResultIds);
      await chai
        .putJSON("/case/" + theCase.id)
        .set("Authorization", "Bearer " + tokens.user_token)
        .send({ hidden: true });
      const res4 = await chai.getJSON("/search").send({});
      const searchResultIds2 = res4.body.results.map(x => x.id);
      theCase.id.should.not.be.oneOf(searchResultIds2);
    });
    it("Hiding an element removes it from full-text search results", async () => {
      const res1 = await chai.getJSON("/search").send({});
      // const body = JSON.parse(res1.text);
      res1.should.have.status(200);
      res1.should.be.json;
      res1.body.results.should.have.lengthOf(20);
      const res2 = await addBasicCase();
      const theCase = res2.body.object;
      await chai
        .putJSON("/case/" + theCase.id)
        .set("Authorization", "Bearer " + tokens.user_token)
        .send({ tags: ["albino", "tiger"] });
      const res3 = await chai.getJSON("/search?query=albino%20tiger").send({});
      res3.body.results.should.have.lengthOf(1);
      res3.body.results[0].id.should.equal(theCase.id);
      await chai
        .putJSON("/case/" + theCase.id)
        .set("Authorization", "Bearer " + tokens.user_token)
        .send({ hidden: true });
      const res4 = await chai.getJSON("/search?query=albino%20tiger").send({});
      res4.body.results.should.have.lengthOf(0);
    });
  });
});
<|endoftext|>


<commit_before>/**
 * Log function
 *
 * @param {String} text
 */
displayLog = function (text) {
    $('.results').append('
' + text + '
');
    console.log(text);
};
/**
 * Clear log
 */
clearLog = function () {
    $('.results').html('');
    console.clear();
};
/**
 * Run the tests
 */
runTests = function () {

    //----------------------------------------------
    // Init resize object
	$('.results').append('
Windows width as media query (including the scrollbar): ' + djs.tools.getWindowWidth() + 'px
');
	$('.results').append('
Windows width only: ' + djs.tools.getWindowWidth(false) + 'px
');
	$('.results').append('
Scrollbar width: ' + djs.tools.getScrollbarWidth() + 'px
');
	$('.results').append('
Body has scroll bar: ' + (djs.tools.bodyHasScrollbar() ? 'Yes': 'No') + '
');

    //----------------------------------------------
    // Ends displayed tests
    displayLog(" ");

};
/**
 * Auto run test
 */
$(document).ready(function () {
    runTests();
});<commit_msg>Rename calls in test<commit_after>/**
 * Log function
 *
 * @param {String} text
 */
displayLog = function (text) {
    $('.results').append('
' + text + '
');
    console.log(text);
};
/**
 * Clear log
 */
clearLog = function () {
    $('.results').html('');
    console.clear();
};
/**
 * Run the tests
 */
runTests = function () {

    //----------------------------------------------
    // Init resize object
	$('.results').append('
Windows width as media query (including the scrollbar): ' + djs.tools.ui.getWindowWidth() + 'px
');
	$('.results').append('
Windows width only: ' + djs.tools.ui.getWindowWidth(false) + 'px
');
	$('.results').append('
Scrollbar width: ' + djs.tools.ui.getScrollbarWidth() + 'px
');
	$('.results').append('
Body has scroll bar: ' + (djs.tools.ui.bodyHasScrollbar() ? 'Yes': 'No') + '
');

    //----------------------------------------------
    // Ends displayed tests
    displayLog(" ");

};
/**
 * Auto run test
 */
$(document).ready(function () {
    runTests();
});<|endoftext|>


<commit_before>const { Readable, Writable } = require('stream');
const { randomBytes, createHash } = require('crypto');
const { expect } = require('chai');
const {
    Disruptor,
    DisruptorReadStream,
    DisruptorWriteStream
}  = require('..');

class RandomStream extends Readable {
    constructor(size) {
        super();
        this.size = size;
        this.hash = createHash('sha256');
    }

    _read(size) {
        if (this.size === 0) {
            return this.push(null);
        }

        randomBytes(Math.min(size, this.size), (err, buf) => {
            if (err) {
                return this.emit('error', err);
            }
            this.size -= buf.length;
            this.hash.update(buf);
            if (this.size === 0) {
                this.digest = this.hash.digest('hex');
            }
            this.push(buf);
        });
    }
}

describe('stream functionality', function () {
    this.timeout(60000);

    let disruptors, streams;

    beforeEach(function () {
        disruptors = [new Disruptor('/test', 1000, 1, 1, 0, true, false)];
        streams = [];
    });

    afterEach(function (cb) {
        function release() {
            for (const d of disruptors) {
                d.release();
            }
            cb();
        }

        if (streams.length === 0) {
            return release();
        }

        let count = 0;

        function closed() {
            if (++count === streams.length) {
                release();
            }
        }

        for (const s of streams) {
            if (s.destroyed) {
                closed();
            } else {
                s.on('close', closed);
                s.destroy();
            }
        }
    });

    it('should send data from writer to reader', function (done) {
        const rs = new DisruptorReadStream(disruptors[0]);
        const ws = new DisruptorWriteStream(disruptors[0]);

        streams.push(rs, ws);

        const bufs = [];

        rs.on('readable', function () {
            while (true) {
                const buf = this.read();
                if (!buf) {
                    break;
                }
                bufs.push(buf);
            }
        });

        rs.on('end', function () {
            expect(Buffer.concat(bufs).toString()).to.equal('hello');
            done();
        });

        ws.end('hello');
    });

    it('should pipe data', function (done) {
        const rs = new DisruptorReadStream(disruptors[0]);
        const ws = new DisruptorWriteStream(disruptors[0]);
        const rngs = new RandomStream(1024 * 1024);

        streams.push(rs, ws);

        rngs.pipe(ws);

        rs.pipe(new class extends Writable {
            constructor(options) {
                super(options);
                this.hash = createHash('sha256');
            }
        }({
            autoDestroy: true, // for Node 12

            /*construct(cb) {
                this.hash = createHash('sha256');
                cb();
            },*/

            write(chunk, encoding, cb) {
                this.hash.update(chunk);
                cb();
            },

            final(cb) {
                expect(this.hash.digest('hex')).to.equal(rngs.digest);
                cb();
            }
        }).on('close', done));
    });

    it('should propagate writer error', function (done) {
        const rs = new DisruptorReadStream(disruptors[0]);
        const ws = new DisruptorWriteStream(disruptors[0]);

        streams.push(rs, ws);

        rs.on('error', function (err) {
            expect(err.message).to.equal('writer errored');
            done();
        });

        rs.on('readable', function () {
        });

        ws.on('error', function (err) {
            expect(err.message).to.equal('foo');
        });

        ws.destroy(new Error('foo'));
    });

    it("should error if element size isn't 1", function () {
        const d2 = new Disruptor('/test2', 1000, 2, 1, 0, true, false);

        expect(function () {
            new DisruptorReadStream(d2);
        }).to.throw('element size must be 1');

        expect(function () {
            new DisruptorWriteStream(d2);
        }).to.throw('element size must be 1');

        d2.release();
    });

    it("should error if spin isn't false", function () {
        const d2 = new Disruptor('/test2', 1000, 1, 1, 0, true, true);

        expect(function () {
            new DisruptorReadStream(d2);
        }).to.throw('spin must be false');

        expect(function () {
            new DisruptorWriteStream(d2);
        }).to.throw('spin must be false');

        d2.release();
    });

    it('should support multiple readers', function (done) {
        disruptors[0].release();
        disruptors = [];

        const num_readers = 1000;

        let count = 0;
        function check() {
            if (++count === num_readers) {
                done();
            }
        }

        const rngs = new RandomStream(1024 * 1024);

        for (let i = 0; i < num_readers; ++i) {
            const d = new Disruptor('/test', 10000, 1, num_readers, i, i === 0, false);
            disruptors.push(d);
            const rs = new DisruptorReadStream(d);
            streams.push(rs);

            rs.pipe(new class extends Writable {
                constructor(options)
                {
                    super(options);
                    this.hash = createHash('sha256');
                }
            }({
                autoDestroy: true, // for Node 12

                /*construct(cb) {
                    this.hash = createHash('sha256');
                    cb();
                },*/

                write(chunk, encoding, cb) {
                    this.hash.update(chunk);
                    cb();
                },

                final(cb) {
                    expect(this.hash.digest('hex')).to.equal(rngs.digest);
                    cb();
                }
            }).on('close', check));
        }

        const d = new Disruptor('/test', 10000, 1, num_readers, 0, false, false);
        disruptors.push(d);
        const ws = new DisruptorWriteStream(d);
        streams.push(ws);
        rngs.pipe(ws);
    });

    it('should destroy while reading', function (done) {
        const rs = new DisruptorReadStream(disruptors[0]);
        streams.push(rs);
        let the_err;
        rs.on('close', () => {
            expect(the_err.message).to.equal('foo');
            done();
        });
        rs.on('error', err => {
            the_err = err;
        });
        rs._read();
        rs.destroy(new Error('foo'));
    });

    it('should destroy while writing', function (done) {
        const ws = new DisruptorWriteStream(disruptors[0]);
        streams.push(ws);
        let the_err;
        ws.on('close', () => {
            expect(the_err.message).to.equal('foo');
            done();
        });
        ws.on('error', err => {
            the_err = err;
        });
        ws.write('bar');
        ws.destroy(new Error('foo'));
    });

    it('should not read once destroyed', function (done) {
        const rs = new DisruptorReadStream(disruptors[0]);
        streams.push(rs);
        rs.on('data', () => {
            done(new Error('unexpected data'));
        });
        rs.on('close', async function () {
            await this._read();
            done();
        });
        rs.destroy();
    });

    it('should not write once destroyed', function (done) {
        const ws = new DisruptorWriteStream(disruptors[0]);
        streams.push(ws);
        ws.on('close', async function () {
            await this._write();
            done();
        });
        ws.destroy();
    });

    it('should catch disruptor errors while reading', function (done) {
        const rs = new DisruptorReadStream(disruptors[0]);
        streams.push(rs);
        rs.on('error', err => {
            expect(err.message).to.equal('foobar');
            done();
        });
        disruptors[0].consumeNew = () => {
            throw new Error('foobar');
        };
        rs.read();
    });

    it('should catch disruptor errors while writing', function (done) {
        const ws = new DisruptorWriteStream(disruptors[0]);
        streams.push(ws);
        ws.on('error', err => {
            expect(err.message).to.equal('foobar');
            done();
        });
        disruptors[0].produceClaimAvail = () => {
            throw new Error('foobar');
        };
        ws.write('test');
    });

    it('should catch disruptor errors while committing', function (done) {
        const ws = new DisruptorWriteStream(disruptors[0]);
        streams.push(ws);
        ws.on('error', err => {
            expect(err.message).to.equal('foobar');
            done();
        });
        disruptors[0].produceCommit = () => {
            throw new Error('foobar');
        };
        ws.write('test');
    });

    it('should retry commit', function (done) {
        const rs = new DisruptorReadStream(disruptors[0]);
        const ws = new DisruptorWriteStream(disruptors[0]);

        streams.push(rs, ws);

        const bufs = [];

        rs.on('readable', function () {
            while (true) {
                const buf = this.read();
                if (!buf) {
                    break;
                }
                bufs.push(buf);
            }
        });

        let count = 0;
        const produceCommit = disruptors[0].produceCommit;

        disruptors[0].produceCommit = function () {
            if (++count === 1) {
                return false;
            }

            return produceCommit.apply(this, arguments);
        };

        let ended = false;
        let finished = false;

        rs.on('end', function () {
            expect(Buffer.concat(bufs).toString()).to.equal('hello');
            ended = true;
            if (finished) {
                done();
            }
        });

        ws.on('finish', function () {
            finished = true;
            expect(count).to.equal(2);
            if (ended) {
                done();
            }
        });

        ws.end('hello');
    });

    it('should not commit when destroyed', function (done) {
        const ws = new DisruptorWriteStream(disruptors[0]);
        streams.push(ws);

        let produce_commit_called = false;
        disruptors[0].produceCommit = function () {
            produce_commit_called = true;
        };

        let the_err;
        ws.on('error', function (err) {
            expect(err.message).to.equal('foo');
            setTimeout(() => {
                expect(produce_commit_called).to.be.false;
                done();
            }, 1000);
        });

        const commit = ws._commit;
        ws._commit = function () {
            this.destroy(new Error('foo'));
            return commit.apply(this, arguments);
        };

        ws.write('hello');
    });

    it('should handle destroy while committing', function (done) {
        const ws = new DisruptorWriteStream(disruptors[0]);
        streams.push(ws);

        ws.on('close', done);

        disruptors[0].produceCommit = function () {
            ws.destroy();
        };

        ws.write('hello');
    });

    it('should error if all consumers ignore data', function (done) {
        disruptors[0].release();
        disruptors = [];

        const num_readers = 1000;

        let count = 0;

        function readable() {
            expect(this.read().toString()).to.equal('A');
            this.on('close', function () {
                this.disruptor.release(true);
                if (++count === num_readers) {
                    ws.once('error', function (err) {
                        expect(err.message).to.equal('no consumers');
                        done();
                    });
                    ws.write('B');
                }
            });
            this.destroy();
        }

        for (let i = 0; i < num_readers; ++i) {
            const d = new Disruptor('/test', 10000, 1, num_readers, i, i === 0, false);
            new DisruptorReadStream(d).once('readable', readable);
        }

        const d = new Disruptor('/test', 10000, 1, num_readers, 0, false, false);
        disruptors.push(d);
        const ws = new DisruptorWriteStream(d);
        streams.push(ws);
        ws.write('A');
    });

    it('should retry writing if Disruptor is full', function (done) {
        const rs = new DisruptorReadStream(disruptors[0], { highWaterMark: 1000 });
        const ws = new DisruptorWriteStream(disruptors[0]);

        streams.push(rs, ws);

        rs.once('readable', function () {
            ws.write('A');
            setTimeout(() => {
                this.once('readable', function () {
                    expect(this.read().length).to.equal(1000);
                    this.once('readable', function () {
                        expect(this.read().toString()).to.equal('A');
                        done();
                    });
                });
                expect(this.read().length).to.equal(1000);

            }, 500);
        });

        // Fill up Disruptor and read stream buffer
        ws.write(Buffer.alloc(2000));
    });

    it("shouldn't read if already reading", function (done) {
        const rs = new DisruptorReadStream(disruptors[0]);
        streams.push(rs);

        let the_resolve = null;

        disruptors[0].consumeNew = function () {
            return new Promise((resolve, reject) => {
                the_resolve = resolve;
            });
        };

        rs.read();
        expect(the_resolve).not.to.be.null;
        rs.push('A');
        setTimeout(() => {
            the_resolve({ bufs: [] });
            done();
        }, 500);
    });
});
<commit_msg>Pipe test: check size<commit_after>const { Readable, Writable } = require('stream');
const { randomBytes, createHash } = require('crypto');
const { expect } = require('chai');
const {
    Disruptor,
    DisruptorReadStream,
    DisruptorWriteStream
}  = require('..');

class RandomStream extends Readable {
    constructor(size) {
        super();
        this.size = size;
        this.hash = createHash('sha256');
    }

    _read(size) {
        if (this.size === 0) {
            return this.push(null);
        }

        randomBytes(Math.min(size, this.size), (err, buf) => {
            if (err) {
                return this.emit('error', err);
            }
            this.size -= buf.length;
            this.hash.update(buf);
            if (this.size === 0) {
                this.digest = this.hash.digest('hex');
            }
            this.push(buf);
        });
    }
}

describe('stream functionality', function () {
    this.timeout(60000);

    let disruptors, streams;

    beforeEach(function () {
        disruptors = [new Disruptor('/test', 1000, 1, 1, 0, true, false)];
        streams = [];
    });

    afterEach(function (cb) {
        function release() {
            for (const d of disruptors) {
                d.release();
            }
            cb();
        }

        if (streams.length === 0) {
            return release();
        }

        let count = 0;

        function closed() {
            if (++count === streams.length) {
                release();
            }
        }

        for (const s of streams) {
            if (s.destroyed) {
                closed();
            } else {
                s.on('close', closed);
                s.destroy();
            }
        }
    });

    it('should send data from writer to reader', function (done) {
        const rs = new DisruptorReadStream(disruptors[0]);
        const ws = new DisruptorWriteStream(disruptors[0]);

        streams.push(rs, ws);

        const bufs = [];

        rs.on('readable', function () {
            while (true) {
                const buf = this.read();
                if (!buf) {
                    break;
                }
                bufs.push(buf);
            }
        });

        rs.on('end', function () {
            expect(Buffer.concat(bufs).toString()).to.equal('hello');
            done();
        });

        ws.end('hello');
    });

    it('should pipe data', function (done) {
        const rs = new DisruptorReadStream(disruptors[0]);
        const ws = new DisruptorWriteStream(disruptors[0]);
        const rngs = new RandomStream(1024 * 1024);

        streams.push(rs, ws);

        rngs.pipe(ws);

        rs.pipe(new class extends Writable {
            constructor(options) {
                super(options);
                this.hash = createHash('sha256');
                this.count = 0;
            }
        }({
            autoDestroy: true, // for Node 12

            /*construct(cb) {
                this.hash = createHash('sha256');
                cb();
            },*/

            write(chunk, encoding, cb) {
                this.hash.update(chunk);
                this.count += chunk.length;
                cb();
            },

            final(cb) {
                expect(this.count).to.equal(1024 * 1024);
                expect(this.hash.digest('hex')).to.equal(rngs.digest);
                cb();
            }
        }).on('close', done));
    });

    it('should propagate writer error', function (done) {
        const rs = new DisruptorReadStream(disruptors[0]);
        const ws = new DisruptorWriteStream(disruptors[0]);

        streams.push(rs, ws);

        rs.on('error', function (err) {
            expect(err.message).to.equal('writer errored');
            done();
        });

        rs.on('readable', function () {
        });

        ws.on('error', function (err) {
            expect(err.message).to.equal('foo');
        });

        ws.destroy(new Error('foo'));
    });

    it("should error if element size isn't 1", function () {
        const d2 = new Disruptor('/test2', 1000, 2, 1, 0, true, false);

        expect(function () {
            new DisruptorReadStream(d2);
        }).to.throw('element size must be 1');

        expect(function () {
            new DisruptorWriteStream(d2);
        }).to.throw('element size must be 1');

        d2.release();
    });

    it("should error if spin isn't false", function () {
        const d2 = new Disruptor('/test2', 1000, 1, 1, 0, true, true);

        expect(function () {
            new DisruptorReadStream(d2);
        }).to.throw('spin must be false');

        expect(function () {
            new DisruptorWriteStream(d2);
        }).to.throw('spin must be false');

        d2.release();
    });

    it('should support multiple readers', function (done) {
        disruptors[0].release();
        disruptors = [];

        const num_readers = 1000;

        let count = 0;
        function check() {
            if (++count === num_readers) {
                done();
            }
        }

        const rngs = new RandomStream(1024 * 1024);

        for (let i = 0; i < num_readers; ++i) {
            const d = new Disruptor('/test', 10000, 1, num_readers, i, i === 0, false);
            disruptors.push(d);
            const rs = new DisruptorReadStream(d);
            streams.push(rs);

            rs.pipe(new class extends Writable {
                constructor(options)
                {
                    super(options);
                    this.hash = createHash('sha256');
                }
            }({
                autoDestroy: true, // for Node 12

                /*construct(cb) {
                    this.hash = createHash('sha256');
                    cb();
                },*/

                write(chunk, encoding, cb) {
                    this.hash.update(chunk);
                    cb();
                },

                final(cb) {
                    expect(this.hash.digest('hex')).to.equal(rngs.digest);
                    cb();
                }
            }).on('close', check));
        }

        const d = new Disruptor('/test', 10000, 1, num_readers, 0, false, false);
        disruptors.push(d);
        const ws = new DisruptorWriteStream(d);
        streams.push(ws);
        rngs.pipe(ws);
    });

    it('should destroy while reading', function (done) {
        const rs = new DisruptorReadStream(disruptors[0]);
        streams.push(rs);
        let the_err;
        rs.on('close', () => {
            expect(the_err.message).to.equal('foo');
            done();
        });
        rs.on('error', err => {
            the_err = err;
        });
        rs._read();
        rs.destroy(new Error('foo'));
    });

    it('should destroy while writing', function (done) {
        const ws = new DisruptorWriteStream(disruptors[0]);
        streams.push(ws);
        let the_err;
        ws.on('close', () => {
            expect(the_err.message).to.equal('foo');
            done();
        });
        ws.on('error', err => {
            the_err = err;
        });
        ws.write('bar');
        ws.destroy(new Error('foo'));
    });

    it('should not read once destroyed', function (done) {
        const rs = new DisruptorReadStream(disruptors[0]);
        streams.push(rs);
        rs.on('data', () => {
            done(new Error('unexpected data'));
        });
        rs.on('close', async function () {
            await this._read();
            done();
        });
        rs.destroy();
    });

    it('should not write once destroyed', function (done) {
        const ws = new DisruptorWriteStream(disruptors[0]);
        streams.push(ws);
        ws.on('close', async function () {
            await this._write();
            done();
        });
        ws.destroy();
    });

    it('should catch disruptor errors while reading', function (done) {
        const rs = new DisruptorReadStream(disruptors[0]);
        streams.push(rs);
        rs.on('error', err => {
            expect(err.message).to.equal('foobar');
            done();
        });
        disruptors[0].consumeNew = () => {
            throw new Error('foobar');
        };
        rs.read();
    });

    it('should catch disruptor errors while writing', function (done) {
        const ws = new DisruptorWriteStream(disruptors[0]);
        streams.push(ws);
        ws.on('error', err => {
            expect(err.message).to.equal('foobar');
            done();
        });
        disruptors[0].produceClaimAvail = () => {
            throw new Error('foobar');
        };
        ws.write('test');
    });

    it('should catch disruptor errors while committing', function (done) {
        const ws = new DisruptorWriteStream(disruptors[0]);
        streams.push(ws);
        ws.on('error', err => {
            expect(err.message).to.equal('foobar');
            done();
        });
        disruptors[0].produceCommit = () => {
            throw new Error('foobar');
        };
        ws.write('test');
    });

    it('should retry commit', function (done) {
        const rs = new DisruptorReadStream(disruptors[0]);
        const ws = new DisruptorWriteStream(disruptors[0]);

        streams.push(rs, ws);

        const bufs = [];

        rs.on('readable', function () {
            while (true) {
                const buf = this.read();
                if (!buf) {
                    break;
                }
                bufs.push(buf);
            }
        });

        let count = 0;
        const produceCommit = disruptors[0].produceCommit;

        disruptors[0].produceCommit = function () {
            if (++count === 1) {
                return false;
            }

            return produceCommit.apply(this, arguments);
        };

        let ended = false;
        let finished = false;

        rs.on('end', function () {
            expect(Buffer.concat(bufs).toString()).to.equal('hello');
            ended = true;
            if (finished) {
                done();
            }
        });

        ws.on('finish', function () {
            finished = true;
            expect(count).to.equal(2);
            if (ended) {
                done();
            }
        });

        ws.end('hello');
    });

    it('should not commit when destroyed', function (done) {
        const ws = new DisruptorWriteStream(disruptors[0]);
        streams.push(ws);

        let produce_commit_called = false;
        disruptors[0].produceCommit = function () {
            produce_commit_called = true;
        };

        let the_err;
        ws.on('error', function (err) {
            expect(err.message).to.equal('foo');
            setTimeout(() => {
                expect(produce_commit_called).to.be.false;
                done();
            }, 1000);
        });

        const commit = ws._commit;
        ws._commit = function () {
            this.destroy(new Error('foo'));
            return commit.apply(this, arguments);
        };

        ws.write('hello');
    });

    it('should handle destroy while committing', function (done) {
        const ws = new DisruptorWriteStream(disruptors[0]);
        streams.push(ws);

        ws.on('close', done);

        disruptors[0].produceCommit = function () {
            ws.destroy();
        };

        ws.write('hello');
    });

    it('should error if all consumers ignore data', function (done) {
        disruptors[0].release();
        disruptors = [];

        const num_readers = 1000;

        let count = 0;

        function readable() {
            expect(this.read().toString()).to.equal('A');
            this.on('close', function () {
                this.disruptor.release(true);
                if (++count === num_readers) {
                    ws.once('error', function (err) {
                        expect(err.message).to.equal('no consumers');
                        done();
                    });
                    ws.write('B');
                }
            });
            this.destroy();
        }

        for (let i = 0; i < num_readers; ++i) {
            const d = new Disruptor('/test', 10000, 1, num_readers, i, i === 0, false);
            new DisruptorReadStream(d).once('readable', readable);
        }

        const d = new Disruptor('/test', 10000, 1, num_readers, 0, false, false);
        disruptors.push(d);
        const ws = new DisruptorWriteStream(d);
        streams.push(ws);
        ws.write('A');
    });

    it('should retry writing if Disruptor is full', function (done) {
        const rs = new DisruptorReadStream(disruptors[0], { highWaterMark: 1000 });
        const ws = new DisruptorWriteStream(disruptors[0]);

        streams.push(rs, ws);

        rs.once('readable', function () {
            ws.write('A');
            setTimeout(() => {
                this.once('readable', function () {
                    expect(this.read().length).to.equal(1000);
                    this.once('readable', function () {
                        expect(this.read().toString()).to.equal('A');
                        done();
                    });
                });
                expect(this.read().length).to.equal(1000);

            }, 500);
        });

        // Fill up Disruptor and read stream buffer
        ws.write(Buffer.alloc(2000));
    });

    it("shouldn't read if already reading", function (done) {
        const rs = new DisruptorReadStream(disruptors[0]);
        streams.push(rs);

        let the_resolve = null;

        disruptors[0].consumeNew = function () {
            return new Promise((resolve, reject) => {
                the_resolve = resolve;
            });
        };

        rs.read();
        expect(the_resolve).not.to.be.null;
        rs.push('A');
        setTimeout(() => {
            the_resolve({ bufs: [] });
            done();
        }, 500);
    });
});
<|endoftext|>


<commit_before>'use strict'
var randomBytes = require('crypto').randomBytes
var test = require('tape').test
var varstruct = require('../')

test('asserts on codec creation', function (t) {
  t.test('length must be a number', function (t) {
    t.throws(function () {
      varstruct.String()
    }, /^TypeError: length must be a number$/)
    t.end()
  })

  t.end()
})

test('encode', function (t) {
  t.test('value must be a string', function (t) {
    t.throws(function () {
      varstruct.String(42).encode(null)
    }, /^TypeError: value must be a string$/)
    t.end()
  })

  t.end()
})

test('encode/decode', function (t) {
  var encodings = [
    'base64',
    'binary',
    'hex'
  ]

  encodings.forEach(function (encoding) {
    t.test('encoding: ' + encoding, function (t) {
      var length = 42
      var s = randomBytes(length).toString(encoding)
      var fixedstring = varstruct.String(length, encoding)

      t.same(fixedstring.decode(fixedstring.encode(s)), s)
      t.end()
    })
  })

  t.end()
})

test('encodingLength', function (t) {
  t.test('should return length even if value is not string', function (t) {
    t.same(varstruct.String(42).encodingLength(null), 42)
    t.end()
  })

  t.test('should return length even if encoding is invalid', function (t) {
    t.same(varstruct.String(42, 'h1').encodingLength(''), 42)
    t.end()
  })

  t.end()
})
<commit_msg>Fix lint issue<commit_after>'use strict'
var randomBytes = require('crypto').randomBytes
var test = require('tape').test
var varstruct = require('../')

test('asserts on codec creation', function (t) {
  t.test('length must be a number', function (t) {
    t.throws(function () {
      varstruct.String()
    }, /^TypeError: length must be a number$/)
    t.end()
  })

  t.end()
})

test('encode', function (t) {
  t.test('value must be a string', function (t) {
    t.throws(function () {
      varstruct.String(42).encode(null)
    }, /^TypeError: value must be a string$/)
    t.end()
  })

  t.end()
})

test('encode/decode', function (t) {
  var encodings = [
    'base64',
    'binary',
    'hex'
  ]

  encodings.forEach(function (encoding) {
    t.test('encoding: ' + encoding, function (t) {
      var length = 42
      var s = randomBytes(length).toString(encoding)
      var fixedstring = varstruct.String(length, encoding)

      t.same(fixedstring.decode(fixedstring.encode(s)), s)
      t.end()
    })
  })

  t.end()
})

test('encodingLength', function (t) {
  t.test('should return length even if value is not string', function (t) {
    t.same(varstruct.String(42).encodingLength(null), 42)
    t.end()
  })

  t.test('should return length even if encoding is invalid', function (t) {
    t.same(varstruct.String(42, 'h1').encodingLength(''), 42)
    t.end()
  })

  t.end()
})
<|endoftext|>


<commit_before>(function (){
	const ObjecExtends = (source, add) => {
		Object.keys(add).forEach(addProperty => {
			source[addProperty] = add[addProperty];
		});
	};
	const selector = (sel, ele) => {
		ele = ele || document;
		if (typeof(sel) !== 'string') {
			return [sel];
		} else {
			return Array.prototype.slice.call(ele.querySelectorAll(sel));
		}
	};

	const DOMMethod = {
		fadeIn(cb, time = 618) {
			this.forEach(ele => {
				ele.style.opacity = 0;
				ele.style.transition = 'opacity '+ time +'ms';
				ele.style.webkitTransition = 'opacity '+ time +'ms';

				ele.style.display = '';
				ele.style.display = getComputedStyle(ele, null).getPropertyValue('display');

				setTimeout(function (){
					ele.style.opacity = 1;
					setTimeout(function (){
						cb && cb();
					}, time);
				}, 16.8);
			})
		},
		fadeOut(cb, time = 618) {
			this.forEach(ele => {
				ele.style.opacity = 1;
				ele.style.transition = 'opacity '+ time +'ms';
				ele.style.webkitTransition = 'opacity '+ time +'ms';

				setTimeout(function (){
					ele.style.opacity = 0;
					setTimeout(function (){
						ele.style.display = 'none';
						console.warn(cb);
						cb && cb();
					}, time);
				}, 16.8);
			})
		},
		remove(){
			this.forEach(ele => {
				ele.parentNode.removeChild(ele)
			})
			return this
		},
		html(value){
			if (typeof(value) !== 'undefined') {
				this.forEach(ele => {
					ele.innerHTML = value;
				})
			} else {
				return this.map(ele => {
					return ele.innerHTML;
				});
			}
		},
		text(value){
			if (typeof(value) !== 'undefined') {
				this.forEach(ele => {
					ele.innerText = value;
				});
				return this;
			} else {
				let textArr = this.map(ele => ele.innerText);
				if (textArr.length === 1) {
					textArr = textArr[0];
				}
				return textArr;
			}
		},
		cssSingle(cssObj){
			Object.keys(cssObj).forEach(property => this.setCss(property, cssObj[property]))
			return this
		},
		setCss(property, value){
			this.forEach(ele => ele.style[property] = value)
			return this
		},
		css(){
			if (arguments.length === 0) {
			} else if (arguments.length === 1) {
				return this.cssSingle(...arguments)
			} else if (arguments.length >= 2) {
				return this.setCss(...arguments)
			}
		},

		class(...classArr){
			this.forEach(ele => {
				classArr.forEach(className => ele.classList.add(className))
			})
			return this;
		},
		classRemove(...classArr) {
			this.forEach(ele => {
				classArr.forEach(className => ele.classList.remove(className))
			})
			return this;
		},
		append(...eleArr) {
			eleArr.forEach(ele => {
				if (Array.isArray(ele)) {
					this.append(...ele)
				} else {
					this[0].appendChild(ele)
				}
			})
			return this
		},
		getAttributesValue(attrEle, name){
			let attr = attrEle.attributes.getNamedItem(name);
			if (attr === null) {
				return null
			} else {
				return attr.value
			}
		},
		getAttr(name){
			let elementAttributesArr = this.map(ele =>
				vools(`[${name}]`, ele).map(attr => this.getAttributesValue(attr, name)).map(valueArr => {
					if (valueArr.length === 1) {
						valueArr = valueArr[0]
					}
					return valueArr
				})
			)

			if (elementAttributesArr.length === 1) {
				return elementAttributesArr[0]
			} else {
				return elementAttributesArr
			}
		},
		setAttr(name, value){
			this.forEach(ele => {
				ele.setAttribute(name, value)
			})
			return this
		},
		attr(name, value){
			if (arguments.length === 0) {
				return this.map(attrEle => {
					return this.getAttributesValue(attrEle)
				})
			} else if (arguments.length === 1) {
				return this.getAttr(name)
			} else if (arguments.length > 1) {
				return this.setAttr(name, value)
			}
		},
		removeAttr(name) {
			this.forEach(ele => ele.removeAttribute(name))
			return this
		},
	};
	const DOMs = function (sel, ele) {
		ObjecExtends(this, DOMMethod);
	};
	DOMs.prototype = Array.prototype;

	const vools = function (sel, ele) {
		const doms = new DOMs;
		if (Array.isArray(sel)) {
			var domArr = sel
		} else {
			var domArr = selector(sel, ele)
		}
		domArr.forEach(element => doms.push(element));

		return doms;
	};

	vools.create = eleName => {
		return vools(document.createElement(eleName))
	};

	const stringifyRequest = (() => {
		const backValueKey = (key, value) => `${key}=` + encodeURIComponent(value);
		const stringifyArray = (key, arr) => arr.length ? arr.map(item => backValueKey(key, item)).join('&') : backValueKey(key, '');
		const fetcher = (data, key) => Array.isArray(data[key]) ? stringifyArray(key, data[key]) : backValueKey(key, data[key]);
		return data => Object.keys(data).map(key => fetcher(data, key)).join('&');
	})();
	vools.stringifyRequest = stringifyRequest
	vools.pjax = function (url, args) {
		const xhr = new XMLHttpRequest;
		if (args.method === undefined) {
			throw new Error('请求方法未指定');
		}
		return new Promise((resolve, reject) => {
			xhr.onloadend = () => {
				if (xhr.status === 200) {
					resolve(xhr.responseText, xhr.status, xhr);
				} else {
					const err = new Error('status is not 200');
					err.status = xhr.status;
					err.responseText = xhr.responseText;
					err.xhr = xhr;
					reject(err);
				}
			};

			xhr.open(args.method.toUpperCase(), url, true);
			if (args.data !== undefined) {
				if (args.type === 'json') {
					xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
				} else if ('type' in args) {
					xhr.setRequestHeader("Content-Type", atgs.type);
				} else {
					xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
				}

				if (/json/.test(args.type)) {
					xhr.send(JSON.stringify(args.data))
				} else if (typeof args.data === 'object') {
					let formated = stringifyRequest(args.data);
					xhr.send(formated);
				} else {
					xhr.send(args.data);
				}
			} else {
				xhr.send();
			}
		});
	};
	vools.get = function (url) {
		return vools.pjax(url, { method: 'GET' })
	};
	vools.post = function (url, data = {}) {
		return vools.pjax(url, { method: 'POST', data })
	};
	vools.patch = function (url, data = {}) {
		return vools.pjax(url, { method: 'PATCH', data });
	};
	vools.delete = function (url, data = {}) {
		return vools.pjax(url, { method: 'DELETE', data });
	};
	vools.rjax = (() => {
		return (url, args) => {
			var xhr = new XMLHttpRequest;

			xhr.onloadend = () => {
				if (xhr.status === 200) {
					args.success && args.success(xhr.responseText, xhr.status, xhr);
				} else {
					args.fail && args.fail(xhr.responseText, xhr.status, xhr);
				}
			};
			if (args.method === undefined) {
				throw new Error('请求方法未指定');
			}

			xhr.open(args.method.toUpperCase(), url, true);
			if (args.data !== undefined) {
				xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
				if (typeof args.data === 'object') {
					let formated = stringifyRequest(args.data);
					xhr.send(formated);
				} else {
					xhr.send(args.data);
				}
			} else {
				xhr.send();
			}
		};
	})();

	const bPrototype = {
		BrowserCore: ['ms', 'moz', 'Moz', 'webkit'],
		dom: document.createElement('div'),
		prop: 'Transition',
		init() {
			const result = this.BrowserCore.some(prefix => {
				if (`${prefix}${this.prop}` in this.dom.style)
					return this.core = prefix.toLowerCase()
			})

			if (!result) {
				console.warn('unsupport browser rendering core')
				this.core = 'unknown'
			}

			return this.core
		},
	}
	vools.browser = Object.create(bPrototype)
	vools.browser.init()

	const voolsEvent = function (){};
	ObjecExtends(voolsEvent.prototype, {

	});
	try {
		module.exports = vools
	} catch (e) {
		if (window.define) {
			define(() => [
				vools,
				function () { return vools.apply(null, arguments).pop() }
			])
		} else {
			window.voolsEvent = voolsEvent;

			window.vools = vools;
			window.$ = vools;
			window.$$ = function (){
				return vools.apply(null, arguments)[0];
			};
		}
	}
})();
<commit_msg>removeCss dom method<commit_after>(function (){
	const ObjecExtends = (source, add) => {
		Object.keys(add).forEach(addProperty => {
			source[addProperty] = add[addProperty];
		});
	};
	const selector = (sel, ele) => {
		ele = ele || document;
		if (typeof(sel) !== 'string') {
			return [sel];
		} else {
			return Array.prototype.slice.call(ele.querySelectorAll(sel));
		}
	};

	const DOMMethod = {
		fadeIn(cb, time = 618) {
			this.forEach(ele => {
				ele.style.opacity = 0;
				ele.style.transition = 'opacity '+ time +'ms';
				ele.style.webkitTransition = 'opacity '+ time +'ms';

				ele.style.display = '';
				ele.style.display = getComputedStyle(ele, null).getPropertyValue('display');

				setTimeout(function (){
					ele.style.opacity = 1;
					setTimeout(function (){
						cb && cb();
					}, time);
				}, 16.8);
			})
		},
		fadeOut(cb, time = 618) {
			this.forEach(ele => {
				ele.style.opacity = 1;
				ele.style.transition = 'opacity '+ time +'ms';
				ele.style.webkitTransition = 'opacity '+ time +'ms';

				setTimeout(function (){
					ele.style.opacity = 0;
					setTimeout(function (){
						ele.style.display = 'none';
						console.warn(cb);
						cb && cb();
					}, time);
				}, 16.8);
			})
		},
		remove(){
			this.forEach(ele => {
				ele.parentNode.removeChild(ele)
			})
			return this
		},
		html(value){
			if (typeof(value) !== 'undefined') {
				this.forEach(ele => {
					ele.innerHTML = value;
				})
			} else {
				return this.map(ele => {
					return ele.innerHTML;
				});
			}
		},
		text(value){
			if (typeof(value) !== 'undefined') {
				this.forEach(ele => {
					ele.innerText = value;
				});
				return this;
			} else {
				let textArr = this.map(ele => ele.innerText);
				if (textArr.length === 1) {
					textArr = textArr[0];
				}
				return textArr;
			}
		},
		cssSingle(cssObj){
			Object.keys(cssObj).forEach(property => this.setCss(property, cssObj[property]))
			return this
		},
		setCss(property, value){
			this.forEach(ele => ele.style[property] = value)
			return this
		},
		css(){
			if (arguments.length === 0) {
			} else if (arguments.length === 1) {
				return this.cssSingle(...arguments)
			} else if (arguments.length >= 2) {
				return this.setCss(...arguments)
			}
		},
		removeCss(...props) {
			props.forEach(prop => this.setCss(prop, ''))
		},

		class(...classArr){
			this.forEach(ele => {
				classArr.forEach(className => ele.classList.add(className))
			})
			return this;
		},
		classRemove(...classArr) {
			this.forEach(ele => {
				classArr.forEach(className => ele.classList.remove(className))
			})
			return this;
		},
		append(...eleArr) {
			eleArr.forEach(ele => {
				if (Array.isArray(ele)) {
					this.append(...ele)
				} else {
					this[0].appendChild(ele)
				}
			})
			return this
		},
		getAttributesValue(attrEle, name){
			let attr = attrEle.attributes.getNamedItem(name);
			if (attr === null) {
				return null
			} else {
				return attr.value
			}
		},
		getAttr(name){
			let elementAttributesArr = this.map(ele =>
				vools(`[${name}]`, ele).map(attr => this.getAttributesValue(attr, name)).map(valueArr => {
					if (valueArr.length === 1) {
						valueArr = valueArr[0]
					}
					return valueArr
				})
			)

			if (elementAttributesArr.length === 1) {
				return elementAttributesArr[0]
			} else {
				return elementAttributesArr
			}
		},
		setAttr(name, value){
			this.forEach(ele => {
				ele.setAttribute(name, value)
			})
			return this
		},
		attr(name, value){
			if (arguments.length === 0) {
				return this.map(attrEle => {
					return this.getAttributesValue(attrEle)
				})
			} else if (arguments.length === 1) {
				return this.getAttr(name)
			} else if (arguments.length > 1) {
				return this.setAttr(name, value)
			}
		},
		removeAttr(name) {
			this.forEach(ele => ele.removeAttribute(name))
			return this
		},
	};
	const DOMs = function (sel, ele) {
		ObjecExtends(this, DOMMethod);
	};
	DOMs.prototype = Array.prototype;

	const vools = function (sel, ele) {
		const doms = new DOMs;
		if (Array.isArray(sel)) {
			var domArr = sel
		} else {
			var domArr = selector(sel, ele)
		}
		domArr.forEach(element => doms.push(element));

		return doms;
	};

	vools.create = eleName => {
		return vools(document.createElement(eleName))
	};

	const stringifyRequest = (() => {
		const backValueKey = (key, value) => `${key}=` + encodeURIComponent(value);
		const stringifyArray = (key, arr) => arr.length ? arr.map(item => backValueKey(key, item)).join('&') : backValueKey(key, '');
		const fetcher = (data, key) => Array.isArray(data[key]) ? stringifyArray(key, data[key]) : backValueKey(key, data[key]);
		return data => Object.keys(data).map(key => fetcher(data, key)).join('&');
	})();
	vools.stringifyRequest = stringifyRequest
	vools.pjax = function (url, args) {
		const xhr = new XMLHttpRequest;
		if (args.method === undefined) {
			throw new Error('请求方法未指定');
		}
		return new Promise((resolve, reject) => {
			xhr.onloadend = () => {
				if (xhr.status === 200) {
					resolve(xhr.responseText, xhr.status, xhr);
				} else {
					const err = new Error('status is not 200');
					err.status = xhr.status;
					err.responseText = xhr.responseText;
					err.xhr = xhr;
					reject(err);
				}
			};

			xhr.open(args.method.toUpperCase(), url, true);
			if (args.data !== undefined) {
				if (args.type === 'json') {
					xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
				} else if ('type' in args) {
					xhr.setRequestHeader("Content-Type", atgs.type);
				} else {
					xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
				}

				if (/json/.test(args.type)) {
					xhr.send(JSON.stringify(args.data))
				} else if (typeof args.data === 'object') {
					let formated = stringifyRequest(args.data);
					xhr.send(formated);
				} else {
					xhr.send(args.data);
				}
			} else {
				xhr.send();
			}
		});
	};
	vools.get = function (url) {
		return vools.pjax(url, { method: 'GET' })
	};
	vools.post = function (url, data = {}) {
		return vools.pjax(url, { method: 'POST', data })
	};
	vools.patch = function (url, data = {}) {
		return vools.pjax(url, { method: 'PATCH', data });
	};
	vools.delete = function (url, data = {}) {
		return vools.pjax(url, { method: 'DELETE', data });
	};
	vools.rjax = (() => {
		return (url, args) => {
			var xhr = new XMLHttpRequest;

			xhr.onloadend = () => {
				if (xhr.status === 200) {
					args.success && args.success(xhr.responseText, xhr.status, xhr);
				} else {
					args.fail && args.fail(xhr.responseText, xhr.status, xhr);
				}
			};
			if (args.method === undefined) {
				throw new Error('请求方法未指定');
			}

			xhr.open(args.method.toUpperCase(), url, true);
			if (args.data !== undefined) {
				xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
				if (typeof args.data === 'object') {
					let formated = stringifyRequest(args.data);
					xhr.send(formated);
				} else {
					xhr.send(args.data);
				}
			} else {
				xhr.send();
			}
		};
	})();

	const bPrototype = {
		BrowserCore: ['ms', 'moz', 'Moz', 'webkit'],
		dom: document.createElement('div'),
		prop: 'Transition',
		init() {
			const result = this.BrowserCore.some(prefix => {
				if (`${prefix}${this.prop}` in this.dom.style)
					return this.core = prefix.toLowerCase()
			})

			if (!result) {
				console.warn('unsupport browser rendering core')
				this.core = 'unknown'
			}

			return this.core
		},
	}
	vools.browser = Object.create(bPrototype)
	vools.browser.init()

	const voolsEvent = function (){};
	ObjecExtends(voolsEvent.prototype, {

	});
	try {
		module.exports = vools
	} catch (e) {
		if (window.define) {
			define(() => [
				vools,
				function () { return vools.apply(null, arguments).pop() }
			])
		} else {
			window.voolsEvent = voolsEvent;

			window.vools = vools;
			window.$ = vools;
			window.$$ = function (){
				return vools.apply(null, arguments)[0];
			};
		}
	}
})();
<|endoftext|>


<commit_before>'use strict';

var UltrasonicSensor = require('../index');

var ultrasonicSensor = new UltrasonicSensor(15, 14);

setInterval(function () {
    console.log(ultrasonicSensor.getDistanceCm());
}, 60);
<commit_msg>Fix test<commit_after>'use strict';

var UltrasonicSensor = require('../index').UltrasonicSensor;

var ultrasonicSensor = new UltrasonicSensor(15, 14);

setInterval(function () {
    console.log(ultrasonicSensor.getDistanceCm());
}, 60);
<|endoftext|>