<commit_before>/*global require, window */
var it = require('tape');
var Ad = require('../js/ad');
var render = require('../js/render');
var Chunk = require('./utils').mock_chunk;
var EnvConfig = require('../js/config');
var $ = require('jquery');
var should = require('should');
var utils = require('./utils');

describe("Ads", function() {
  it('ads contain currentAds', function (done) {
    should.exist(Ad);
    Ad.should.have.property('currentAds');
  });
  it("ad url creation", function(done) {
    var url = Ad.getSrc('it');
    t.equal( url,
      EnvConfig.AD_LOCATION +
        '#placement=it&groupid=&key=&height=0&uri=' +
        window.location.pathname,
      'ad iframe src set as expected'
    );
  });
});
it("ad created and rendered", function(done) {
    var dustBase = render.dustBase();
    var chunk = new Chunk();
    shuold.exist(dustBase);
    dustBase.global.ad(chunk, {}, {}, {placement: 'it'})
      .then(function() {
        var el = utils.el(chunk.output);
        var iframeSrc = EnvConfig.AD_LOCATION +
              '#placement=it&groupid=&key=&height=0&uri=' +
              window.location.pathname;
        should(el.attr('src'))
          .eql(iframeSrc, 'ad iframe html rendered correctly');
        Ad.currentAds.should.have.property('it');
        done();
      });
});
it("it reload",
  function(done) {

    t.equal(Ad.key, '', 'Keywords starts unset');
    t.equal(Ad.groupId, '', 'Group Id starts unset');
    var dustBase = render.dustBase();
    var chunk = new Chunk();
    dustBase.global.ad(chunk, {}, {}, {placement: 'it'})
      .then(function() {
          $('body').append($(chunk.output));
          t.ok($('#ad_it'), 'iframe attatched');
          Ad.reload('it keyword');
          t.equal(Ad.key, 'it keyword', 'Keywords set at refresh');
          t.notEqual(Ad.groupId, '', 'Group Id changes on reload');
          t.equal($('#ad_it').attr('src'),
            EnvConfig.AD_LOCATION +
              '#placement=it&groupid=' +
              Ad.groupId +
              '&key=it+keyword' +
              '&height=0&uri=' +
              window.location.pathname,
            'src updates on reload'
          );
          $('#ad_it').remove();
      });
  }
);
it("it event",
  function(done) {

    var dustBase = render.dustBase();
    var chunk = new Chunk();
    dustBase.global.ad(chunk, {}, {}, {placement: 'it'})
    .then(function() {
        $('body').append($(chunk.output));
        t.equal('150px', $('#ad_it').css('height'),
         'height starts at base');
        var event;
        if (document.createEvent) {
          event = document.createEvent("HTMLEvents");
          event.initEvent("message", true, true);
        } else {
          event = document.createEventObject();
          event.eventType = "message";
        }
        event.eventName = "message";
        event.data = { iframe: 'it', height: 100 };
        event.origin = EnvConfig.AD_LOCATION;
        if (document.createEvent) {
          window.document.dispatchEvent(event);
        } else {
          window.document.fireEvent("on" + event.eventType, event);
        }
        setTimeout(function () {
          t.equal('100px', $('#ad_it').css('height'),
           'height changed through event');
        }, 100);
    });
  }
);
<commit_msg>make ads use mocha tests<commit_after>/*global require, window */
var Ad = require('../js/ad');
var render = require('../js/render');
var Chunk = require('./utils').mock_chunk;
var EnvConfig = require('../js/config');
var $ = require('jquery');
var should = require('should');
var utils = require('./utils');

describe("Ads", function() {
  it('ads contain currentAds', function (done) {
    should.exist(Ad);
    should(Ad).have.property('currentAds');
    done();
  });
  it("ads create urls from placement", function(done) {
    var url = Ad.getSrc('it');
    console.log(window.location.pathname);
    should(url).eql(
      EnvConfig.AD_LOCATION +
        '#placement=it&groupid=&key=&height=0&uri=' +
        window.location.pathname
    );
  });
  it("ads are creatable and render", function(done) {
      var dustBase = render.dustBase();
      var chunk = new Chunk();
      should.exist(dustBase);
      dustBase.global.ad(chunk, {}, {}, {placement: 'it'})
        .then(function() {
          var el = utils.el(chunk.output);
          var iframeSrc = EnvConfig.AD_LOCATION +
                '#placement=it&groupid=&key=&height=0&uri=' +
                window.location.pathname;
          should(el.attr('src'))
            .eql(iframeSrc, 'ad iframe html rendered correctly');
          Ad.currentAds.should.have.property('it');
          done();
        });
  });
  it("ads reload",
    function(done) {
      should(Ad.key).be.empty;
      should(Ad.groupId).be.empty;
      var dustBase = render.dustBase();
      var chunk = new Chunk();
      dustBase.global.ad(chunk, {}, {}, {placement: 'it'})
        .then(function() {
            $('body').append($(chunk.output));
            should($('#ad_it')).be.ok;
            Ad.reload('it keyword');
            should(Ad.key).not.be.empty;
            should(Ad.groupId).eq('it keyword');
            should($('#ad_it').attr('src')).eql(
              EnvConfig.AD_LOCATION +
                '#placement=it&groupid=' +
                Ad.groupId +
                '&key=it+keyword' +
                '&height=0&uri=' +
                window.location.pathname,
              'src updates on reload'
            );
            $('#ad_it').remove();
            done();
        });
    }
  );
  it("events change ad height",
    function(done) {
      var dustBase = render.dustBase();
      var chunk = new Chunk();
      dustBase.global.ad(chunk, {}, {}, {placement: 'it'})
      .then(function() {
          $('body').append($(chunk.output));
          should($('#ad_it').css('height')).eql('150px');

          var event;
          if (document.createEvent) {
            event = document.createEvent("HTMLEvents");
            event.initEvent("message", true, true);
          } else {
            event = document.createEventObject();
            event.eventType = "message";
          }
          event.eventName = "message";
          event.data = { iframe: 'it', height: 100 };
          event.origin = EnvConfig.AD_LOCATION;
          if (document.createEvent) {
            window.document.dispatchEvent(event);
          } else {
            window.document.fireEvent("on" + event.eventType, event);
          }
          setTimeout(function () {
            should( $('#ad_it').css('height') ).eql('100px');
            done();
          }, 100);
      });
    }
  );
});
<|endoftext|>


<commit_before>/* global browser */
/* global it */
/* global describe */
/* global by */
/* global element */
/* global expect */
/* global beforeEach */

'use strict';

var htmlContentHelper =
  require('../utils/htmlContentHelper');
var findBrockenUrls = require('../utils/findBrockenUrls');

describe('Tool Bar', function() {
  function testToolBar(description, link, currentLanguage) {
    describe(description, function() {
      var currentUrl;
      var htmlContent;
      beforeEach(function() {
        browser.get(link);
        browser.getCurrentUrl().then(function(url) {
          currentUrl = url;
        });
        htmlContent = element(by.id('toolbar'));
        htmlContentHelper.showHiddenElements(htmlContent)
          .then(function(content) {
            console.log(content);
            htmlContent.outerHtml = content;
          });
      });
      it('should check translated strings', function() {
        htmlContentHelper
          .findNotTranslationedStrings(htmlContent, currentUrl)
          .then(function(result) {
            expect(result.length).toBe(0, result.message);
          });
      });
      it('should change language ', function(done) {
        var targetLanguage = currentLanguage === 'de' ? '#/en/' : '#/de/';
        var changeLanguage;
        if (currentLanguage === 'en') {
          changeLanguage = element(by.id('changeLanguageToDe'));
        }else {
          changeLanguage = element(by.id('changeLanguageToEn'));
        }
        changeLanguage.click().then(function() {
          browser.getCurrentUrl().then(function(url) {
            expect(url.indexOf(targetLanguage) !== -1).toBe(true, 'from ' +
            currentLanguage + ' to' + targetLanguage);
          });
          done();
        });
      });
      it('should open login page', function(done) {
        var loginButton = element(by.id('login'));
        loginButton.click().then(function() {
          findBrockenUrls.checkStates(browser.baseUrl +
              '#/' + currentLanguage + '/login',
              currentUrl,
              'login')
            .then(function(result) {
              expect(result.isValidUrl).toBe(true,
                result.message);
              done();
            });
        });
      });
      it('should open registration page', function(done) {
        var registerButton = element(by.id('register'));
        registerButton.click().then(function() {
          findBrockenUrls.checkStates(browser.baseUrl +
              '#/' + currentLanguage + '/register',
              currentUrl,
              'register')
            .then(function(result) {
              expect(result.isValidUrl).toBe(true,
                result.message);
              done();
            });
        });
      });
    });
  }
  testToolBar('with german language', '#/de/', 'de');
  testToolBar('with english language', '#/en/', 'en');
});
<commit_msg>#421 removed console output<commit_after>/* global browser */
/* global it */
/* global describe */
/* global by */
/* global element */
/* global expect */
/* global beforeEach */

'use strict';

var htmlContentHelper =
  require('../utils/htmlContentHelper');
var findBrockenUrls = require('../utils/findBrockenUrls');

describe('Tool Bar', function() {
  function testToolBar(description, link, currentLanguage) {
    describe(description, function() {
      var currentUrl;
      var htmlContent;
      beforeEach(function() {
        browser.get(link);
        browser.getCurrentUrl().then(function(url) {
          currentUrl = url;
        });
        htmlContent = element(by.id('toolbar'));
        htmlContentHelper.showHiddenElements(htmlContent)
          .then(function(content) {
            htmlContent.outerHtml = content;
          });
      });
      it('should check translated strings', function() {
        htmlContentHelper
          .findNotTranslationedStrings(htmlContent, currentUrl)
          .then(function(result) {
            expect(result.length).toBe(0, result.message);
          });
      });
      it('should change language ', function(done) {
        var targetLanguage = currentLanguage === 'de' ? '#/en/' : '#/de/';
        var changeLanguage;
        if (currentLanguage === 'en') {
          changeLanguage = element(by.id('changeLanguageToDe'));
        }else {
          changeLanguage = element(by.id('changeLanguageToEn'));
        }
        changeLanguage.click().then(function() {
          browser.getCurrentUrl().then(function(url) {
            expect(url.indexOf(targetLanguage) !== -1).toBe(true, 'from ' +
            currentLanguage + ' to' + targetLanguage);
          });
          done();
        });
      });
      it('should open login page', function(done) {
        var loginButton = element(by.id('login'));
        loginButton.click().then(function() {
          findBrockenUrls.checkStates(browser.baseUrl +
              '#/' + currentLanguage + '/login',
              currentUrl,
              'login')
            .then(function(result) {
              expect(result.isValidUrl).toBe(true,
                result.message);
              done();
            });
        });
      });
      it('should open registration page', function(done) {
        var registerButton = element(by.id('register'));
        registerButton.click().then(function() {
          findBrockenUrls.checkStates(browser.baseUrl +
              '#/' + currentLanguage + '/register',
              currentUrl,
              'register')
            .then(function(result) {
              expect(result.isValidUrl).toBe(true,
                result.message);
              done();
            });
        });
      });
    });
  }
  testToolBar('with german language', '#/de/', 'de');
  testToolBar('with english language', '#/en/', 'en');
});
<|endoftext|>


<commit_before>'use strict';

//  ---------------------------------------------------------------------------

const ccxt = require ('ccxt');
const { ExchangeError } = require ('ccxt/js/base/errors');
const { ArrayCache, ArrayCacheByTimestamp } = require ('./base/Cache');

// ----------------------------------------------------------------------------

module.exports = class cdax extends ccxt.cdax {
    describe () {
        return this.deepExtend (super.describe (), {
            'has': {
                'ws': true,
                'watchOrderBook': true,
                'watchTickers': false, // for now
                'watchTicker': true,
                'watchTrades': true,
                'watchBalance': false, // for now
                'watchOHLCV': true,
            },
            'urls': {
                'api': {
                    'ws': {
                        'api': {
                            'public': 'wss://{hostname}/api/ws',
                            'private': 'wss://{hostname}/api/ws/v2',
                        },
                    },
                },
                'www': 'https://cdax.io',
                'referral': 'https://cdax.io/invite?invite_code=esc74',
                'doc': 'https://github.com/cloudapidoc/API_Docs',
                'fees': 'https://cdax.io/about/fee',
            },
            'options': {
                'tradesLimit': 1000,
                'OHLCVLimit': 1000,
                'api': 'api', // or api-aws for clients hosted on AWS
                'ws': {
                    'gunzip': true,
                },
            },
        });
    }

    requestId () {
        const requestId = this.sum (this.safeInteger (this.options, 'requestId', 0), 1);
        this.options['requestId'] = requestId;
        return requestId.toString ();
    }

    async watchTicker (symbol, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        // only supports a limit of 150 at this time
        const messageHash = 'market.' + market['id'] + '.detail';
        const api = this.safeString (this.options, 'api', 'api');
        const hostname = { 'hostname': this.hostname };
        const url = this.implodeParams (this.urls['api']['ws'][api]['public'], hostname);
        const requestId = this.requestId ();
        const request = {
            'sub': messageHash,
            'id': requestId,
        };
        const subscription = {
            'id': requestId,
            'messageHash': messageHash,
            'symbol': symbol,
            'params': params,
        };
        return await this.watch (url, messageHash, this.extend (request, params), messageHash, subscription);
    }

    handleTicker (client, message) {
        //
        //     {
        //         ch: 'market.btcusdt.detail',
        //         ts: 1583494163784,
        //         tick: {
        //             id: 209988464418,
        //             low: 8988,
        //             high: 9155.41,
        //             open: 9078.91,
        //             close: 9136.46,
        //             vol: 237813910.5928412,
        //             amount: 26184.202558551195,
        //             version: 209988464418,
        //             count: 265673
        //         }
        //     }
        //
        const tick = this.safeValue (message, 'tick', {});
        const ch = this.safeString (message, 'ch');
        const parts = ch.split ('.');
        const marketId = this.safeString (parts, 1);
        const market = this.safeMarket (marketId);
        const ticker = this.parseTicker (tick, market);
        const timestamp = this.safeValue (message, 'ts');
        ticker['timestamp'] = timestamp;
        ticker['datetime'] = this.iso8601 (timestamp);
        const symbol = ticker['symbol'];
        this.tickers[symbol] = ticker;
        client.resolve (ticker, ch);
        return message;
    }

    async watchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        // only supports a limit of 150 at this time
        const messageHash = 'market.' + market['id'] + '.trade.detail';
        const api = this.safeString (this.options, 'api', 'api');
        const hostname = { 'hostname': this.hostname };
        const url = this.implodeParams (this.urls['api']['ws'][api]['public'], hostname);
        const requestId = this.requestId ();
        const request = {
            'sub': messageHash,
            'id': requestId,
        };
        const subscription = {
            'id': requestId,
            'messageHash': messageHash,
            'symbol': symbol,
            'params': params,
        };
        const trades = await this.watch (url, messageHash, this.extend (request, params), messageHash, subscription);
        if (this.newUpdates) {
            limit = trades.getLimit (symbol, limit);
        }
        return this.filterBySinceLimit (trades, since, limit, 'timestamp', true);
    }

    handleTrades (client, message) {
        //
        //     {
        //         ch: "market.btcusdt.trade.detail",
        //         ts: 1583495834011,
        //         tick: {
        //             id: 105004645372,
        //             ts: 1583495833751,
        //             data: [
        //                 {
        //                     id: 1.050046453727319e+22,
        //                     ts: 1583495833751,
        //                     tradeId: 102090727790,
        //                     amount: 0.003893,
        //                     price: 9150.01,
        //                     direction: "sell"
        //                 }
        //             ]
        //         }
        //     }
        //
        const tick = this.safeValue (message, 'tick', {});
        const data = this.safeValue (tick, 'data', {});
        const ch = this.safeString (message, 'ch');
        const parts = ch.split ('.');
        const marketId = this.safeString (parts, 1);
        const market = this.safeMarket (marketId);
        const symbol = market['symbol'];
        let tradesCache = this.safeValue (this.trades, symbol);
        if (tradesCache === undefined) {
            const limit = this.safeInteger (this.options, 'tradesLimit', 1000);
            tradesCache = new ArrayCache (limit);
            this.trades[symbol] = tradesCache;
        }
        for (let i = 0; i < data.length; i++) {
            const trade = this.parseTrade (data[i], market);
            tradesCache.append (trade);
        }
        client.resolve (tradesCache, ch);
        return message;
    }

    async watchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
        await this.loadMarkets ();
        const market = this.market (symbol);
        const interval = this.timeframes[timeframe];
        const messageHash = 'market.' + market['id'] + '.kline.' + interval;
        const api = this.safeString (this.options, 'api', 'api');
        const hostname = { 'hostname': this.hostname };
        const url = this.implodeParams (this.urls['api']['ws'][api]['public'], hostname);
        const requestId = this.requestId ();
        const request = {
            'sub': messageHash,
            'id': requestId,
        };
        const subscription = {
            'id': requestId,
            'messageHash': messageHash,
            'symbol': symbol,
            'timeframe': timeframe,
            'params': params,
        };
        const ohlcv = await this.watch (url, messageHash, this.extend (request, params), messageHash, subscription);
        if (this.newUpdates) {
            limit = ohlcv.getLimit (symbol, limit);
        }
        return this.filterBySinceLimit (ohlcv, since, limit, 0, true);
    }

    handleOHLCV (client, message) {
        //
        //     {
        //         ch: 'market.btcusdt.kline.1min',
        //         ts: 1583501786794,
        //         tick: {
        //             id: 1583501760,
        //             open: 9094.5,
        //             close: 9094.51,
        //             low: 9094.5,
        //             high: 9094.51,
        //             amount: 0.44639786263800907,
        //             vol: 4059.76919054,
        //             count: 16
        //         }
        //     }
        //
        const ch = this.safeString (message, 'ch');
        const parts = ch.split ('.');
        const marketId = this.safeString (parts, 1);
        const market = this.safeMarket (marketId);
        const symbol = market['symbol'];
        const interval = this.safeString (parts, 3);
        const timeframe = this.findTimeframe (interval);
        this.ohlcvs[symbol] = this.safeValue (this.ohlcvs, symbol, {});
        let stored = this.safeValue (this.ohlcvs[symbol], timeframe);
        if (stored === undefined) {
            const limit = this.safeInteger (this.options, 'OHLCVLimit', 1000);
            stored = new ArrayCacheByTimestamp (limit);
            this.ohlcvs[symbol][timeframe] = stored;
        }
        const tick = this.safeValue (message, 'tick');
        const parsed = this.parseOHLCV (tick, market);
        stored.append (parsed);
        client.resolve (stored, ch);
    }

    async watchOrderBook (symbol, limit = undefined, params = {}) {
        if ((limit !== undefined) && (limit !== 150)) {
            throw new ExchangeError (this.id + ' watchOrderBook accepts limit = 150 only');
        }
        await this.loadMarkets ();
        const market = this.market (symbol);
        // only supports a limit of 150 at this time
        limit = (limit === undefined) ? 150 : limit;
        const messageHash = 'market.' + market['id'] + '.mbp.' + limit.toString ();
        const api = this.safeString (this.options, 'api', 'api');
        const hostname = { 'hostname': this.hostname };
        const url = this.implodeParams (this.urls['api']['ws'][api]['public'], hostname);
        const requestId = this.requestId ();
        const request = {
            'sub': messageHash,
            'id': requestId,
        };
        const subscription = {
            'id': requestId,
            'messageHash': messageHash,
            'symbol': symbol,
            'limit': limit,
            'params': params,
            'method': this.handleOrderBookSubscription,
        };
        const orderbook = await this.watch (url, messageHash, this.extend (request, params), messageHash, subscription);
        return orderbook.limit (limit);
    }

    handleOrderBookSnapshot (client, message, subscription) {
        //
        //     {
        //         id: 1583473663565,
        //         rep: 'market.btcusdt.mbp.150',
        //         status: 'ok',
        //         data: {
        //             seqNum: 104999417756,
        //             bids: [
        //                 [9058.27, 0],
        //                 [9058.43, 0],
        //                 [9058.99, 0],
        //             ],
        //             asks: [
        //                 [9084.27, 0.2],
        //                 [9085.69, 0],
        //                 [9085.81, 0],
        //             ]
        //         }
        //     }
        //
        const symbol = this.safeString (subscription, 'symbol');
        const messageHash = this.safeString (subscription, 'messageHash');
        const orderbook = this.orderbooks[symbol];
        const data = this.safeValue (message, 'data');
        const snapshot = this.parseOrderBook (data, symbol);
        snapshot['nonce'] = this.safeInteger (data, 'seqNum');
        orderbook.reset (snapshot);
        // unroll the accumulated deltas
        const messages = orderbook.cache;
        for (let i = 0; i < messages.length; i++) {
            const message = messages[i];
            this.handleOrderBookMessage (client, message, orderbook);
        }
        this.orderbooks[symbol] = orderbook;
        client.resolve (orderbook, messageHash);
    }

    async watchOrderBookSnapshot (client, message, subscription) {
        const symbol = this.safeString (subscription, 'symbol');
        const limit = this.safeInteger (subscription, 'limit');
        const params = this.safeValue (subscription, 'params');
        const messageHash = this.safeString (subscription, 'messageHash');
        const api = this.safeString (this.options, 'api', 'api');
        const hostname = { 'hostname': this.hostname };
        const url = this.implodeParams (this.urls['api']['ws'][api]['public'], hostname);
        const requestId = this.requestId ();
        const request = {
            'req': messageHash,
            'id': requestId,
        };
        // this is a temporary subscription by a specific requestId
        // it has a very short lifetime until the snapshot is received over ws
        const snapshotSubscription = {
            'id': requestId,
            'messageHash': messageHash,
            'symbol': symbol,
            'limit': limit,
            'params': params,
            'method': this.handleOrderBookSnapshot,
        };
        const orderbook = await this.watch (url, requestId, request, requestId, snapshotSubscription);
        return orderbook.limit (limit);
    }

    handleDelta (bookside, delta) {
        const price = this.safeFloat (delta, 0);
        const amount = this.safeFloat (delta, 1);
        bookside.store (price, amount);
    }

    handleDeltas (bookside, deltas) {
        for (let i = 0; i < deltas.length; i++) {
            this.handleDelta (bookside, deltas[i]);
        }
    }

    handleOrderBookMessage (client, message, orderbook) {
        //
        //     {
        //         ch: "market.btcusdt.mbp.150",
        //         ts: 1583472025885,
        //         tick: {
        //             seqNum: 104998984994,
        //             prevSeqNum: 104998984977,
        //             bids: [
        //                 [9058.27, 0],
        //                 [9058.43, 0],
        //                 [9058.99, 0],
        //             ],
        //             asks: [
        //                 [9084.27, 0.2],
        //                 [9085.69, 0],
        //                 [9085.81, 0],
        //             ]
        //         }
        //     }
        //
        const tick = this.safeValue (message, 'tick', {});
        const seqNum = this.safeInteger (tick, 'seqNum');
        const prevSeqNum = this.safeInteger (tick, 'prevSeqNum');
        if ((prevSeqNum <= orderbook['nonce']) && (seqNum > orderbook['nonce'])) {
            const asks = this.safeValue (tick, 'asks', []);
            const bids = this.safeValue (tick, 'bids', []);
            this.handleDeltas (orderbook['asks'], asks);
            this.handleDeltas (orderbook['bids'], bids);
            orderbook['nonce'] = seqNum;
            const timestamp = this.safeInteger (message, 'ts');
            orderbook['timestamp'] = timestamp;
            orderbook['datetime'] = this.iso8601 (timestamp);
        }
        return orderbook;
    }

    handleOrderBook (client, message) {
        //
        // deltas
        //
        //     {
        //         ch: "market.btcusdt.mbp.150",
        //         ts: 1583472025885,
        //         tick: {
        //             seqNum: 104998984994,
        //             prevSeqNum: 104998984977,
        //             bids: [
        //                 [9058.27, 0],
        //                 [9058.43, 0],
        //                 [9058.99, 0],
        //             ],
        //             asks: [
        //                 [9084.27, 0.2],
        //                 [9085.69, 0],
        //                 [9085.81, 0],
        //             ]
        //         }
        //     }
        //
        const messageHash = this.safeString (message, 'ch');
        const ch = this.safeValue (message, 'ch');
        const parts = ch.split ('.');
        const marketId = this.safeString (parts, 1);
        const symbol = this.safeSymbol (marketId);
        const orderbook = this.orderbooks[symbol];
        if (orderbook['nonce'] === undefined) {
            orderbook.cache.push (message);
        } else {
            this.handleOrderBookMessage (client, message, orderbook);
            client.resolve (orderbook, messageHash);
        }
    }

    handleOrderBookSubscription (client, message, subscription) {
        const symbol = this.safeString (subscription, 'symbol');
        const limit = this.safeInteger (subscription, 'limit');
        if (symbol in this.orderbooks) {
            delete this.orderbooks[symbol];
        }
        this.orderbooks[symbol] = this.orderBook ({}, limit);
        // watch the snapshot in a separate async call
        this.spawn (this.watchOrderBookSnapshot, client, message, subscription);
    }

    handleSubscriptionStatus (client, message) {
        //
        //     {
        //         "id": 1583414227,
        //         "status": "ok",
        //         "subbed": "market.btcusdt.mbp.150",
        //         "ts": 1583414229143
        //     }
        //
        const id = this.safeString (message, 'id');
        const subscriptionsById = this.indexBy (client.subscriptions, 'id');
        const subscription = this.safeValue (subscriptionsById, id);
        if (subscription !== undefined) {
            const method = this.safeValue (subscription, 'method');
            if (method !== undefined) {
                return method.call (this, client, message, subscription);
            }
            // clean up
            if (id in client.subscriptions) {
                delete client.subscriptions[id];
            }
        }
        return message;
    }

    handleSystemStatus (client, message) {
        //
        // todo: answer the question whether handleSystemStatus should be renamed
        // and unified as handleStatus for any usage pattern that
        // involves system status and maintenance updates
        //
        //     {
        //         id: '1578090234088', // connectId
        //         type: 'welcome',
        //     }
        //
        return message;
    }

    handleSubject (client, message) {
        //
        //     {
        //         ch: "market.btcusdt.mbp.150",
        //         ts: 1583472025885,
        //         tick: {
        //             seqNum: 104998984994,
        //             prevSeqNum: 104998984977,
        //             bids: [
        //                 [9058.27, 0],
        //                 [9058.43, 0],
        //                 [9058.99, 0],
        //             ],
        //             asks: [
        //                 [9084.27, 0.2],
        //                 [9085.69, 0],
        //                 [9085.81, 0],
        //             ]
        //         }
        //     }
        //
        const ch = this.safeValue (message, 'ch');
        const parts = ch.split ('.');
        const type = this.safeString (parts, 0);
        if (type === 'market') {
            const methodName = this.safeString (parts, 2);
            const methods = {
                'mbp': this.handleOrderBook,
                'detail': this.handleTicker,
                'trade': this.handleTrades,
                'kline': this.handleOHLCV,
                // ...
            };
            const method = this.safeValue (methods, methodName);
            if (method === undefined) {
                return message;
            } else {
                return method.call (this, client, message);
            }
        }
    }

    async pong (client, message) {
        //
        //     { ping: 1583491673714 }
        //
        await client.send ({ 'pong': this.safeInteger (message, 'ping') });
    }

    handlePing (client, message) {
        this.spawn (this.pong, client, message);
    }

    handleErrorMessage (client, message) {
        //
        //     {
        //         ts: 1586323747018,
        //         status: 'error',
        //         'err-code': 'bad-request',
        //         'err-msg': 'invalid mbp.150.symbol linkusdt',
        //         id: '2'
        //     }
        //
        const status = this.safeString (message, 'status');
        if (status === 'error') {
            const id = this.safeString (message, 'id');
            const subscriptionsById = this.indexBy (client.subscriptions, 'id');
            const subscription = this.safeValue (subscriptionsById, id);
            if (subscription !== undefined) {
                const errorCode = this.safeString (message, 'err-code');
                try {
                    this.throwExactlyMatchedException (this.exceptions['exact'], errorCode, this.json (message));
                } catch (e) {
                    const messageHash = this.safeString (subscription, 'messageHash');
                    client.reject (e, messageHash);
                    client.reject (e, id);
                    if (id in client.subscriptions) {
                        delete client.subscriptions[id];
                    }
                }
            }
            return false;
        }
        return message;
    }

    handleMessage (client, message) {
        if (this.handleErrorMessage (client, message)) {
            //
            //     {"id":1583414227,"status":"ok","subbed":"market.btcusdt.mbp.150","ts":1583414229143}
            //
            if ('id' in message) {
                this.handleSubscriptionStatus (client, message);
            } else if ('ch' in message) {
                // route by channel aka topic aka subject
                this.handleSubject (client, message);
            } else if ('ping' in message) {
                this.handlePing (client, message);
            }
        }
    }
};
<commit_msg>delist cdax<commit_after><|endoftext|>


<commit_before>var rekuire = require('rekuire');
var config = require('config');
var mongoose = require('mongoose');
var async = require('async');

module.exports = {

    start: function(collections, cb) {
        var db = mongoose.connection.db;
        var functions = [];
        for (var name in collections) {
            functions.push(function(cb) {
                db.createCollection(name, function(err, collection) {
                    collection.remove({}, function() {
                        collection.insert(collections[name], cb);
                    });
                });
            });
        }
        async.parallel(functions, cb);
    },

    stop: function(cb) {
        cb();
    }
};<commit_msg>Fixed test problem when the mongodb is empty<commit_after>var rekuire = require('rekuire');
var config = require('config');
var mongoose = require('mongoose');
var async = require('async');

module.exports = {

    start: function(collections, cb) {
        var db = mongoose.connection.db;
        var functions = [];
        for (var name in collections) {
            functions.push(function(cb) {
               db.collection(name, function(err, collection) {
                    collection.remove({}, function() {
                        collection.insert(collections[name], cb);
                    });
                });
            });
        }
        async.parallel(functions, cb);
    },

    stop: function(cb) {
        cb();
    }
};<|endoftext|>


<commit_before>class Core {
	constructor() {
		this.$infoHeader = $('#info-header');
		this.$noWallet = $('#no-wallets-empty');
		this.$summaryBalances = $('#summaryBalances');
		this.$walletDetails = $('#wallet-details');

		myWallets.onWalletSaved(() => {
			this.renderView();
		});

		this.renderView();
	}

	renderView() {
		let wallets = myWallets.fetch();
		if (wallets.length === 0) {
			this.noWallets();
			return;
		}
		this.getTokensAndRender(wallets);
	}

	registerRemoveWallet() {
		this.$removeWallet = $('.remove-wallet');

		Rx.Observable.fromEvent(this.$removeWallet, 'click')
		.map(e => {
			let address = $(e.target).closest('.card').find('.address-id').text();
			return address;
		})
		.subscribe(address => {
			let removed = Settings.removeWallet(address);
			console.log(removed);
			this.renderView();
		});
	}

	noWallets() {
		this.$noWallet.show();
		this.$infoHeader.html(`This is a Free, open-source, client-side interface for Ethereum wallet dashboard that shows,
			in depth balance and summary of your all your Ethereum & ERC-20 tokens.
 To get started just add all your Ethereum wallet public keys and see the magic.`)
	}

	getTokensAndRender(wallets) {
		this.$infoHeader.text('Tokens Summary');
		this.$noWallet.hide();
		this.$summaryBalances.empty().html(`<span class="col-sm-12">Loading Blockchain....</span>`).show();

		myWallets.getTokens(wallets)
			.subscribe((list) => {
				let summary = this.computeSummary(list);
				this.renderSummaryView(summary);
				this.renderWalletDetails(list);
				this.registerRemoveWallet();
			});
	}

	computeSummary(list) {
		// As we are changing inside wallets array thus need to cloneDeep.
		//let wallets = _.cloneDeep(list);
		let wallets = list.filter(b => !_.property('error')(b));

		return wallets.reduce((totalTokenSummary, wallet) => {
			let tokens = wallet.tokens;
			for (let token of tokens) {
					// Find if that token exists, then add baalance to it.
				let tokenIndex = _.findIndex(totalTokenSummary, _token => _token.symbol == token.symbol);
				if (tokenIndex !== -1) {
					totalTokenSummary[tokenIndex].balance = totalTokenSummary[tokenIndex].balance + token.balance;
				} else {
					totalTokenSummary.push(token);
				}
			}
			return totalTokenSummary;
		}, [])
	}

	renderTokens(tokens) {
		//
		return `
			${tokens.map(token => `

${token.symbol}

${Utils.roundOff(token.balance)}

                        `
		).join('')}`;
	}

	renderWalletDetails(list) {
		let filteredList = list.filter(b => !_.property('error')(b));
		let errorList = list.filter(b => !!_.property('error')(b));

		this.$walletDetails.empty();

		if (filteredList.length > 0) {
			let details = `
			${filteredList.map(item => `

${item.name}

	              <button type="button" class="close remove-wallet" aria-label="Close">
								  ×
								</button>

               <h7 class="card-subtitle mb-2 text-muted address-id">${item.address}</h7>

									${this.renderTokens(item.tokens)}

			`).join('')}
		`;
			this.$walletDetails.append(details);
		}

		if (errorList.length > 0) {
			let errorDetails = `
			${errorList.map(item => `

${item.name}

	              <button type="button" class="close remove-wallet" aria-label="Close">
								  ×
								</button>

							<h7 class="card-subtitle mb-2 text-muted address-id">${item.address}</h7>

                   ${item.error.message}

			`).join('')}
		`;
			this.$walletDetails.append(errorDetails);
		}
	}

	renderSummaryView(summary) {
		const $summaryBalances = this.$summaryBalances;
		$summaryBalances.empty();
		if (summary.length > 0) {
			for (let token of summary) {
				if (token.balance >= 0.00001) {
					let balance = Utils.roundOff(token.balance);
					let className = `cc ${token.symbol} pr-2`;
					$summaryBalances.append(`<span class="col-sm-4 col-lg-3 col-xl-2 col-6 mt-4"><i class="${className}"></i>${balance} ${token.symbol}</span>`);
					const icon = $summaryBalances[0].getElementsByClassName(className)[0];

					const psudeo = window.getComputedStyle(icon, ':before').getPropertyValue('content');
					if (!psudeo) {
						$(icon).removeClass(token.symbol).addClass('BTC-alt');
					}
				}
			}
		}
	}

}

const init = new Core();<commit_msg>Bug fix remove old card remnants when no wallets found.<commit_after>class Core {
	constructor() {
		this.$infoHeader = $('#info-header');
		this.$noWallet = $('#no-wallets-empty');
		this.$summaryBalances = $('#summaryBalances');
		this.$walletDetails = $('#wallet-details');

		myWallets.onWalletSaved(() => {
			this.renderView();
		});

		this.renderView();
	}

	clearState() {
		this.$summaryBalances.empty();
		this.$walletDetails.empty();
	}

	renderView() {
		let wallets = myWallets.fetch();
		if (wallets.length === 0) {
			this.noWallets();
			return;
		}
		this.getTokensAndRender(wallets);
	}

	registerRemoveWallet() {
		this.$removeWallet = $('.remove-wallet');

		Rx.Observable.fromEvent(this.$removeWallet, 'click')
		.map(e => {
			let address = $(e.target).closest('.card').find('.address-id').text();
			return address;
		})
		.subscribe(address => {
			let removed = Settings.removeWallet(address);
			console.log(removed);
			this.renderView();
		});
	}

	noWallets() {
		this.clearState();
		this.$noWallet.show();
		this.$infoHeader.html(`This is a Free, open-source, client-side interface for Ethereum wallet dashboard that shows,
			in depth balance and summary of your all your Ethereum & ERC-20 tokens.
 To get started just add all your Ethereum wallet public keys and see the magic.`)
	}

	getTokensAndRender(wallets) {
		this.$infoHeader.text('Tokens Summary');
		this.$noWallet.hide();
		this.$summaryBalances.empty().html(`<span class="col-sm-12">Loading Blockchain....</span>`).show();

		myWallets.getTokens(wallets)
			.subscribe((list) => {
				let summary = this.computeSummary(list);
				this.renderSummaryView(summary);
				this.renderWalletDetails(list);
				this.registerRemoveWallet();
			});
	}

	computeSummary(list) {
		// As we are changing inside wallets array thus need to cloneDeep.
		//let wallets = _.cloneDeep(list);
		let wallets = list.filter(b => !_.property('error')(b));

		return wallets.reduce((totalTokenSummary, wallet) => {
			let tokens = wallet.tokens;
			for (let token of tokens) {
					// Find if that token exists, then add baalance to it.
				let tokenIndex = _.findIndex(totalTokenSummary, _token => _token.symbol == token.symbol);
				if (tokenIndex !== -1) {
					totalTokenSummary[tokenIndex].balance = totalTokenSummary[tokenIndex].balance + token.balance;
				} else {
					totalTokenSummary.push(token);
				}
			}
			return totalTokenSummary;
		}, [])
	}

	renderTokens(tokens) {
		//
		return `
			${tokens.map(token => `

${token.symbol}

${Utils.roundOff(token.balance)}

                        `
		).join('')}`;
	}

	renderWalletDetails(list) {
		let filteredList = list.filter(b => !_.property('error')(b));
		let errorList = list.filter(b => !!_.property('error')(b));

		this.$walletDetails.empty();

		if (filteredList.length > 0) {
			let details = `
			${filteredList.map(item => `

${item.name}

	              <button type="button" class="close remove-wallet" aria-label="Close">
								  ×
								</button>

               <h7 class="card-subtitle mb-2 text-muted address-id">${item.address}</h7>

									${this.renderTokens(item.tokens)}

			`).join('')}
		`;
			this.$walletDetails.append(details);
		}

		if (errorList.length > 0) {
			let errorDetails = `
			${errorList.map(item => `

${item.name}

	              <button type="button" class="close remove-wallet" aria-label="Close">
								  ×
								</button>

							<h7 class="card-subtitle mb-2 text-muted address-id">${item.address}</h7>

                   ${item.error.message}

			`).join('')}
		`;
			this.$walletDetails.append(errorDetails);
		}
	}

	renderSummaryView(summary) {
		const $summaryBalances = this.$summaryBalances;
		$summaryBalances.empty();
		if (summary.length > 0) {
			for (let token of summary) {
				if (token.balance >= 0.00001) {
					let balance = Utils.roundOff(token.balance);
					let className = `cc ${token.symbol} pr-2`;
					$summaryBalances.append(`<span class="col-sm-4 col-lg-3 col-xl-2 col-6 mt-4"><i class="${className}"></i>${balance} ${token.symbol}</span>`);
					const icon = $summaryBalances[0].getElementsByClassName(className)[0];

					const psudeo = window.getComputedStyle(icon, ':before').getPropertyValue('content');
					if (!psudeo) {
						$(icon).removeClass(token.symbol).addClass('BTC-alt');
					}
				}
			}
		}
	}

}

const init = new Core();<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012-2014 André Bargull
 * Alle Rechte vorbehalten / All Rights Reserved.  Use is subject to license terms.
 *
 * <https://github.com/anba/es6draft>
 */

const Transformers = (() => {
  function toStr(number, radix, pad) {
    let s = number.toString(radix);
    return "0".repeat(pad - s.length) + s;
  }

  function rangeLength(range) {
    return ~~((range.end - range.start) / range.increment) + 1;
  }

  function identity(range) {
    return String(range);
  }

  function toCharClass(pattern, range) {
    return `[${pattern}]{${rangeLength(range)}}`;
  }

  function toNegatedCharClass(pattern, range) {
    return `[^${pattern}]{${rangeLength(range)}}`;
  }

  function toCharClassRange(t, range) {
    return `[${t(range.startR())}-${t(range.endR())}]{${rangeLength(range)}}`;
  }

  function toNegatedCharClassRange(t, range) {
    return `[^${t(range.startR())}-${t(range.endR())}]{${rangeLength(range)}}`;
  }

  function toIdentityEscape(range) {
    let result = "";
    for (let cp of String(range)) {
      if ((cp >= '0' && cp <= '9') || (cp >= 'A' && cp <= 'Z') || (cp >= 'a' && cp <= 'z')) {
        result += cp;
      } else {
        result += `\\${cp}`;
      }
    }
    return result;
  }

  function toOctalEscape(range) {
    let result = "";
    for (let cp of range) {
      result += `\\0${toStr(cp, 8, 3)}`;
    }
    return result;
  }

  function toHexEscape(range) {
    let result = "";
    for (let cp of range) {
      result += `\\x${toStr(cp, 16, 2)}`;
    }
    return result;
  }

  function toUnicodeEscape(range) {
    let result = "";
    for (let cp of range) {
      result += `\\u${toStr(cp, 16, 4)}`;
    }
    return result;
  }

  function toExtendedUnicodeEscape(range) {
    let result = "";
    for (let cp of range) {
      result += `\\u{${cp.toString(16)}}`;
    }
    return result;
  }

  const combine = (f, g) => (...args) => f(g(...args), ...args);
  const combine2 = (f, g) => (...args) => f(g, ...args);

  return {
    identity, toIdentityEscape, toOctalEscape, toHexEscape, toUnicodeEscape, toExtendedUnicodeEscape,
    charClass: {
      identity: combine(toCharClass, identity),
      toIdentityEscape: combine(toCharClass, toIdentityEscape),
      toOctalEscape: combine(toCharClass, toOctalEscape),
      toHexEscape: combine(toCharClass, toHexEscape),
      toUnicodeEscape: combine(toCharClass, toUnicodeEscape),
      toExtendedUnicodeEscape: combine(toCharClass, toExtendedUnicodeEscape),
      negated: {
        identity: combine(toNegatedCharClass, identity),
        toIdentityEscape: combine(toNegatedCharClass, toIdentityEscape),
        toOctalEscape: combine(toNegatedCharClass, toOctalEscape),
        toHexEscape: combine(toNegatedCharClass, toHexEscape),
        toUnicodeEscape: combine(toNegatedCharClass, toUnicodeEscape),
        toExtendedUnicodeEscape: combine(toNegatedCharClass, toExtendedUnicodeEscape),
      },
    },
    charClassRange: {
      identity: combine2(toCharClassRange, identity),
      toIdentityEscape: combine2(toCharClassRange, toIdentityEscape),
      toOctalEscape: combine2(toCharClassRange, toOctalEscape),
      toHexEscape: combine2(toCharClassRange, toHexEscape),
      toUnicodeEscape: combine2(toCharClassRange, toUnicodeEscape),
      toExtendedUnicodeEscape: combine2(toCharClassRange, toExtendedUnicodeEscape),
      negated: {
        identity: combine2(toNegatedCharClassRange, identity),
        toIdentityEscape: combine2(toNegatedCharClassRange, toIdentityEscape),
        toOctalEscape: combine2(toNegatedCharClassRange, toOctalEscape),
        toHexEscape: combine2(toNegatedCharClassRange, toHexEscape),
        toUnicodeEscape: combine2(toNegatedCharClassRange, toUnicodeEscape),
        toExtendedUnicodeEscape: combine2(toNegatedCharClassRange, toExtendedUnicodeEscape),
      },
    },
  };
})();
<commit_msg>Remove leading zero in transform function<commit_after>/*
 * Copyright (c) 2012-2014 André Bargull
 * Alle Rechte vorbehalten / All Rights Reserved.  Use is subject to license terms.
 *
 * <https://github.com/anba/es6draft>
 */

const Transformers = (() => {
  function toStr(number, radix, pad) {
    let s = number.toString(radix);
    return "0".repeat(pad - s.length) + s;
  }

  function rangeLength(range) {
    return ~~((range.end - range.start) / range.increment) + 1;
  }

  function identity(range) {
    return String(range);
  }

  function toCharClass(pattern, range) {
    return `[${pattern}]{${rangeLength(range)}}`;
  }

  function toNegatedCharClass(pattern, range) {
    return `[^${pattern}]{${rangeLength(range)}}`;
  }

  function toCharClassRange(t, range) {
    return `[${t(range.startR())}-${t(range.endR())}]{${rangeLength(range)}}`;
  }

  function toNegatedCharClassRange(t, range) {
    return `[^${t(range.startR())}-${t(range.endR())}]{${rangeLength(range)}}`;
  }

  function toIdentityEscape(range) {
    let result = "";
    for (let cp of String(range)) {
      if ((cp >= '0' && cp <= '9') || (cp >= 'A' && cp <= 'Z') || (cp >= 'a' && cp <= 'z')) {
        result += cp;
      } else {
        result += `\\${cp}`;
      }
    }
    return result;
  }

  function toOctalEscape(range) {
    let result = "";
    for (let cp of range) {
      result += `\\${toStr(cp, 8, 3)}`;
    }
    return result;
  }

  function toHexEscape(range) {
    let result = "";
    for (let cp of range) {
      result += `\\x${toStr(cp, 16, 2)}`;
    }
    return result;
  }

  function toUnicodeEscape(range) {
    let result = "";
    for (let cp of range) {
      result += `\\u${toStr(cp, 16, 4)}`;
    }
    return result;
  }

  function toExtendedUnicodeEscape(range) {
    let result = "";
    for (let cp of range) {
      result += `\\u{${cp.toString(16)}}`;
    }
    return result;
  }

  const combine = (f, g) => (...args) => f(g(...args), ...args);
  const combine2 = (f, g) => (...args) => f(g, ...args);

  return {
    identity, toIdentityEscape, toOctalEscape, toHexEscape, toUnicodeEscape, toExtendedUnicodeEscape,
    charClass: {
      identity: combine(toCharClass, identity),
      toIdentityEscape: combine(toCharClass, toIdentityEscape),
      toOctalEscape: combine(toCharClass, toOctalEscape),
      toHexEscape: combine(toCharClass, toHexEscape),
      toUnicodeEscape: combine(toCharClass, toUnicodeEscape),
      toExtendedUnicodeEscape: combine(toCharClass, toExtendedUnicodeEscape),
      negated: {
        identity: combine(toNegatedCharClass, identity),
        toIdentityEscape: combine(toNegatedCharClass, toIdentityEscape),
        toOctalEscape: combine(toNegatedCharClass, toOctalEscape),
        toHexEscape: combine(toNegatedCharClass, toHexEscape),
        toUnicodeEscape: combine(toNegatedCharClass, toUnicodeEscape),
        toExtendedUnicodeEscape: combine(toNegatedCharClass, toExtendedUnicodeEscape),
      },
    },
    charClassRange: {
      identity: combine2(toCharClassRange, identity),
      toIdentityEscape: combine2(toCharClassRange, toIdentityEscape),
      toOctalEscape: combine2(toCharClassRange, toOctalEscape),
      toHexEscape: combine2(toCharClassRange, toHexEscape),
      toUnicodeEscape: combine2(toCharClassRange, toUnicodeEscape),
      toExtendedUnicodeEscape: combine2(toCharClassRange, toExtendedUnicodeEscape),
      negated: {
        identity: combine2(toNegatedCharClassRange, identity),
        toIdentityEscape: combine2(toNegatedCharClassRange, toIdentityEscape),
        toOctalEscape: combine2(toNegatedCharClassRange, toOctalEscape),
        toHexEscape: combine2(toNegatedCharClassRange, toHexEscape),
        toUnicodeEscape: combine2(toNegatedCharClassRange, toUnicodeEscape),
        toExtendedUnicodeEscape: combine2(toNegatedCharClassRange, toExtendedUnicodeEscape),
      },
    },
  };
})();
<|endoftext|>


<commit_before>const test = require('ava');
const upcast = require('../src');

const testFn = function() {};
testFn.foo = 'bar';

test('should be a function', t => {
    t.true(typeof upcast.to === 'function');
});

const testTo = (t, inputs, expected) => {
    inputs.forEach(input => {
        if (expected === 'function') {
            return t.deepEqual(upcast.to(input, 'function')(), input);
        }

        if (isNaN(input.to)) {
            return t.true(isNaN(upcast.to(input.from, expected)));
        }

        t.deepEqual(upcast.to(input.from, expected), input.to);
    });
};

test('should convert to arrays correctly', testTo, [
    {from: ['a', 'b', 'c'], to: ['a', 'b', 'c']},
    {from: [1, 2, 3], to: [1, 2, 3]},
    {from: [], to: []},
    {from: true, to: [true]},
    {from: false, to: [false]},
    {from: testFn, to: [testFn]},
    {from: null, to: []},
    {from: 123, to: [123]},
    {from: NaN, to: [NaN]},
    {from: Infinity, to: [Infinity]},
    {from: {foo: 'bar'}, to: [{foo: 'bar'}]},
    {from: 'foo', to: ['f', 'o', 'o']},
    {from: '', to: []},
    {from: 'true', to: [true]},
    {from: 'false', to: [false]},
    {from: undefined, to: []}
], 'array');

test('should convert to arrays with correct types', t => {
    t.is(upcast.to('true', 'array')[0], true);
    t.is(upcast.to('false', 'array')[0], false);
});

test('should convert to booleans correctly', testTo, [
    {from: ['a', 'b', 'c'], to: true},
    {from: [1, 2, 3], to: true},
    {from: [], to: false},
    {from: true, to: true},
    {from: false, to: false},
    {from: testFn, to: true},
    {from: null, to: false},
    {from: 123, to: true},
    {from: 0, to: false},
    {from: NaN, to: false},
    {from: Infinity, to: true},
    {from: {foo: 'bar'}, to: true},
    {from: 'foo', to: true},
    {from: '', to: false},
    {from: 'true', to: true},
    {from: 'false', to: false},
    {from: undefined, to: false}
], 'boolean');

test('should convert to functions correctly', testTo, [
    ['a', 'b', 'c'],
    [1, 2, 3],
    [],
    true,
    false,
    null,
    123,
    0,
    NaN,
    Infinity,
    {foo: 'bar'},
    'foo',
    '',
    'true',
    'false',
    undefined
], 'function');

test('should convert to null correctly', testTo, [
    {from: ['a', 'b', 'c'], to: null},
    {from: [1, 2, 3], to: null},
    {from: [], to: null},
    {from: true, to: null},
    {from: false, to: null},
    {from: testFn, to: null},
    {from: null, to: null},
    {from: 123, to: null},
    {from: 0, to: null},
    {from: NaN, to: null},
    {from: Infinity, to: null},
    {from: {foo: 'bar'}, to: null},
    {from: 'foo', to: null},
    {from: '', to: null},
    {from: 'true', to: null},
    {from: 'false', to: null},
    {from: undefined, to: null}
], 'null');

test('should convert to numbers correctly', testTo, [
    {from: ['a', 'b', 'c'], to: 0},
    {from: [1, 2, 3], to: 123},
    {from: [], to: 0},
    {from: true, to: 1},
    {from: false, to: 0},
    {from: testFn, to: NaN},
    {from: null, to: 0},
    {from: 123, to: 123},
    {from: 1.23, to: 1.23},
    {from: '123', to: 123},
    {from: '1.23', to: 1.23},
    {from: NaN, to: NaN},
    {from: Infinity, to: Infinity},
    {from: {foo: 'bar'}, to: NaN},
    {from: 'foo', to: 0},
    {from: '', to: 0},
    {from: 'true', to: 1},
    {from: 'false', to: 0},
    {from: undefined, to: 0}
], 'number');

/* eslint-disable no-new-object */
test('should convert to objects correctly', testTo, [
    {from: ['a', 'b', 'c'], to: {0: 'a', 1: 'b', 2: 'c'}},
    {from: [1, 2, 3], to: {0: 1, 1: 2, 2: 3}},
    {from: [], to: []},
    {from: true, to: new Object(true)},
    {from: false, to: new Object(false)},
    {from: testFn, to: testFn},
    {from: null, to: {}},
    {from: 123, to: new Object(123)},
    {from: NaN, to: {}},
    {from: Infinity, to: new Object(Infinity)},
    {from: {foo: 'bar'}, to: {foo: 'bar'}},
    {from: 'foo', to: {0: 'f', 1: 'o', 2: 'o'}},
    {from: '', to: new Object('')},
    {from: 'true', to: Object(true)},
    {from: 'false', to: Object(false)},
    {from: undefined, to: {}}
], 'object');
/* eslint-enable */

test('should convert to strings correctly', testTo, [
    {from: ['a', 'b', 'c'], to: 'abc'},
    {from: [1, 2, 3], to: '123'},
    {from: [], to: ''},
    {from: true, to: 'true'},
    {from: false, to: 'false'},
    {from: testFn, to: 'function () {}'},
    {from: null, to: ''},
    {from: 123, to: '123'},
    {from: NaN, to: 'NaN'},
    {from: Infinity, to: 'Infinity'},
    {from: {foo: 'bar'}, to: '[object Object]'},
    {from: 'foo', to: 'foo'},
    {from: '', to: ''},
    {from: 'true', to: 'true'},
    {from: 'false', to: 'false'},
    {from: undefined, to: ''}
], 'string');

test('should convert to undefined correctly', testTo, [
    {from: ['a', 'b', 'c'], to: undefined},
    {from: [1, 2, 3], to: undefined},
    {from: [], to: undefined},
    {from: true, to: undefined},
    {from: false, to: undefined},
    {from: testFn, to: undefined},
    {from: null, to: undefined},
    {from: 123, to: undefined},
    {from: 0, to: undefined},
    {from: NaN, to: undefined},
    {from: Infinity, to: undefined},
    {from: {foo: 'bar'}, to: undefined},
    {from: 'foo', to: undefined},
    {from: '', to: undefined},
    {from: 'true', to: undefined},
    {from: 'false', to: undefined},
    {from: undefined, to: undefined}
], 'undefined');

test('should throw when called with a non-string type', t => {
    t.throws(() => {
        upcast.to('bar', 123);
    }, /invalid argument: type/i);
});

test('should resolve type aliases', t => {
    upcast.alias.seq = 'array';
    t.deepEqual(upcast.to('foo', 'seq'), ['f', 'o', 'o']);
});

test('should guard against types without casters', t => {
    t.is(upcast.to('foo', 'poo'), 'foo');
});
<commit_msg>disable unicorn/new-for-builtins for single test<commit_after>const test = require('ava');
const upcast = require('../src');

const testFn = function() {};
testFn.foo = 'bar';

test('should be a function', t => {
    t.true(typeof upcast.to === 'function');
});

const testTo = (t, inputs, expected) => {
    inputs.forEach(input => {
        if (expected === 'function') {
            return t.deepEqual(upcast.to(input, 'function')(), input);
        }

        if (isNaN(input.to)) {
            return t.true(isNaN(upcast.to(input.from, expected)));
        }

        t.deepEqual(upcast.to(input.from, expected), input.to);
    });
};

test('should convert to arrays correctly', testTo, [
    {from: ['a', 'b', 'c'], to: ['a', 'b', 'c']},
    {from: [1, 2, 3], to: [1, 2, 3]},
    {from: [], to: []},
    {from: true, to: [true]},
    {from: false, to: [false]},
    {from: testFn, to: [testFn]},
    {from: null, to: []},
    {from: 123, to: [123]},
    {from: NaN, to: [NaN]},
    {from: Infinity, to: [Infinity]},
    {from: {foo: 'bar'}, to: [{foo: 'bar'}]},
    {from: 'foo', to: ['f', 'o', 'o']},
    {from: '', to: []},
    {from: 'true', to: [true]},
    {from: 'false', to: [false]},
    {from: undefined, to: []}
], 'array');

test('should convert to arrays with correct types', t => {
    t.is(upcast.to('true', 'array')[0], true);
    t.is(upcast.to('false', 'array')[0], false);
});

test('should convert to booleans correctly', testTo, [
    {from: ['a', 'b', 'c'], to: true},
    {from: [1, 2, 3], to: true},
    {from: [], to: false},
    {from: true, to: true},
    {from: false, to: false},
    {from: testFn, to: true},
    {from: null, to: false},
    {from: 123, to: true},
    {from: 0, to: false},
    {from: NaN, to: false},
    {from: Infinity, to: true},
    {from: {foo: 'bar'}, to: true},
    {from: 'foo', to: true},
    {from: '', to: false},
    {from: 'true', to: true},
    {from: 'false', to: false},
    {from: undefined, to: false}
], 'boolean');

test('should convert to functions correctly', testTo, [
    ['a', 'b', 'c'],
    [1, 2, 3],
    [],
    true,
    false,
    null,
    123,
    0,
    NaN,
    Infinity,
    {foo: 'bar'},
    'foo',
    '',
    'true',
    'false',
    undefined
], 'function');

test('should convert to null correctly', testTo, [
    {from: ['a', 'b', 'c'], to: null},
    {from: [1, 2, 3], to: null},
    {from: [], to: null},
    {from: true, to: null},
    {from: false, to: null},
    {from: testFn, to: null},
    {from: null, to: null},
    {from: 123, to: null},
    {from: 0, to: null},
    {from: NaN, to: null},
    {from: Infinity, to: null},
    {from: {foo: 'bar'}, to: null},
    {from: 'foo', to: null},
    {from: '', to: null},
    {from: 'true', to: null},
    {from: 'false', to: null},
    {from: undefined, to: null}
], 'null');

test('should convert to numbers correctly', testTo, [
    {from: ['a', 'b', 'c'], to: 0},
    {from: [1, 2, 3], to: 123},
    {from: [], to: 0},
    {from: true, to: 1},
    {from: false, to: 0},
    {from: testFn, to: NaN},
    {from: null, to: 0},
    {from: 123, to: 123},
    {from: 1.23, to: 1.23},
    {from: '123', to: 123},
    {from: '1.23', to: 1.23},
    {from: NaN, to: NaN},
    {from: Infinity, to: Infinity},
    {from: {foo: 'bar'}, to: NaN},
    {from: 'foo', to: 0},
    {from: '', to: 0},
    {from: 'true', to: 1},
    {from: 'false', to: 0},
    {from: undefined, to: 0}
], 'number');

/* eslint-disable no-new-object, unicorn/new-for-builtins */
test('should convert to objects correctly', testTo, [
    {from: ['a', 'b', 'c'], to: {0: 'a', 1: 'b', 2: 'c'}},
    {from: [1, 2, 3], to: {0: 1, 1: 2, 2: 3}},
    {from: [], to: []},
    {from: true, to: new Object(true)},
    {from: false, to: new Object(false)},
    {from: testFn, to: testFn},
    {from: null, to: {}},
    {from: 123, to: new Object(123)},
    {from: NaN, to: {}},
    {from: Infinity, to: new Object(Infinity)},
    {from: {foo: 'bar'}, to: {foo: 'bar'}},
    {from: 'foo', to: {0: 'f', 1: 'o', 2: 'o'}},
    {from: '', to: new Object('')},
    {from: 'true', to: Object(true)},
    {from: 'false', to: Object(false)},
    {from: undefined, to: {}}
], 'object');
/* eslint-enable */

test('should convert to strings correctly', testTo, [
    {from: ['a', 'b', 'c'], to: 'abc'},
    {from: [1, 2, 3], to: '123'},
    {from: [], to: ''},
    {from: true, to: 'true'},
    {from: false, to: 'false'},
    {from: testFn, to: 'function () {}'},
    {from: null, to: ''},
    {from: 123, to: '123'},
    {from: NaN, to: 'NaN'},
    {from: Infinity, to: 'Infinity'},
    {from: {foo: 'bar'}, to: '[object Object]'},
    {from: 'foo', to: 'foo'},
    {from: '', to: ''},
    {from: 'true', to: 'true'},
    {from: 'false', to: 'false'},
    {from: undefined, to: ''}
], 'string');

test('should convert to undefined correctly', testTo, [
    {from: ['a', 'b', 'c'], to: undefined},
    {from: [1, 2, 3], to: undefined},
    {from: [], to: undefined},
    {from: true, to: undefined},
    {from: false, to: undefined},
    {from: testFn, to: undefined},
    {from: null, to: undefined},
    {from: 123, to: undefined},
    {from: 0, to: undefined},
    {from: NaN, to: undefined},
    {from: Infinity, to: undefined},
    {from: {foo: 'bar'}, to: undefined},
    {from: 'foo', to: undefined},
    {from: '', to: undefined},
    {from: 'true', to: undefined},
    {from: 'false', to: undefined},
    {from: undefined, to: undefined}
], 'undefined');

test('should throw when called with a non-string type', t => {
    t.throws(() => {
        upcast.to('bar', 123);
    }, /invalid argument: type/i);
});

test('should resolve type aliases', t => {
    upcast.alias.seq = 'array';
    t.deepEqual(upcast.to('foo', 'seq'), ['f', 'o', 'o']);
});

test('should guard against types without casters', t => {
    t.is(upcast.to('foo', 'poo'), 'foo');
});
<|endoftext|>


<commit_before>/* global angular, expect */

'use strict';

describe('play trump', function () {
    var $scope, $rootScope, $httpBackend;

    beforeEach(angular.mock.module('ngWebSocket', 'ngWebSocketMock', 'aot.game'));

    beforeEach(inject(function (_$rootScope_, $controller) {
        $rootScope = _$rootScope_;
        $scope = $rootScope.$new();
        $controller('game', {$scope: $scope});
    }));

    beforeEach(inject(function (_$httpBackend_) {
        $httpBackend = _$httpBackend_;
        var createGameUrl = '/rest/createGame';

        var gameCreatedData = {
            players: [player1, player2],
            nextPlayer: {
                name: "Toto",
                id: "0"
            },
            possibleCardsNextPlayer: [
                {
                    name: "King",
                    color: "Red"
                }
            ],
            trumpsNextPlayer: [
                {
                    name: "Reinforcement",
                    description: "Allow the player to play one more move.",
                    mustTargetPlayer: false
                }
            ]
        };

        $httpBackend.when('GET', createGameUrl)
                .respond(gameCreatedData);
    }));

    var players, trump, currentPlayerIndex;
    var player1 = {name: 'Toto', index: 0};
    var player2 = {name: 'Tata', index: 1};

    beforeEach(function () {
        trump = {name: 'trump', mustTargetPlayer: false};
        players = [
            player1,
            player2
        ];
        currentPlayerIndex = 0;
    });

    beforeEach(function () {
        $scope.players = players;
        $scope.currentPlayer = player1;
        $scope.playTrump(trump);
    });

    it('must target player', function () {
        trump.mustTargetPlayer = true;
        expect($scope.showTargetedPlayerForTrumpSelector).toBe(false);
        $scope.playTrump(trump);
        expect($scope.trumpName).toBe(trump.name);
        expect($scope.otherPlayers).toEqual([player2]);
        expect($scope.showTargetedPlayerForTrumpSelector).toBe(true);
    });

    it('must not target player', function () {
        $scope.playTrump(trump);
        expect($scope.showTargetedPlayerForTrumpSelector).toBe(false);
        expect($scope.trumpName).toBe(trump.name);
        expect($scope.otherPlayers).toEqual([player2]);
        expect($scope.showTargetedPlayerForTrumpSelector).toBe(false);
    });

    describe('play', function () {
        var $websocketBackend;
        var playTrumpUrl = 'ws://localhost:8080/api/game/context.html';

        beforeEach(inject(function (_$websocketBackend_) {
            $websocketBackend = _$websocketBackend_;
            $websocketBackend.mock();
            $websocketBackend.expectConnect(playTrumpUrl);

            var event = data2event({rt: 'PLAY_TRUMP', play_trump: [trump]});
            $websocketBackend.expectSend(event);
        }));

        it('success', function () {
            trump.mustTargetPlayer = false;
            $scope.playTrump(trump);
            expect($scope.trumpTargetedPlayer).not.toBeDefined();
            expect($scope.showTargetedPlayerForTrumpSelector).toBe(false);
            expect($scope.activeTrumps).toEqual([trump]);
        });
    });

});
<commit_msg>test(play-trump): Update spec to match new implementation.<commit_after>/* global angular, expect */

'use strict';

describe('play trump', function () {
    var $scope, $rootScope, $httpBackend;

    beforeEach(angular.mock.module('ngWebSocket', 'ngWebSocketMock', 'aot.game'));

    beforeEach(inject(function (_$rootScope_, $controller) {
        $rootScope = _$rootScope_;
        $scope = $rootScope.$new();
        $controller('game', {$scope: $scope});
    }));

    beforeEach(inject(function (_$httpBackend_) {
        $httpBackend = _$httpBackend_;
        var createGameUrl = '/rest/createGame';

        var gameCreatedData = {
            players: [player1, player2],
            nextPlayer: {
                name: "Toto",
                id: "0"
            },
            possibleCardsNextPlayer: [
                {
                    name: "King",
                    color: "Red"
                }
            ],
            trumpsNextPlayer: [
                {
                    name: "Reinforcement",
                    description: "Allow the player to play one more move.",
                    mustTargetPlayer: false
                }
            ]
        };

        $httpBackend.when('GET', createGameUrl)
                .respond(gameCreatedData);
    }));

    var players, trump, currentPlayerIndex;
    var player1 = {name: 'Toto', index: 0};
    var player2 = {name: 'Tata', index: 1};

    beforeEach(function () {
        trump = {name: 'trump', mustTargetPlayer: false};
        players = [
            player1,
            player2
        ];
        currentPlayerIndex = 0;
    });

    beforeEach(function () {
        $scope.players = players;
        $scope.currentPlayer = player1;
        $scope.playTrump(trump);
    });

    it('must target player', function () {
        trump.mustTargetPlayer = true;
        expect($scope.showTargetedPlayerForTrumpSelector).toBe(false);
        $scope.playTrump(trump);
        expect($scope.trumpName).toBe(trump.name);
        expect($scope.otherPlayers).toEqual([player2]);
        expect($scope.showTargetedPlayerForTrumpSelector).toBe(true);
    });

    it('must not target player', function () {
        $scope.playTrump(trump);
        expect($scope.showTargetedPlayerForTrumpSelector).toBe(false);
        expect($scope.trumpName).toBe(trump.name);
        expect($scope.otherPlayers).toEqual([player2]);
        expect($scope.showTargetedPlayerForTrumpSelector).toBe(false);
    });

    describe('play', function () {
        var $websocketBackend;
        var playTrumpUrl = 'ws://localhost:8080/api/game/context.html';

        beforeEach(inject(function (_$websocketBackend_) {
            $websocketBackend = _$websocketBackend_;
            $websocketBackend.mock();
            $websocketBackend.expectConnect(playTrumpUrl);

            var event = data2event({rt: 'PLAY_TRUMP', play_trump: [trump]});
            $websocketBackend.expectSend(event);
        }));

        it('success', function () {
            trump.mustTargetPlayer = false;
            $scope.playTrump(trump);
            expect($scope.trumpTargetedPlayer.index).toBe(-1);
            expect($scope.showTargetedPlayerForTrumpSelector).toBe(false);
            expect($scope.activeTrumps).toEqual([trump]);
        });
    });

});
<|endoftext|>


<commit_before>/* this is kinda still a work in progress */
/* head nod to Ununoctium118 who wrote the original GM script for finding servers */
var modBlocking = true;
var nodeDiv = document.createElement("div");

nodeDiv.id = "includedContent";
nodeDiv.style.width = "320px"
nodeDiv.style.backgroundColor = "#000000";
nodeDiv.style.zIndex = 9999999999;
nodeDiv.style.position = "center";
nodeDiv.style.padding = "10px";
nodeDiv.style.left = "-225px";
nodeDiv.style.borderRadius = "10px";
nodeDiv.style.color = "#dddddd";
nodeDiv.innerHTML = "electronoob's evergreen server script for team play. Website.
";
nodeDiv.innerHTML += "
There is a new Mumble chat here.";
nodeDiv.innerHTML += "connections steps";
nodeDiv.innerHTML += "\

\

1: get ip address from friend.
\

2: put it in text box below.
\

3: press the swirly icon next to it.
\

Note: There are many worlds on any given IP address so you must compare the leaderboard with your friends.
\

\
\
";

jQuery('#region').parent().get(0).appendChild(document.createElement("br"));
jQuery('#region').parent().get(0).appendChild(nodeDiv);

var selector = jQuery('#region');
var playBtn = jQuery('#playBtn');
var nodeInput = document.createElement("input");
var nodeSpan = document.createElement("span");
var nodeBr = document.createElement("br");
nodeSpan.className = "glyphicon glyphicon-refresh";
nodeSpan.style.fontSize = "1.5em";
nodeSpan.style.cssFloat = "left";
nodeSpan.style.paddingTop = "5px";
nodeSpan.style.paddingLeft = "15px";
nodeSpan.addEventListener("click", function (e) {
    if (modBlocking == false) {
                      console.log ("clicked refresh");
                      jQuery('#region').val("EU-London");
                      jQuery('#region').change();
                      jQuery('#region').val("SG-Singapore");
                      jQuery('#region').change();
		      jQuery('#region').hide(200);
		      jQuery(this).fadeOut(100).fadeIn(100);
    }
});
nodeInput.className = "form-control";
nodeInput.id = "iphack"
nodeInput.style.width = "85%";
nodeInput.style.cssFloat = "left";
nodeInput.style.cssClear = "right";

nodeInput.placeholder = "Alternative server ip:port here.";

jQuery(playBtn).parent().get(0).appendChild(nodeBr);
jQuery(playBtn).parent().get(0).appendChild(nodeInput);
jQuery(playBtn).parent().get(0).appendChild(nodeSpan);

jQuery('#iphack').change(function() {
    if (jQuery('#iphack').val() == "") {
        modBlocking = true;
    }
    modBlocking = false;
});

jQuery('#playBtn').off();
$('.btn-needs-server').prop('disabled', false);
jQuery('#playBtn').click(function() {
    setNick(document.getElementById('nick').value);
    return false;
});
jQuery('#region').off();
jQuery('#region').change(function() {
    jQuery.ajax("http://m.agar.io/", {
        error: function() {},
        success: function(a) {
            a = a.split("\n");
            if (modBlocking == true) {
                jQuery('#includedContent').html("Here is the IP address of the server you are connected to currently, pass it to your friends for team playing.
" + a[0] + "
");
            } else {
                jQuery('#includedContent').html("
Connecting to " + jQuery('#iphack').val() + "

Check leaderboard with your friend to ensure you are both on the exact world on the same server.

If you cannot see the same people in the leaderboard as your friend, randomly select a different region and it will try another world on the same server.");
            }
        },
        dataType: "text",
        method: "POST",
        cache: !1,
        crossDomain: !0,
        data: jQuery('#region').val()
    });
});
(function(window) {
    var WebSocket_original = window.WebSocket;
    window.WebSocket_original = WebSocket_original;
    window.WebSocket = function(data) {
        if (modBlocking == true) {
            newWebSocket = new window.WebSocket_original(data);
            return newWebSocket;
        } else {
            console.log("HAXXED: connecting to " + jQuery('#iphack').val() + "(ignoring: " + data + ")");
            newWebSocket = new window.WebSocket_original("ws://" + jQuery('#iphack').val());
            return newWebSocket;
        }
    };
})(window);

<commit_msg>Update mods.js<commit_after>/* this is kinda still a work in progress */
/* head nod to Ununoctium118 who wrote the original GM script for finding servers */
var modBlocking = true;
var nodeDiv = document.createElement("div");

nodeDiv.id = "includedContent";
nodeDiv.style.width = "320px"
nodeDiv.style.backgroundColor = "#000000";
nodeDiv.style.zIndex = 9999999999;
nodeDiv.style.position = "center";
nodeDiv.style.padding = "10px";
nodeDiv.style.left = "-225px";
nodeDiv.style.borderRadius = "10px";
nodeDiv.style.color = "#dddddd";
nodeDiv.innerHTML = "Agariomods' evergreen server script for team play. Version 1.1 Agariomods.com.
";
nodeDiv.innerHTML += "
There is a new Mumble chat here.";
nodeDiv.innerHTML += "connections steps";
nodeDiv.innerHTML += "\

\

1: Get ip address from friend.
\

2: Put it in text box below.
\

3: Press the swirly icon next to it.
\

Note: There are many worlds on any given IP address so you must compare the leaderboard with your friends.
\

\
\
";

jQuery('#region').parent().get(0).appendChild(document.createElement("br"));
jQuery('#region').parent().get(0).appendChild(nodeDiv);

var selector = jQuery('#region');
var playBtn = jQuery('#playBtn');
var nodeInput = document.createElement("input");
var nodeSpan = document.createElement("span");
var nodeBr = document.createElement("br");
nodeSpan.className = "glyphicon glyphicon-refresh";
nodeSpan.style.fontSize = "1.5em";
nodeSpan.style.cssFloat = "left";
nodeSpan.style.paddingTop = "5px";
nodeSpan.style.paddingLeft = "15px";
nodeSpan.addEventListener("click", function (e) {
    if (modBlocking == false) {
                      console.log ("clicked refresh");
                      jQuery('#region').val("EU-London");
                      jQuery('#region').change();
                      jQuery('#region').val("SG-Singapore");
                      jQuery('#region').change();
		      jQuery('#region').hide(200);
		      jQuery(this).fadeOut(100).fadeIn(100);
    }
});
nodeInput.className = "form-control";
nodeInput.id = "iphack"
nodeInput.style.width = "85%";
nodeInput.style.cssFloat = "left";
nodeInput.style.cssClear = "right";

nodeInput.placeholder = "Alternative server ip:port here.";

jQuery(playBtn).parent().get(0).appendChild(nodeBr);
jQuery(playBtn).parent().get(0).appendChild(nodeInput);
jQuery(playBtn).parent().get(0).appendChild(nodeSpan);

jQuery('#iphack').change(function() {
    if (jQuery('#iphack').val() == "") {
        modBlocking = true;
    }
    modBlocking = false;
});

jQuery('#playBtn').off();
$('.btn-needs-server').prop('disabled', false);
jQuery('#playBtn').click(function() {
    setNick(document.getElementById('nick').value);
    return false;
});
jQuery('#region').off();
jQuery('#region').change(function() {
    jQuery.ajax("http://m.agar.io/", {
        error: function() {},
        success: function(a) {
            a = a.split("\n");
            if (modBlocking == true) {
                jQuery('#includedContent').html("Here is the IP address of the server you are connected to currently, pass it to your friends for team playing.
" + a[0] + "
");
            } else {
                jQuery('#includedContent').html("
Connecting to " + jQuery('#iphack').val() + "

Check leaderboard with your friend to ensure you are both on the exact world on the same server.

If you cannot see the same people in the leaderboard as your friend, randomly select a different region and it will try another world on the same server.");
            }
        },
        dataType: "text",
        method: "POST",
        cache: !1,
        crossDomain: !0,
        data: jQuery('#region').val()
    });
});
(function(window) {
    var WebSocket_original = window.WebSocket;
    window.WebSocket_original = WebSocket_original;
    window.WebSocket = function(data) {
        if (modBlocking == true) {
            newWebSocket = new window.WebSocket_original(data);
            return newWebSocket;
        } else {
            console.log("HAXXED: connecting to " + jQuery('#iphack').val() + "(ignoring: " + data + ")");
            newWebSocket = new window.WebSocket_original("ws://" + jQuery('#iphack').val());
            return newWebSocket;
        }
    };
})(window);

<|endoftext|>


<commit_before>/** tipiX - TIme PIcture eXplorer
 *
 * Copyright (c) 2013 TIPIX <adalca@mit.edu>
 *
 * tipiX is licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * See LICENSE file for more information
 *
 * Author: Adrian V. Dalca, http://www.mit.edu/~adalca/
 */

/** Launch display of a set given a set choice
 *
 * @param choice - String - a set choice (see cases for options).
 * @returns {Array} - 1d or 2d pictureBox objects
 */
function launchDisplay(choice) {
	switch (choice) {
		case "boston4day":
			loadObj = loadBoston4Day();
			break;
		case "boston5day":
			loadObj = loadBoston5Day();
			break;
		case "bostonStorm":
			loadObj = loadBostonStorm();
			break;
		case "vermontDrive":
			loadObj = loadVermontDrive();
			break;
		case "lakePlacidDrive":
			loadObj = loadLakePlacidDrive();
			break;
		case "emerald":
			loadObj = loadEmerald();
			break;
		case "userSet":
			loadObj = loadUserSet();
			break;
		default:
			alert('Not a valid case');
			break;
	}

	// get the images according to the sources.
	pictureBoxes = loadImages(loadObj);

	// canvas should be turned on
	canvasOn = true;

	var canvas = document.getElementById(DRAW_CANVAS_NAME); // main canvas
	canvas.getContext('2d').clearRect(0,0,canvas.width,canvas.height);
	drawLogo();

	// close nav
	nav(currentTab);

	// return the images
	return pictureBoxes;
}

function loadBoston4Day() {
	loadObj.nDims = 2;
	loadObj.xBins = 5;
	loadObj.yBins = 24;
	loadObj.fileName = CORE_SET_PATH + '/imageSets/boston4day/average_img_%d_%d.jpg';
	return loadObj;
}

function loadBoston5Day() {
	loadObj.nDims = 2;
	loadObj.xBins = 5;
	loadObj.yBins = 24;
	loadObj.fileName = CORE_SET_PATH + '/imageSets/boston5day/l_average_img_%d_%d.jpg';
	return loadObj;
}

function loadBostonStorm() {
	loadObj.nDims = 1;
	loadObj.xBins = 30;
	loadObj.fileName = CORE_SET_PATH + '/imageSets/bostonStorm/l_average_img_%d.jpg';
	return loadObj;
}

function loadVermontDrive() {
	loadObj.nDims = 1;
	loadObj.xBins = 60;
	loadObj.fileName = CORE_SET_PATH + '/imageSets/vermontDrive/l_average_img_%d.jpg';
	return loadObj;
}

function loadLakePlacidDrive() {
	loadObj.nDims = 1;
	loadObj.xBins = 26;
	loadObj.fileName = CORE_SET_PATH + '/imageSets/lakePlacidDrive/l_average_img_%d.jpg';
	return loadObj;
}

function loadEmerald() {
	loadObj.nDims = 1;
	loadObj.xBins = 337;
	loadObj.fileName = CORE_SET_PATH + '/imageSets/emerald/img (%d).jpg';
	return loadObj;
}

function loadUserSet() {
	var oForm = document.getElementById('userSet');

	var radios = document.getElementsByName('nDims');
	for (var i = 0, length = radios.length; i < length; i++) {
		if (radios[i].checked) {
			loadObj.nDims = radios[i].value;
		}
	}

	loadObj.xBins = parseInt(oForm.elements['xBins'].value);
	if (loadObj.nDims == 2) {
		loadObj.yBins = parseInt(oForm.elements['yBins'].value);
	}
	loadObj.fileName = oForm.elements['filename'].value;
	return loadObj;
}

/******************************************************************************
 * Execution
 *****************************************************************************/

// original settings and global variables
var DRAW_CANVAS_NAME = 'mainDisplay';
var canvasOn = false;
var currentX = 0;
var currentY = 0;
var pictureBoxes = [];
var startTime = 0;
var loadObj = new Object();
var curPictureBox = null;
var currentTab = 'about';
var currentTabState = true;
var CORE_SET_PATH = 'http://www.mit.edu/~adalca/tipiX';
var logoImage;
var lockx = false;
var locky = false;

// key presses
$(document).keyup(function(e) {
  if (e.keyCode == 88) {
  	lockx = !lockx;
	}   // x
  if (e.keyCode == 89) {
  	locky = !locky;
	}   // x

});

// canvas and listener
var canvas = document.getElementById(DRAW_CANVAS_NAME); // main canvas
canvas.addEventListener('mousemove', function(evt) {
	if (canvasOn) {
		var mousePos = getMousePos(canvas, evt);
		drawImageAtPosition(mousePos);
	}
}, false);
<commit_msg>added esc key functionality<commit_after>/** tipiX - TIme PIcture eXplorer
 *
 * Copyright (c) 2013 TIPIX <adalca@mit.edu>
 *
 * tipiX is licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * See LICENSE file for more information
 *
 * Author: Adrian V. Dalca, http://www.mit.edu/~adalca/
 */

/** Launch display of a set given a set choice
 *
 * @param choice - String - a set choice (see cases for options).
 * @returns {Array} - 1d or 2d pictureBox objects
 */
function launchDisplay(choice) {
	switch (choice) {
		case "boston4day":
			loadObj = loadBoston4Day();
			break;
		case "boston5day":
			loadObj = loadBoston5Day();
			break;
		case "bostonStorm":
			loadObj = loadBostonStorm();
			break;
		case "vermontDrive":
			loadObj = loadVermontDrive();
			break;
		case "lakePlacidDrive":
			loadObj = loadLakePlacidDrive();
			break;
		case "emerald":
			loadObj = loadEmerald();
			break;
		case "userSet":
			loadObj = loadUserSet();
			break;
		default:
			alert('Not a valid case');
			break;
	}

	// get the images according to the sources.
	pictureBoxes = loadImages(loadObj);

	// canvas should be turned on
	canvasOn = true;

	var canvas = document.getElementById(DRAW_CANVAS_NAME); // main canvas
	canvas.getContext('2d').clearRect(0,0,canvas.width,canvas.height);
	drawLogo();

	// close nav
	nav(currentTab);

	// return the images
	return pictureBoxes;
}

function loadBoston4Day() {
	loadObj.nDims = 2;
	loadObj.xBins = 5;
	loadObj.yBins = 24;
	loadObj.fileName = CORE_SET_PATH + '/imageSets/boston4day/average_img_%d_%d.jpg';
	return loadObj;
}

function loadBoston5Day() {
	loadObj.nDims = 2;
	loadObj.xBins = 5;
	loadObj.yBins = 24;
	loadObj.fileName = CORE_SET_PATH + '/imageSets/boston5day/l_average_img_%d_%d.jpg';
	return loadObj;
}

function loadBostonStorm() {
	loadObj.nDims = 1;
	loadObj.xBins = 30;
	loadObj.fileName = CORE_SET_PATH + '/imageSets/bostonStorm/l_average_img_%d.jpg';
	return loadObj;
}

function loadVermontDrive() {
	loadObj.nDims = 1;
	loadObj.xBins = 60;
	loadObj.fileName = CORE_SET_PATH + '/imageSets/vermontDrive/l_average_img_%d.jpg';
	return loadObj;
}

function loadLakePlacidDrive() {
	loadObj.nDims = 1;
	loadObj.xBins = 26;
	loadObj.fileName = CORE_SET_PATH + '/imageSets/lakePlacidDrive/l_average_img_%d.jpg';
	return loadObj;
}

function loadEmerald() {
	loadObj.nDims = 1;
	loadObj.xBins = 337;
	loadObj.fileName = CORE_SET_PATH + '/imageSets/emerald/img (%d).jpg';
	return loadObj;
}

function loadUserSet() {
	var oForm = document.getElementById('userSet');

	var radios = document.getElementsByName('nDims');
	for (var i = 0, length = radios.length; i < length; i++) {
		if (radios[i].checked) {
			loadObj.nDims = radios[i].value;
		}
	}

	loadObj.xBins = parseInt(oForm.elements['xBins'].value);
	if (loadObj.nDims == 2) {
		loadObj.yBins = parseInt(oForm.elements['yBins'].value);
	}
	loadObj.fileName = oForm.elements['filename'].value;
	return loadObj;
}

/******************************************************************************
 * Execution
 *****************************************************************************/

// original settings and global variables
var DRAW_CANVAS_NAME = 'mainDisplay';
var canvasOn = false;
var currentX = 0;
var currentY = 0;
var pictureBoxes = [];
var startTime = 0;
var loadObj = new Object();
var curPictureBox = null;
var currentTab = 'about';
var currentTabState = true;
var CORE_SET_PATH = 'http://www.mit.edu/~adalca/tipiX';
var logoImage;
var lockx = false;
var locky = false;

// key presses
$(document).keyup(function(e) {
  if (e.keyCode == 88) {
  	lockx = !lockx;
	}   // x
  if (e.keyCode == 89) {
  	locky = !locky;
	}   // x
  if (e.keyCode == 27) {
  	lockx = false;
  	locky = false;
	}   // x

});

// canvas and listener
var canvas = document.getElementById(DRAW_CANVAS_NAME); // main canvas
canvas.addEventListener('mousemove', function(evt) {
	if (canvasOn) {
		var mousePos = getMousePos(canvas, evt);
		drawImageAtPosition(mousePos);
	}
}, false);
<|endoftext|>


<commit_before>/*
	author: bartek
	date: 23:49 19-08-2015
*/

function ChatCreator(){
	this.$box = document.querySelector('#min-chat > main');

	this.stop = false;
	this.notifyTimeout = null;
	this.defaultTitle = document.title;
	this.toSeen = false;
	this.url = 'http://forum.miroslawzelent.pl/chat';

	this.userID = null;
	this.lastID = 0;
	this.users = new Map();
	this.messages = new Set();

	this.commands = new Set([
		'/online'
		,'/clear'
		,'/lastid' //dev
	]);
}

ChatCreator.prototype.bindDOM = function(e){
	document.getElementById('chat-input').addEventListener('keyup', function(e){
		if(e.which != 13 || document.getElementById('chat-input').value.trim().length < 2 || e.shiftKey)return;
		this.sendMessage(document.getElementById('chat-input').value.trim());
	}.bind(this));
};

ChatCreator.prototype.systemMessage = function(val){
	this.updateMessages([{
		postid: 0 - Math.round(Math.random()*1000),
		userid: -1,
		username: 'System',
		posted: new Date().toISOString().substr(0, 19).split('T').join(' '),
		message: val
	}]);
};

ChatCreator.prototype.commandParse = function(val){
	if(!this.commands.has(val))return false;

	switch(val){
		case '/online':
			(function(){
				var a = '';
				for(var i of this.users.values()){
					a += (a===''?'':', ') + (i.idle?'[i] ':'') + i.name;
				}

				this.systemMessage('online: ' + a);
			}).apply(this);
			break;

		case '/clear':
			this.$box.innerHTML = '';
			break;

		case '/lastid':
			this.systemMessage('lastID: ' + this.lastID);
			break;
	}

	return true;
};

ChatCreator.prototype.updateMessages = function(m){
	m = m.reverse();
	m.forEach(function(i){
		if(this.messages.has(Number(i.postid)))return;

		this.messages.add(Number(i.postid));

		if(Number(i.postid) > this.lastID)this.lastID = Number(i.postid);

		this.$box.appendChild(new Message(i).getDOM());
		this.$box.scrollTop = 99999999999;
		//notify?
	}.bind(this));
};

ChatCreator.prototype.updateUsers = function(u){
	this.users.clear();

	u.forEach(function(o){
		this.users.set(Number(o.userid), {
			name: o.username
			,idle: (o.idle==="1")
			,level: Number(o.level)
			,kicked: Number(o.kicked) //or bool maybe?
			,kickable: Number(o.kickable) //the same? xD
		});
	}.bind(this));
};

ChatCreator.prototype.sendMessage = function(val){

	var chatInput = document.getElementById('chat-input');
	chatInput.value = '';
	chatInput.setAttribute('disabled', 'disabled');

	if(this.commandParse.bind(this)(val))return;

	$.post(this.url, {
		ajax_add_message: val
		,ajax_add_lastid: this.lastID
	}).done(function(res){
		if(res.indexOf("Nie jesteś już zalogowany.") > -1){
			this.stop = true;
			return;
		}

		res = res.split('\n');

		if(!this.userID)
			this.userID = Number(res[1]);

		this.updateMessages([JSON.parse(res[2])]);
		chatInput.removeAttribute('disabled');
	}.bind(this)).fail(function(){
		console.warn('sendMessage fail');
		chatInput.removeAttribute('disabled');
	});
};

ChatCreator.prototype.getMessages = function(){
	if(this.stop)return;

	$.post(this.url, {
		ajax_get_messages: this.lastID
	}).done(function(res){
		if(res.indexOf("Nie jesteś już zalogowany.") > -1){
			this.stop = true;
			return;
		}

		res = res.split('\n');

		if(!this.userID)
			this.userID = Number(res[1]);

		this.updateMessages(JSON.parse(res[2]));
		this.updateUsers(JSON.parse(res[3]));
	}.bind(this)).fail(function(){
		console.warn('getMessages fail');
	});

	setTimeout(this.getMessages.bind(this), 1500);
};

document.addEventListener('DOMContentLoaded', function(){
	window.chat = new ChatCreator();
	chat.bindDOM();
	chat.getMessages();
});
<commit_msg>Disable attr set if not command<commit_after>/*
	author: bartek
	date: 23:49 19-08-2015
*/

function ChatCreator(){
	this.$box = document.querySelector('#min-chat > main');

	this.stop = false;
	this.notifyTimeout = null;
	this.defaultTitle = document.title;
	this.toSeen = false;
	this.url = 'http://forum.miroslawzelent.pl/chat';

	this.userID = null;
	this.lastID = 0;
	this.users = new Map();
	this.messages = new Set();

	this.commands = new Set([
		'/online'
		,'/clear'
		,'/lastid' //dev
	]);
}

ChatCreator.prototype.bindDOM = function(e){
	document.getElementById('chat-input').addEventListener('keyup', function(e){
		if(e.which != 13 || document.getElementById('chat-input').value.trim().length < 2 || e.shiftKey)return;
		this.sendMessage(document.getElementById('chat-input').value.trim());
	}.bind(this));
};

ChatCreator.prototype.systemMessage = function(val){
	this.updateMessages([{
		postid: 0 - Math.round(Math.random()*1000),
		userid: -1,
		username: 'System',
		posted: new Date().toISOString().substr(0, 19).split('T').join(' '),
		message: val
	}]);
};

ChatCreator.prototype.commandParse = function(val){
	if(!this.commands.has(val))return false;

	switch(val){
		case '/online':
			(function(){
				var a = '';
				for(var i of this.users.values()){
					a += (a===''?'':', ') + (i.idle?'[i] ':'') + i.name;
				}

				this.systemMessage('online: ' + a);
			}).apply(this);
			break;

		case '/clear':
			this.$box.innerHTML = '';
			break;

		case '/lastid':
			this.systemMessage('lastID: ' + this.lastID);
			break;
	}

	return true;
};

ChatCreator.prototype.updateMessages = function(m){
	m = m.reverse();
	m.forEach(function(i){
		if(this.messages.has(Number(i.postid)))return;

		this.messages.add(Number(i.postid));

		if(Number(i.postid) > this.lastID)this.lastID = Number(i.postid);

		this.$box.appendChild(new Message(i).getDOM());
		this.$box.scrollTop = 99999999999;
		//notify?
	}.bind(this));
};

ChatCreator.prototype.updateUsers = function(u){
	this.users.clear();

	u.forEach(function(o){
		this.users.set(Number(o.userid), {
			name: o.username
			,idle: (o.idle==="1")
			,level: Number(o.level)
			,kicked: Number(o.kicked) //or bool maybe?
			,kickable: Number(o.kickable) //the same? xD
		});
	}.bind(this));
};

ChatCreator.prototype.sendMessage = function(val){

	var chatInput = document.getElementById('chat-input');
	chatInput.value = '';

	if(this.commandParse.bind(this)(val))return;

	chatInput.setAttribute('disabled', 'disabled');
	$.post(this.url, {
		ajax_add_message: val
		,ajax_add_lastid: this.lastID
	}).done(function(res){
		if(res.indexOf("Nie jesteś już zalogowany.") > -1){
			this.stop = true;
			return;
		}

		res = res.split('\n');

		if(!this.userID)
			this.userID = Number(res[1]);

		this.updateMessages([JSON.parse(res[2])]);
		chatInput.removeAttribute('disabled');
	}.bind(this)).fail(function(){
		console.warn('sendMessage fail');
		chatInput.removeAttribute('disabled');
	});
};

ChatCreator.prototype.getMessages = function(){
	if(this.stop)return;

	$.post(this.url, {
		ajax_get_messages: this.lastID
	}).done(function(res){
		if(res.indexOf("Nie jesteś już zalogowany.") > -1){
			this.stop = true;
			return;
		}

		res = res.split('\n');

		if(!this.userID)
			this.userID = Number(res[1]);

		this.updateMessages(JSON.parse(res[2]));
		this.updateUsers(JSON.parse(res[3]));
	}.bind(this)).fail(function(){
		console.warn('getMessages fail');
	});

	setTimeout(this.getMessages.bind(this), 1500);
};

document.addEventListener('DOMContentLoaded', function(){
	window.chat = new ChatCreator();
	chat.bindDOM();
	chat.getMessages();
});
<|endoftext|>