<commit_before>// Generated by CoffeeScript 1.4.0
(function() {
  "use strict";
  var CTCPHandler, exports, _ref,
    __slice = [].slice;

  var exports = (_ref = window.irc) != null ? _ref : window.irc = {};

  /*
   * Handles CTCP requests such as VERSION, PING, etc.
  */

  CTCPHandler = (function() {

    CTCPHandler.DELIMITER = '\u0001';

    function CTCPHandler() {
      /*
           * TODO: Respond with this message when an unknown query is seen.
      */
      this._error = "" + CTCPHandler.DELIMITER + "ERRMSG" + CTCPHandler.DELIMITER;
    }

    CTCPHandler.prototype.isCTCPRequest = function(msg) {
      if (!/\u0001[\w\s]*\u0001/.test(msg)) {
        return false;
      }
      return this.getResponses(msg).length > 0;
    };

    CTCPHandler.prototype.getReadableName = function(msg) {
      var args, type, _ref1;
      _ref1 = this._parseMessage(msg), type = _ref1[0], args = _ref1[1];
      return type;
    };

    CTCPHandler.prototype.getResponses = function(msg) {
      var args, response, responses, type, _i, _len, _ref1, _results;
      _ref1 = this._parseMessage(msg), type = _ref1[0], args = _ref1[1];
      responses = this._getResponseText(type, args);
      _results = [];
      for (_i = 0, _len = responses.length; _i < _len; _i++) {
        response = responses[_i];
        _results.push(this._createCTCPResponse(type, response));
      }
      return _results;
    };

    /*
       * Parses the type and arguments from a CTCP request.
       * @param {string} msg CTCP message in the format: '\0001TYPE ARG1 ARG2\0001'.
       *     Note: \0001 is a single character.
       * @return {string, Array.<string>} Returns the type and the args.
    */

    CTCPHandler.prototype._parseMessage = function(msg) {
      var args, type, _ref1;
      msg = msg.slice(1, +(msg.length - 2) + 1 || 9e9);
      _ref1 = msg.split(' '), type = _ref1[0], args = 2 <= _ref1.length ? __slice.call(_ref1, 1) : [];
      return [type, args];
    };

    /*
       * @return {Array.<string>} Returns the unformatted responses to a CTCP
       *     request.
    */

    CTCPHandler.prototype._getResponseText = function(type, args) {
      /*
           * TODO support the o ther types found here:
           * http://www.irchelp.org/irchelp/rfc/ctcpspec.html
      */

      var environment, name;
      switch (type) {
        case 'VERSION':
          name = 'CIRC';
          environment = 'Chrome';
          return [' ' + [name, irc.VERSION, environment].join(' ')];
        case 'SOURCE':
          return [''];
        case 'PING':
          return [' ' + args[0]];
        default:
          return [];
      }
    };

    /*
       * @return {string} Returns a correctly formatted response to a CTCP request.
    */

    CTCPHandler.prototype._createCTCPResponse = function(type, response) {
      return "" + CTCPHandler.DELIMITER + type + response + CTCPHandler.DELIMITER;
    };

    return CTCPHandler;

  })();

  exports.CTCPHandler = CTCPHandler;

}).call(this);
<commit_msg>Provide correct CTCP TIME reply, re: http://redd.it/28qqkn<commit_after>// Generated by CoffeeScript 1.4.0
(function() {
  "use strict";
  var CTCPHandler, exports, _ref,
    __slice = [].slice;

  var exports = (_ref = window.irc) != null ? _ref : window.irc = {};

  /*
   * Handles CTCP requests such as VERSION, PING, etc.
  */

  CTCPHandler = (function() {

    CTCPHandler.DELIMITER = '\u0001';

    function CTCPHandler() {
      /*
           * TODO: Respond with this message when an unknown query is seen.
      */
      this._error = "" + CTCPHandler.DELIMITER + "ERRMSG" + CTCPHandler.DELIMITER;
    }

    CTCPHandler.prototype.isCTCPRequest = function(msg) {
      if (!/\u0001[\w\s]*\u0001/.test(msg)) {
        return false;
      }
      return this.getResponses(msg).length > 0;
    };

    CTCPHandler.prototype.getReadableName = function(msg) {
      var args, type, _ref1;
      _ref1 = this._parseMessage(msg), type = _ref1[0], args = _ref1[1];
      return type;
    };

    CTCPHandler.prototype.getResponses = function(msg) {
      var args, response, responses, type, _i, _len, _ref1, _results;
      _ref1 = this._parseMessage(msg), type = _ref1[0], args = _ref1[1];
      responses = this._getResponseText(type, args);
      _results = [];
      for (_i = 0, _len = responses.length; _i < _len; _i++) {
        response = responses[_i];
        _results.push(this._createCTCPResponse(type, response));
      }
      return _results;
    };

    /*
       * Parses the type and arguments from a CTCP request.
       * @param {string} msg CTCP message in the format: '\0001TYPE ARG1 ARG2\0001'.
       *     Note: \0001 is a single character.
       * @return {string, Array.<string>} Returns the type and the args.
    */

    CTCPHandler.prototype._parseMessage = function(msg) {
      var args, type, _ref1;
      msg = msg.slice(1, +(msg.length - 2) + 1 || 9e9);
      _ref1 = msg.split(' '), type = _ref1[0], args = 2 <= _ref1.length ? __slice.call(_ref1, 1) : [];
      return [type, args];
    };

    /*
       * @return {Array.<string>} Returns the unformatted responses to a CTCP
       *     request.
    */

    CTCPHandler.prototype._getResponseText = function(type, args) {
      /*
           * TODO support the o ther types found here:
           * http://www.irchelp.org/irchelp/rfc/ctcpspec.html
      */

      var environment, name;
      switch (type) {
        case 'VERSION':
          name = 'CIRC';
          environment = 'Chrome';
          return [' ' + [name, irc.VERSION, environment].join(' ')];
        case 'SOURCE':
          return [''];
        case 'PING':
          return [' ' + args[0]];
        case 'TIME':
          var d = new Date();
          return [' ' + d.toUTCString()];
        default:
          return [];
      }
    };

    /*
       * @return {string} Returns a correctly formatted response to a CTCP request.
    */

    CTCPHandler.prototype._createCTCPResponse = function(type, response) {
      return "" + CTCPHandler.DELIMITER + type + response + CTCPHandler.DELIMITER;
    };

    return CTCPHandler;

  })();

  exports.CTCPHandler = CTCPHandler;

}).call(this);
<|endoftext|>


<commit_before>describe('Rest Proxy in Model', function() {
    it('should save entity', function() {
        var owner = Ext.create('Test.TestBundle.Entity.CarOwner', {
            name: 'James'
        });
        var runned = false;
        runs(function() {
            owner.save({
                callback: function(record, operation, success) {
                    runned = true;
                }
            });
        });
        waitsFor(function() {
            return runned;
        });
        runs(function() {
            expect(owner.get('name')).toBe('James');
        });
    });
    it('should save existing entity with new hasMany association', function() {
        var owner = Ext.create('Test.TestBundle.Entity.CarOwner', {
            name: 'James'
        });
        var runned = false;
        runs(function() {
            owner.save({
                callback: function(record, operation, success) {
                    owner.cars().add({
                        name: 'Ford',
                        plateNumber: 'AA1234',
                        password: 'xx'
                    }, {
                        name: 'BMW',
                        plateNumber: 'ASF87654',
                        password: 'xx'
                    });
                    owner.cars().sync({
                        callback: function() {
                            Test.TestBundle.Entity.CarOwner.load(owner.getId(), {
                                callback: function(record) {
                                    owner = record;
                                    runned = true;
                                }
                            });
                        }
                    });
                }
            });
        });
        waitsFor(function() {
            return runned;
        });
        runs(function() {
            expect(owner).not.toBeNull();
            expect(owner.cars().count()).toBe(2);
            expect(owner.cars().first().get('name')).toBe('Ford');
            expect(owner.cars().first().getCarOwner()).toBe(owner);
        });
    });
    it('should save existing entity with existing hasMany association', function() {
        var owner = Ext.create('Test.TestBundle.Entity.CarOwner', {
            name: 'James'
        });
        var runned = false;
        runs(function() {
            owner.save({
                callback: function(record, operation, success) {
                    var car = Ext.create('Test.TestBundle.Entity.Car', {
                        name: 'Ford',
                        plateNumber: 'AA1234',
                        password: 'xx'
                    });
                    car.save({
                        callback: function(record) {
                            owner.cars().add(record);
                            owner.cars().sync({
                                callback: function() {
                                    owner.cars().first().getCarOwner({
                                        callback: function() {
                                            runned = true;
                                        }
                                    });
                                }
                            });
                        }
                    });
                }
            });
        });
        waitsFor(function() {
            return runned;
        });
        runs(function() {
            expect(owner).not.toBeNull();
            expect(owner.cars().count()).toBe(1);
            expect(owner.cars().first().get('name')).toBe('Ford');
            expect(owner.cars().first().getCarOwner().getData()).toEqual(owner.getData());
        });
    });
    it('should save existing entity with existing belongTo association', function() {
        var car = Ext.create('Test.TestBundle.Entity.Car', {
            name: 'Ford',
            plateNumber: 'AA1234',
            password: 'xx'
        });
        var runned = false;
        runs(function() {
            car.save({
                callback: function(record) {
                    var owner = Ext.create('Test.TestBundle.Entity.CarOwner', {
                        name: 'James'
                    });
                    owner.save({
                        callback: function(record) {
                            car.setCarOwner(record, {
                                callback: function() {
                                    runned = true;
                                }
                            });
                        }
                    });
                }
            });
        });
        waitsFor(function() {
            return runned;
        });
        runs(function() {
            expect(car.getCarOwner()).not.toBeNull();
            expect(car.getCarOwner().getId()).toBeGreaterThan(0);
        });
    });
});<commit_msg>Added additional test case.<commit_after>describe('Rest Proxy in Model', function() {
    it('should save entity', function() {
        var owner = Ext.create('Test.TestBundle.Entity.CarOwner', {
            name: 'James'
        });
        var runned = false;
        runs(function() {
            owner.save({
                callback: function(record, operation, success) {
                    Test.TestBundle.Entity.CarOwner.load(record.getId(), {
                        callback: function(record) {
                            owner = record;
                            runned = true;
                        }
                    });
                }
            });
        });
        waitsFor(function() {
            return runned;
        });
        runs(function() {
            expect(owner.get('name')).toBe('James');
        });
    });
    it('should save existing entity with new hasMany association', function() {
        var owner = Ext.create('Test.TestBundle.Entity.CarOwner', {
            name: 'James'
        });
        var runned = false;
        runs(function() {
            owner.save({
                callback: function(record, operation, success) {
                    owner.cars().add({
                        name: 'Ford',
                        plateNumber: 'AA1234',
                        password: 'xx'
                    }, {
                        name: 'BMW',
                        plateNumber: 'ASF87654',
                        password: 'xx'
                    });
                    owner.cars().sync({
                        callback: function() {
                            Test.TestBundle.Entity.CarOwner.load(owner.getId(), {
                                callback: function(record) {
                                    owner = record;
                                    runned = true;
                                }
                            });
                        }
                    });
                }
            });
        });
        waitsFor(function() {
            return runned;
        });
        runs(function() {
            expect(owner).not.toBeNull();
            expect(owner.cars().count()).toBe(2);
            expect(owner.cars().first().get('name')).toBe('Ford');
            expect(owner.cars().first().getCarOwner()).toBe(owner);
        });
    });
    it('should save existing entity with existing hasMany association', function() {
        var owner = Ext.create('Test.TestBundle.Entity.CarOwner', {
            name: 'James'
        });
        var runned = false;
        runs(function() {
            owner.save({
                callback: function(record, operation, success) {
                    var car = Ext.create('Test.TestBundle.Entity.Car', {
                        name: 'Ford',
                        plateNumber: 'AA1234',
                        password: 'xx'
                    });
                    car.save({
                        callback: function(record) {
                            owner.cars().add(record);
                            owner.cars().sync({
                                callback: function() {
                                    owner.cars().first().getCarOwner({
                                        callback: function() {
                                            runned = true;
                                        }
                                    });
                                }
                            });
                        }
                    });
                }
            });
        });
        waitsFor(function() {
            return runned;
        });
        runs(function() {
            expect(owner).not.toBeNull();
            expect(owner.cars().count()).toBe(1);
            expect(owner.cars().first().get('name')).toBe('Ford');
            expect(owner.cars().first().getCarOwner().getData()).toEqual(owner.getData());
        });
    });
    it('should save existing entity with existing belongTo association', function() {
        var car = Ext.create('Test.TestBundle.Entity.Car', {
            name: 'Ford',
            plateNumber: 'AA1234',
            password: 'xx'
        });
        var runned = false;
        runs(function() {
            car.save({
                callback: function(record) {
                    var owner = Ext.create('Test.TestBundle.Entity.CarOwner', {
                        name: 'James'
                    });
                    owner.save({
                        callback: function(record) {
                            car.setCarOwner(record, {
                                callback: function() {
                                    runned = true;
                                }
                            });
                        }
                    });
                }
            });
        });
        waitsFor(function() {
            return runned;
        });
        runs(function() {
            expect(car.getCarOwner()).not.toBeNull();
            expect(car.getCarOwner().getId()).toBeGreaterThan(0);
        });
    });
    it('should update entity', function() {
        var car = Ext.create('Test.TestBundle.Entity.Car', {
            name: 'Ford',
            plateNumber: 'AA1234',
            password: 'xx'
        });
        var originalId;
        var runned = false;
        runs(function() {
            car.save({
                callback: function(record) {
                    originalId = record.getId();
                    record.set('name', 'BMW');
                    record.save({
                        callback: function(record) {
                            car = record;
                            runned = true;
                        }
                    })
                }
            })
        });
        waitsFor(function() {
            return runned;
        });
        runs(function() {
            expect(originalId).toBe(car.getId());
            expect(car.get('name')).toBe('BMW');
        });
    })
});
describe('Rest Proxy in Store', function() {
    var store = Ext.create('Ext.data.Store', {
        model: 'Test.TestBundle.Entity.Car',
        autoLoad: false,
        proxy: {
            type: 'rest',
            url: '/mycars',
            format: 'json'
        }
    });
    it('should load all the entity', function() {
        var runned = false;
        runs(function() {
            var car = Ext.create('Test.TestBundle.Entity.Car', {
                name: 'Ford',
                plateNumber: 'AA1234',
                password: 'xx'
            });
            car.save({
                callback: function() {
                    store.load({
                        callback: function() {
                            runned = true;
                        }
                    });
                }
            });
        });
        waitsFor(function() {
            return runned;
        });
        runs(function() {
            expect(store.count()).toBeGreaterThan(0);
        })
    });
    it('should remove all entity', function () {
        var runned = false;
        runs(function () {
            store.load({
                callback: function() {
                    store.removeAll();
                    store.sync({
                        callback: function() {
                            store.load({
                                callback: function() {
                                    runned = true;
                                }
                            })
                        }
                    })
                }
            });
        });
        waitsFor(function () {
            return runned;
        });
        runs(function () {
            expect(store.count()).toBe(0);
        });
    });
    it('should add new entity', function () {
        var runned = false;
        runs(function () {
            store.add([
                {
                    name: 'Ford',
                    plateNumber: 'AA1234',
                    password: 'xx'
                },
                {
                    name: 'BMW',
                    plateNumber: 'ZZ54',
                    password: 'xx'
                }
            ]);
            store.sync({
                callback: function() {
                    runned = true;
                }
            });
        });
        waitsFor(function () {
            return runned;
        });
        runs(function () {
            expect(store.count()).toBe(2);
            expect(store.getNewRecords().length).toBe(0);
        });
    });
});<|endoftext|>


<commit_before>/**
 * A helper for embedding Flambe games in a browser that smartly chooses either the Flash or HTML
 * platform based on what the browser best supports.
 *
 * For testing, you can use URL query ?flambe=flash (or =html) to force the use of a specific
 * platform.
 */
var flambe = {};

/** @define {string} */
flambe.FLASH_VERSION = "11";

/**
 * Embed a Flambe game into the page.
 *
 * @return True if the game was successfully embedded. False if the browser doesn't have a
 *     recent enough browser or Flash player.
 */
flambe.embed = function (urls, elementId) {

    if (typeof urls == "string") {
        urls = [ urls + "-flash.swf", urls + "-html.js" ];
    }

    var container = document.getElementById(elementId);
    if (container == null) {
        throw new Error("Could not find element [id=" + elementId + "]");
    }

    var args = {};
    var pairs = window.location.search.substr(1).split("&");
    for (var ii = 0; ii < pairs.length; ++ii) {
        var pair = pairs[ii].split("=");
        args[unescape(pair[0])] = (pair.length > 1) ? unescape(pair[1]) : null;
    }

    var pref = args["flambe"];

    for (var ii = 0; ii < urls.length; ++ii) {
        var url = urls[ii];
        var ext = url.match(/\.(\w+)(\?|$)/);
        if (ext) {
            ext = ext[1].toLowerCase();
        }

        switch (ext) {
        case "swf":
            if ((pref == null || pref == "flash")
                    && swfobject.hasFlashPlayerVersion(flambe.FLASH_VERSION)) {

                // SWFObject replaces the element it's given, so create a temporary inner element
                // for parity with JS
                var swf = document.createElement("div");
                swf.id = elementId + "-swf";
                container.appendChild(swf);

                // Setup the helper for binding global functions
                if (typeof $flambe_expose == "undefined") {
                    window.$flambe_expose = function (name, objectId) {
                        window[name] = (objectId != null) ? function () {
                            var swf = document.getElementById(objectId);
                            swf[name].apply(swf, arguments);
                        } : null;
                    };
                }

                swfobject.embedSWF(url, swf.id, "100%", "100%", flambe.FLASH_VERSION, null, {}, {
                    allowScriptAccess: "always",
                    allowFullScreen: "true",
                    fullscreenOnSelection: "true",
                    wmode: "direct"
                }, {id: swf.id, name: swf.id});
                return true;
            }
            break;

        case "js":
            if (pref == null || pref == "html") {
                var canvas = document.createElement("canvas");
                if ("getContext" in canvas) {
                    canvas.id = elementId + "-canvas";
                    container.appendChild(canvas);

                    // Expose the canvas so Haxe can use it
                    flambe.canvas = canvas;

                    var script = document.createElement("script");
                    script.onload = function () {
                        flambe.canvas = null;
                    };
                    script.src = url;
                    container.appendChild(script);
                    return true;
                }
            }
            break;

        default:
            throw new Error("Don't know how to embed [url=" + url + "]");
        }
    }

    // Nothing was embedded!
    return false;
};
<commit_msg>Never use Flash on Android.<commit_after>/**
 * A helper for embedding Flambe games in a browser that smartly chooses either the Flash or HTML
 * platform based on what the browser best supports.
 *
 * For testing, you can use URL query ?flambe=flash (or =html) to force the use of a specific
 * platform.
 */
var flambe = {};

/** @define {string} */
flambe.FLASH_VERSION = "11";

/**
 * Embed a Flambe game into the page.
 *
 * @return True if the game was successfully embedded. False if the browser doesn't have a
 *     recent enough browser or Flash player.
 */
flambe.embed = function (urls, elementId) {

    if (typeof urls == "string") {
        urls = [ urls + "-flash.swf", urls + "-html.js" ];
    }

    var container = document.getElementById(elementId);
    if (container == null) {
        throw new Error("Could not find element [id=" + elementId + "]");
    }

    var args = {};
    var pairs = window.location.search.substr(1).split("&");
    for (var ii = 0; ii < pairs.length; ++ii) {
        var pair = pairs[ii].split("=");
        args[unescape(pair[0])] = (pair.length > 1) ? unescape(pair[1]) : null;
    }

    var pref = args["flambe"];

    for (var ii = 0; ii < urls.length; ++ii) {
        var url = urls[ii];
        var ext = url.match(/\.(\w+)(\?|$)/);
        if (ext) {
            ext = ext[1].toLowerCase();
        }

        switch (ext) {
        case "swf":
            if ((pref == null || pref == "flash")
                    && swfobject.hasFlashPlayerVersion(flambe.FLASH_VERSION)
                    // Android Flash is old and busted
                    && !/\bAndroid\b/.exec(navigator.userAgent)) {

                // SWFObject replaces the element it's given, so create a temporary inner element
                // for parity with JS
                var swf = document.createElement("div");
                swf.id = elementId + "-swf";
                container.appendChild(swf);

                // Setup the helper for binding global functions
                if (typeof $flambe_expose == "undefined") {
                    window.$flambe_expose = function (name, objectId) {
                        window[name] = (objectId != null) ? function () {
                            var swf = document.getElementById(objectId);
                            swf[name].apply(swf, arguments);
                        } : null;
                    };
                }

                swfobject.embedSWF(url, swf.id, "100%", "100%", flambe.FLASH_VERSION, null, {}, {
                    allowScriptAccess: "always",
                    allowFullScreen: "true",
                    fullscreenOnSelection: "true",
                    wmode: "direct"
                }, {id: swf.id, name: swf.id});
                return true;
            }
            break;

        case "js":
            if (pref == null || pref == "html") {
                var canvas = document.createElement("canvas");
                if ("getContext" in canvas) {
                    canvas.id = elementId + "-canvas";
                    container.appendChild(canvas);

                    // Expose the canvas so Haxe can use it
                    flambe.canvas = canvas;

                    var script = document.createElement("script");
                    script.onload = function () {
                        flambe.canvas = null;
                    };
                    script.src = url;
                    container.appendChild(script);
                    return true;
                }
            }
            break;

        default:
            throw new Error("Don't know how to embed [url=" + url + "]");
        }
    }

    // Nothing was embedded!
    return false;
};
<|endoftext|>


<commit_before>test('modal shows up', function(assert) {
  var $modal = $('.swal2-modal');

  assert.ok($modal.not(':visible'));
  swal('Hello world!');
  assert.ok($modal.is(':visible'));
});

test('confirm button', function(assert) {
  var done = assert.async();

  swal('Confirm me').then(function(result) {
    assert.equal(result, true);
    done();
  });

  swal.clickConfirm();
});

test('custom buttons classes', function(assert) {
  swal({
    text: 'Modal with custom buttons classes',
    confirmButtonClass: 'btn btn-success',
    cancelButtonClass: 'btn btn-warning'
  });
  assert.ok($('.swal2-confirm').hasClass('btn'));
  assert.ok($('.swal2-confirm').hasClass('btn-success'));
  assert.ok($('.swal2-cancel').hasClass('btn'));
  assert.ok($('.swal2-cancel').hasClass('btn-warning'));

  swal('Modal with default buttons classes');
  assert.notOk($('.swal2-confirm').hasClass('btn'));
  assert.notOk($('.swal2-confirm').hasClass('btn-success'));
  assert.notOk($('.swal2-cancel').hasClass('btn'));
  assert.notOk($('.swal2-cancel').hasClass('btn-warning'));
});

test('cancel button', function(assert) {
  var done = assert.async();

  swal('Cancel me').then(
    function() {},
    function(dismiss) {
      assert.equal(dismiss, 'cancel');
      done();
    }
  );

  swal.clickCancel();
});

test('esc key', function(assert) {
  var done = assert.async();

  swal('Esc me').then(
    function() {},
    function(dismiss) {
      assert.equal(dismiss, 'esc');
      done();
    }
  );

  $(document).trigger($.Event('keydown', {
    keyCode: 27
  }));
});

test('overlay click', function(assert) {
  var done = assert.async();

  swal('Overlay click').then(
    function() {},
    function(dismiss) {
      assert.equal(dismiss, 'overlay');
      done();
    }
  );

  $('.swal2-overlay').click();
});

test('timer works', function(assert) {
  var done = assert.async();

  swal({title: 'Timer test', timer: 10, animation: false}).then(
    function() {},
    function(dismiss) {
      assert.equal(dismiss, 'timer');
      done();
    }
  );
});

test('Close button', function(assert) {
  var done = assert.async();

  swal({title: 'Close button test', showCloseButton: true}).then(
    function() {},
    function(dismiss) {
      assert.equal(dismiss, 'close');
      done();
    }
  );

  var $closeButton = $('.swal2-close');
  assert.ok($closeButton.is(':visible'));
  $closeButton.click();
});

test('jquery/js element as html param', function(assert) {
  swal({
    html: $('
jquery element
')
  });
  assert.equal($('.swal2-content').html(), '
jquery element
');

  var p = document.createElement('p');
  p.textContent = 'js element';
  swal({
    html: p
  });
  assert.equal($('.swal2-content').html(), '
js element
');
});

test('set and reset defaults', function(assert) {
  swal.setDefaults({confirmButtonText: 'Next >', showCancelButton: true});
  swal('Modal with changed defaults');
  assert.equal('Next >', $('.swal2-confirm').text());
  assert.ok($('.swal2-cancel').is(':visible'));

  swal.resetDefaults();
  swal('Modal after resetting defaults');
  assert.equal('OK', $('.swal2-confirm').text());
  assert.ok($('.swal2-cancel').is(':hidden'));

  swal.clickCancel();
});

test('input text', function(assert) {
  var done = assert.async();

  var string = 'Live for yourself';
  swal({input: 'text'}).then(function(result) {
    assert.equal(result, string);
    done();
  });

  $('.swal2-input').val(string);
  swal.clickConfirm();
});

test('input select', function(assert) {
  var done = assert.async();

  var selected = 'dos';
  swal({input: 'select', inputOptions: {uno: 1, dos: 2} }).then(function(result) {
    assert.equal(result, selected);
    done();
  });

  $('.swal2-select').val(selected);
  swal.clickConfirm();
});

test('queue', function(assert) {
  var steps = ['Step 1', 'Step 2'];

  swal.queue(steps).then(function() {
    swal('All done!');
  });
  assert.equal('Step 1', $('.swal2-modal h2').text());
  swal.clickConfirm();
  setTimeout(function() {
    assert.equal('Step 2', $('.swal2-modal h2').text());
    swal.clickConfirm();
  });
  setTimeout(function() {
    assert.equal('All done!', $('.swal2-modal h2').text());
    swal.clickConfirm();
  });

  swal.queue(steps);
  swal.clickCancel();

  setTimeout(function() {
    assert.ok($('.swal2-cancel').is(':hidden'));
  });
});

test('showLoading and hideLoading', function(assert) {
  swal({
    title: 'test loading state',
    showCancelButton: true
  });

  swal.showLoading();
  assert.ok($('.swal2-confirm').hasClass('loading'));
  assert.ok($('.swal2-cancel').is(':disabled'));

  swal.hideLoading();
  assert.notOk($('.swal2-confirm').hasClass('loading'));
  assert.notOk($('.swal2-cancel').is(':disabled'));
});

test('disable/enable buttons', function(assert) {
  swal('test disable/enable buttons');

  swal.disableButtons();
  assert.ok($('.swal2-confirm').is(':disabled'));
  assert.ok($('.swal2-cancel').is(':disabled'));

  swal.enableButtons();
  assert.notOk($('.swal2-confirm').is(':disabled'));
  assert.notOk($('.swal2-cancel').is(':disabled'));

  swal.disableConfirmButton();
  assert.ok($('.swal2-confirm').is(':disabled'));

  swal.enableConfirmButton();
  assert.notOk($('.swal2-confirm').is(':disabled'));
});
<commit_msg>Tests: Add input radio test<commit_after>test('modal shows up', function(assert) {
  var $modal = $('.swal2-modal');

  assert.ok($modal.not(':visible'));
  swal('Hello world!');
  assert.ok($modal.is(':visible'));
});

test('confirm button', function(assert) {
  var done = assert.async();

  swal('Confirm me').then(function(result) {
    assert.equal(result, true);
    done();
  });

  swal.clickConfirm();
});

test('custom buttons classes', function(assert) {
  swal({
    text: 'Modal with custom buttons classes',
    confirmButtonClass: 'btn btn-success',
    cancelButtonClass: 'btn btn-warning'
  });
  assert.ok($('.swal2-confirm').hasClass('btn'));
  assert.ok($('.swal2-confirm').hasClass('btn-success'));
  assert.ok($('.swal2-cancel').hasClass('btn'));
  assert.ok($('.swal2-cancel').hasClass('btn-warning'));

  swal('Modal with default buttons classes');
  assert.notOk($('.swal2-confirm').hasClass('btn'));
  assert.notOk($('.swal2-confirm').hasClass('btn-success'));
  assert.notOk($('.swal2-cancel').hasClass('btn'));
  assert.notOk($('.swal2-cancel').hasClass('btn-warning'));
});

test('cancel button', function(assert) {
  var done = assert.async();

  swal('Cancel me').then(
    function() {},
    function(dismiss) {
      assert.equal(dismiss, 'cancel');
      done();
    }
  );

  swal.clickCancel();
});

test('esc key', function(assert) {
  var done = assert.async();

  swal('Esc me').then(
    function() {},
    function(dismiss) {
      assert.equal(dismiss, 'esc');
      done();
    }
  );

  $(document).trigger($.Event('keydown', {
    keyCode: 27
  }));
});

test('overlay click', function(assert) {
  var done = assert.async();

  swal('Overlay click').then(
    function() {},
    function(dismiss) {
      assert.equal(dismiss, 'overlay');
      done();
    }
  );

  $('.swal2-overlay').click();
});

test('timer works', function(assert) {
  var done = assert.async();

  swal({title: 'Timer test', timer: 10, animation: false}).then(
    function() {},
    function(dismiss) {
      assert.equal(dismiss, 'timer');
      done();
    }
  );
});

test('Close button', function(assert) {
  var done = assert.async();

  swal({title: 'Close button test', showCloseButton: true}).then(
    function() {},
    function(dismiss) {
      assert.equal(dismiss, 'close');
      done();
    }
  );

  var $closeButton = $('.swal2-close');
  assert.ok($closeButton.is(':visible'));
  $closeButton.click();
});

test('jquery/js element as html param', function(assert) {
  swal({
    html: $('
jquery element
')
  });
  assert.equal($('.swal2-content').html(), '
jquery element
');

  var p = document.createElement('p');
  p.textContent = 'js element';
  swal({
    html: p
  });
  assert.equal($('.swal2-content').html(), '
js element
');
});

test('set and reset defaults', function(assert) {
  swal.setDefaults({confirmButtonText: 'Next >', showCancelButton: true});
  swal('Modal with changed defaults');
  assert.equal('Next >', $('.swal2-confirm').text());
  assert.ok($('.swal2-cancel').is(':visible'));

  swal.resetDefaults();
  swal('Modal after resetting defaults');
  assert.equal('OK', $('.swal2-confirm').text());
  assert.ok($('.swal2-cancel').is(':hidden'));

  swal.clickCancel();
});

test('input text', function(assert) {
  var done = assert.async();

  var string = 'Live for yourself';
  swal({input: 'text'}).then(function(result) {
    assert.equal(result, string);
    done();
  });

  $('.swal2-input').val(string);
  swal.clickConfirm();
});

test('input select', function(assert) {
  var done = assert.async();

  var selected = 'dos';
  swal({input: 'select', inputOptions: {uno: 1, dos: 2} }).then(function(result) {
    assert.equal(result, selected);
    done();
  });

  $('.swal2-select').val(selected);
  swal.clickConfirm();
});

test('queue', function(assert) {
  var steps = ['Step 1', 'Step 2'];

  swal.queue(steps).then(function() {
    swal('All done!');
  });
  assert.equal('Step 1', $('.swal2-modal h2').text());
  swal.clickConfirm();
  setTimeout(function() {
    assert.equal('Step 2', $('.swal2-modal h2').text());
    swal.clickConfirm();
  });
  setTimeout(function() {
    assert.equal('All done!', $('.swal2-modal h2').text());
    swal.clickConfirm();
  });

  swal.queue(steps);
  swal.clickCancel();

  setTimeout(function() {
    assert.ok($('.swal2-cancel').is(':hidden'));
  });
});

test('showLoading and hideLoading', function(assert) {
  swal({
    title: 'test loading state',
    showCancelButton: true
  });

  swal.showLoading();
  assert.ok($('.swal2-confirm').hasClass('loading'));
  assert.ok($('.swal2-cancel').is(':disabled'));

  swal.hideLoading();
  assert.notOk($('.swal2-confirm').hasClass('loading'));
  assert.notOk($('.swal2-cancel').is(':disabled'));
});

test('disable/enable buttons', function(assert) {
  swal('test disable/enable buttons');

  swal.disableButtons();
  assert.ok($('.swal2-confirm').is(':disabled'));
  assert.ok($('.swal2-cancel').is(':disabled'));

  swal.enableButtons();
  assert.notOk($('.swal2-confirm').is(':disabled'));
  assert.notOk($('.swal2-cancel').is(':disabled'));

  swal.disableConfirmButton();
  assert.ok($('.swal2-confirm').is(':disabled'));

  swal.enableConfirmButton();
  assert.notOk($('.swal2-confirm').is(':disabled'));
});

test('input radio', function(assert) {
  swal({
    input: 'radio',
    inputOptions: {
      'one': 'one',
      'two': 'two'
    }
  });

  assert.equal($('.swal2-radio label').length, 2);
  assert.equal($('.swal2-radio input[type="radio"]').length, 2);
});
<|endoftext|>


<commit_before>import { mat3, mat4 } from 'gl-matrix';
import Constants      from 'vtk.js/Sources/Common/Transform/LandmarkTransform/Constants';
import macro          from 'vtk.js/Sources/macro';
import vtkMath        from 'vtk.js/Sources/Common/Core/Math';

const { Mode } = Constants;

// ----------------------------------------------------------------------------
// vtkLandmarkTransform methods
// ----------------------------------------------------------------------------

function vtkLandmarkTransform(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkLandmarkTransform');

  // Convert a mat4 matrix to a Matrix 2 dimensions
  function mat4To2DArray(mat) {
    const output = [[0.0, 0.0, 0.0, 0.0],
      [0.0, 0.0, 0.0, 0.0],
      [0.0, 0.0, 0.0, 0.0],
      [0.0, 0.0, 0.0, 0.0]];
    let cpt = 0;
    for (let c = 0; c < 4; c++) {
      for (let r = 0; r < 4; r++) {
        output[r][c] = mat[cpt++];
      }
    }
    return output;
  }

  function update() {
    mat4.identity(model.matrix);
    const N_PTS = model.sourceLandmark.getNumberOfPoints();
    if (model.targetLandmark.getNumberOfPoints() !== N_PTS
      || model.sourceLandmark === null || model.targetLandmark === null || N_PTS === 0) {
      console.error('Error : Bad inputs of vtkLandmarkTransform');
      return model.matrix;
    }

    // -- find the centroid of each set --

    const sourceCentroid = [0, 0, 0];
    const targetCentroid = [0, 0, 0];
    const p = [0, 0, 0];
    for (let i = 0; i < N_PTS; i++) {
      model.sourceLandmark.getPoint(i, p);
      sourceCentroid[0] += p[0];
      sourceCentroid[1] += p[1];
      sourceCentroid[2] += p[2];
      model.targetLandmark.getPoint(i, p);
      targetCentroid[0] += p[0];
      targetCentroid[1] += p[1];
      targetCentroid[2] += p[2];
    }
    sourceCentroid[0] /= N_PTS;
    sourceCentroid[1] /= N_PTS;
    sourceCentroid[2] /= N_PTS;
    targetCentroid[0] /= N_PTS;
    targetCentroid[1] /= N_PTS;
    targetCentroid[2] /= N_PTS;

    // -- if only one point, stop right here

    if (N_PTS === 1) {
      mat4.identity(model.matrix);
      model.matrix.elem[12] = targetCentroid[0] - sourceCentroid[0];
      model.matrix.elem[13] = targetCentroid[1] - sourceCentroid[1];
      model.matrix.elem[14] = targetCentroid[2] - sourceCentroid[2];
      return model.matrix;
    }

    // -- build the 3x3 matrix M --

    const M = mat3.fromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
    const AAT = mat3.fromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);

    const a = [0, 0, 0];
    const b = [0, 0, 0];
    let sa = 0.0;
    let sb = 0.0;
    for (let pt = 0; pt < N_PTS; pt++) {
      // get the origin-centred point (a) in the source set
      model.sourceLandmark.getPoint(pt, a);
      a[0] -= sourceCentroid[0];
      a[1] -= sourceCentroid[1];
      a[2] -= sourceCentroid[2];

      // get the origin-centred point (b) in the target set
      model.targetLandmark.getPoint(pt, b);
      b[0] -= targetCentroid[0];
      b[1] -= targetCentroid[1];
      b[2] -= targetCentroid[2];

      // accumulate the products a*T(b) into the matrix M
      for (let i = 0; i < 3; i++) {
        M[(3 * 0) + i] += a[i] * b[0];
        M[(3 * 1) + i] += a[i] * b[1];
        M[(3 * 2) + i] += a[i] * b[2];

        // for the affine transform, compute ((a.a^t)^-1 . a.b^t)^t.
        // a.b^t is already in M.  here we put a.a^t in AAT.
        if (model.mode === Mode.AFFINE) {
          AAT[(3 * 0) + i] += a[i] * a[0];
          AAT[(3 * 1) + i] += a[i] * a[1];
          AAT[(3 * 2) + i] += a[i] * a[2];
        }
      }
      // accumulate scale factors (if desired)
      sa += (a[0] * a[0]) + (a[1] * a[1]) + (a[2] * a[2]);
      sb += (b[0] * b[0]) + (b[1] * b[1]) + (b[2] * b[2]);
    }

    if (model.mode === Mode.AFFINE) {
      // AAT = (a.a^t)^-1
      mat3.invert(AAT, AAT);

      // M = (a.a^t)^-1 . a.b^t
      mat3.multiply(M, AAT, M);

      // this->Matrix = M^t
      for (let i = 0; i < 3; ++i) {
        for (let j = 0; j < 3; ++j) {
          model.matrix[(4 * j) + i] = M[(4 * i) + j];
        }
      }
    } else {
      const scale = Math.sqrt(sb / sa);

      // -- build the 4x4 matrix N --

      const N = mat4.fromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
      // on-diagonal elements
      N[0] = M[0] + M[4] + M[8];
      N[5] = M[0] - M[4] - M[8];
      N[10] = -M[0] + M[4] - M[8];
      N[15] = -M[0] - M[4] + M[8];
      // off-diagonal elements
      N[4] = N[1] = (M[7] - M[5]);
      N[8] = N[2] = (M[2] - M[6]);
      N[12] = N[3] = (M[3] - M[1]);

      N[9] = N[6] = (M[3] + M[1]);
      N[13] = N[7] = (M[2] + M[6]);
      N[14] = N[11] = (M[7] + M[5]);

      // -- eigen-decompose N (is symmetric) --

      const eigenVectors = [[0.0, 0.0, 0.0, 0.0],
                            [0.0, 0.0, 0.0, 0.0],
                            [0.0, 0.0, 0.0, 0.0],
                            [0.0, 0.0, 0.0, 0.0]];
      const eigenValues = [0.0, 0.0, 0.0, 0.0];

      const NMatrix = mat4To2DArray(N);
      vtkMath.jacobiN(NMatrix, 4, eigenValues, eigenVectors);

      // The eigenvector with the largest eigenvalue is the quaternion we want
      // (they are sorted in decreasing order for us by JacobiN)
      let w;
      let x;
      let y;
      let z;

      // first; if points are collinear, choose the quaternion that
      // results in the smallest rotation
      if (eigenValues[0] === eigenValues[1] || N_PTS === 2) {
        const s0 = [0, 0, 0];
        const t0 = [0, 0, 0];
        const s1 = [0, 0, 0];
        const t1 = [0, 0, 0];
        model.sourceLandmark.getPoint(0, s0);
        model.targetLandmark.getPoint(0, t0);
        model.sourceLandmark.getPoint(1, s1);
        model.targetLandmark.getPoint(1, t1);

        let ds;
        let dt;
        let rs = 0;
        let rt = 0;
        for (let i = 0; i < 3; i++) {
          ds[i] = s1[i] - s0[i]; // vector between points
          rs = (ds[i] * ds[i]) + rs;
          dt[i] = t1[i] - t0[i];
          rt = (dt[i] * dt[i]) + rt;
        }

        // normalize the two vectors
        rs = Math.sqrt(rs);
        ds[0] /= rs;
        ds[1] /= rs;
        ds[2] /= rs;
        rt = Math.sqrt(rt);
        dt[0] /= rt;
        dt[1] /= rt;
        dt[2] /= rt;

        // take dot & cross product
        w = (ds[0] * dt[0]) + (ds[1] * dt[1]) + (ds[2] * dt[2]);
        x = (ds[1] * dt[2]) - (ds[2] * dt[1]);
        y = (ds[2] * dt[0]) - (ds[0] * dt[2]);
        z = (ds[0] * dt[1]) - (ds[1] * dt[0]);

        let r = Math.sqrt((x * x) + (y * y) + (z * z));
        const theta = Math.atan2(r, w);

        // construct quaternion
        w = Math.cos(theta / 2);
        if (r !== 0) {
          r = Math.sin(theta / 2) / r;
          x *= r;
          y *= r;
          z *= r;
        } else { // rotation by 180 degrees : special case
          // Rotate around a vector perpendicular to ds
          vtkMath.perpendiculars(ds, dt, 0, 0);
          r = Math.sin(theta / 2);
          x = dt[0] * r;
          y = dt[1] * r;
          z = dt[2] * r;
        }
      } else { // points are not collinear
        w = eigenVectors[0][0];
        x = eigenVectors[1][0];
        y = eigenVectors[2][0];
        z = eigenVectors[3][0];
      }

      // convert quaternion to a rotation matrix

      const ww = w * w;
      const wx = w * x;
      const wy = w * y;
      const wz = w * z;

      const xx = x * x;
      const yy = y * y;
      const zz = z * z;

      const xy = x * y;
      const xz = x * z;
      const yz = y * z;

      model.matrix[0] = ww + xx - yy - zz;
      model.matrix[1] = 2.0 * (wz + xy);
      model.matrix[2] = 2.0 * (-wy + xz);

      model.matrix[4] = 2.0 * (-wz + xy);
      model.matrix[5] = ww - xx + yy - zz;
      model.matrix[6] = 2.0 * (wx + yz);

      model.matrix[8] = 2.0 * (wy + xz);
      model.matrix[9] = 2.0 * (-wx + yz);
      model.matrix[10] = ww - xx - yy + zz;

      // add in the scale factor (if desired)
      if (model.mode !== Mode.VTK_LANDMARK_RIGIDBODY) {
        for (let i = 0; i < 3; i++) {
          model.matrix[(4 * 0) + i] = model.matrix[(4 * 0) + i] * scale;
          model.matrix[(4 * 1) + i] = model.matrix[(4 * 1) + i] * scale;
          model.matrix[(4 * 2) + i] = model.matrix[(4 * 2) + i] * scale;
        }
      }
    }

    // the translation is given by the difference in the transformed source
    // centroid and the target centroid
    const sx = (model.matrix[0] * sourceCentroid[0]) +
               (model.matrix[4] * sourceCentroid[1]) +
               (model.matrix[8] * sourceCentroid[2]);
    const sy = (model.matrix[1] * sourceCentroid[0]) +
               (model.matrix[5] * sourceCentroid[1]) +
               (model.matrix[9] * sourceCentroid[2]);
    const sz = (model.matrix[2] * sourceCentroid[0]) +
               (model.matrix[6] * sourceCentroid[1]) +
               (model.matrix[10] * sourceCentroid[2]);

    model.matrix[12] = targetCentroid[0] - sx;
    model.matrix[13] = targetCentroid[1] - sy;
    model.matrix[14] = targetCentroid[2] - sz;

    // fill the bottom row of the 4x4 matrix
    model.matrix[3] = 0.0;
    model.matrix[7] = 0.0;
    model.matrix[11] = 0.0;
    model.matrix[15] = 1.0;

    return model.matrix;
  }

  // Expose method
  publicAPI.update = update;
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  mode: Mode.SIMILARITY,
};

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

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);
  macro.obj(publicAPI, model);

  // Internal objects initialization
  model.matrix = mat4.create(); // identity

  macro.setGet(publicAPI, model, ['sourceLandmark', 'targetLandmark', 'mode']);
  macro.get(publicAPI, model, ['matrix']);

  vtkLandmarkTransform(publicAPI, model);
}

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

export const newInstance = macro.newInstance(extend, 'vtkLandmarkTransform');

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

export default { newInstance, extend };
<commit_msg>fix(landmarkTransform): Fix the call of constants that doesn't exist<commit_after>import { mat3, mat4 } from 'gl-matrix';
import Constants      from 'vtk.js/Sources/Common/Transform/LandmarkTransform/Constants';
import macro          from 'vtk.js/Sources/macro';
import vtkMath        from 'vtk.js/Sources/Common/Core/Math';

const { Mode } = Constants;

// ----------------------------------------------------------------------------
// vtkLandmarkTransform methods
// ----------------------------------------------------------------------------

function vtkLandmarkTransform(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkLandmarkTransform');

  // Convert a mat4 matrix to a Matrix 2 dimensions
  function mat4To2DArray(mat) {
    const output = [[0.0, 0.0, 0.0, 0.0],
      [0.0, 0.0, 0.0, 0.0],
      [0.0, 0.0, 0.0, 0.0],
      [0.0, 0.0, 0.0, 0.0]];
    let cpt = 0;
    for (let c = 0; c < 4; c++) {
      for (let r = 0; r < 4; r++) {
        output[r][c] = mat[cpt++];
      }
    }
    return output;
  }

  function update() {
    mat4.identity(model.matrix);
    const N_PTS = model.sourceLandmark.getNumberOfPoints();
    if (model.targetLandmark.getNumberOfPoints() !== N_PTS
      || model.sourceLandmark === null || model.targetLandmark === null || N_PTS === 0) {
      console.error('Error : Bad inputs of vtkLandmarkTransform');
      return model.matrix;
    }

    // -- find the centroid of each set --

    const sourceCentroid = [0, 0, 0];
    const targetCentroid = [0, 0, 0];
    const p = [0, 0, 0];
    for (let i = 0; i < N_PTS; i++) {
      model.sourceLandmark.getPoint(i, p);
      sourceCentroid[0] += p[0];
      sourceCentroid[1] += p[1];
      sourceCentroid[2] += p[2];
      model.targetLandmark.getPoint(i, p);
      targetCentroid[0] += p[0];
      targetCentroid[1] += p[1];
      targetCentroid[2] += p[2];
    }
    sourceCentroid[0] /= N_PTS;
    sourceCentroid[1] /= N_PTS;
    sourceCentroid[2] /= N_PTS;
    targetCentroid[0] /= N_PTS;
    targetCentroid[1] /= N_PTS;
    targetCentroid[2] /= N_PTS;

    // -- if only one point, stop right here

    if (N_PTS === 1) {
      mat4.identity(model.matrix);
      model.matrix.elem[12] = targetCentroid[0] - sourceCentroid[0];
      model.matrix.elem[13] = targetCentroid[1] - sourceCentroid[1];
      model.matrix.elem[14] = targetCentroid[2] - sourceCentroid[2];
      return model.matrix;
    }

    // -- build the 3x3 matrix M --

    const M = mat3.fromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
    const AAT = mat3.fromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);

    const a = [0, 0, 0];
    const b = [0, 0, 0];
    let sa = 0.0;
    let sb = 0.0;
    for (let pt = 0; pt < N_PTS; pt++) {
      // get the origin-centred point (a) in the source set
      model.sourceLandmark.getPoint(pt, a);
      a[0] -= sourceCentroid[0];
      a[1] -= sourceCentroid[1];
      a[2] -= sourceCentroid[2];

      // get the origin-centred point (b) in the target set
      model.targetLandmark.getPoint(pt, b);
      b[0] -= targetCentroid[0];
      b[1] -= targetCentroid[1];
      b[2] -= targetCentroid[2];

      // accumulate the products a*T(b) into the matrix M
      for (let i = 0; i < 3; i++) {
        M[(3 * 0) + i] += a[i] * b[0];
        M[(3 * 1) + i] += a[i] * b[1];
        M[(3 * 2) + i] += a[i] * b[2];

        // for the affine transform, compute ((a.a^t)^-1 . a.b^t)^t.
        // a.b^t is already in M.  here we put a.a^t in AAT.
        if (model.mode === Mode.AFFINE) {
          AAT[(3 * 0) + i] += a[i] * a[0];
          AAT[(3 * 1) + i] += a[i] * a[1];
          AAT[(3 * 2) + i] += a[i] * a[2];
        }
      }
      // accumulate scale factors (if desired)
      sa += (a[0] * a[0]) + (a[1] * a[1]) + (a[2] * a[2]);
      sb += (b[0] * b[0]) + (b[1] * b[1]) + (b[2] * b[2]);
    }

    if (model.mode === Mode.AFFINE) {
      // AAT = (a.a^t)^-1
      mat3.invert(AAT, AAT);

      // M = (a.a^t)^-1 . a.b^t
      mat3.multiply(M, AAT, M);

      // this->Matrix = M^t
      for (let i = 0; i < 3; ++i) {
        for (let j = 0; j < 3; ++j) {
          model.matrix[(4 * j) + i] = M[(4 * i) + j];
        }
      }
    } else {
      const scale = Math.sqrt(sb / sa);

      // -- build the 4x4 matrix N --

      const N = mat4.fromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
      // on-diagonal elements
      N[0] = M[0] + M[4] + M[8];
      N[5] = M[0] - M[4] - M[8];
      N[10] = -M[0] + M[4] - M[8];
      N[15] = -M[0] - M[4] + M[8];
      // off-diagonal elements
      N[4] = N[1] = (M[7] - M[5]);
      N[8] = N[2] = (M[2] - M[6]);
      N[12] = N[3] = (M[3] - M[1]);

      N[9] = N[6] = (M[3] + M[1]);
      N[13] = N[7] = (M[2] + M[6]);
      N[14] = N[11] = (M[7] + M[5]);

      // -- eigen-decompose N (is symmetric) --

      const eigenVectors = [[0.0, 0.0, 0.0, 0.0],
                            [0.0, 0.0, 0.0, 0.0],
                            [0.0, 0.0, 0.0, 0.0],
                            [0.0, 0.0, 0.0, 0.0]];
      const eigenValues = [0.0, 0.0, 0.0, 0.0];

      const NMatrix = mat4To2DArray(N);
      vtkMath.jacobiN(NMatrix, 4, eigenValues, eigenVectors);

      // The eigenvector with the largest eigenvalue is the quaternion we want
      // (they are sorted in decreasing order for us by JacobiN)
      let w;
      let x;
      let y;
      let z;

      // first; if points are collinear, choose the quaternion that
      // results in the smallest rotation
      if (eigenValues[0] === eigenValues[1] || N_PTS === 2) {
        const s0 = [0, 0, 0];
        const t0 = [0, 0, 0];
        const s1 = [0, 0, 0];
        const t1 = [0, 0, 0];
        model.sourceLandmark.getPoint(0, s0);
        model.targetLandmark.getPoint(0, t0);
        model.sourceLandmark.getPoint(1, s1);
        model.targetLandmark.getPoint(1, t1);

        let ds;
        let dt;
        let rs = 0;
        let rt = 0;
        for (let i = 0; i < 3; i++) {
          ds[i] = s1[i] - s0[i]; // vector between points
          rs = (ds[i] * ds[i]) + rs;
          dt[i] = t1[i] - t0[i];
          rt = (dt[i] * dt[i]) + rt;
        }

        // normalize the two vectors
        rs = Math.sqrt(rs);
        ds[0] /= rs;
        ds[1] /= rs;
        ds[2] /= rs;
        rt = Math.sqrt(rt);
        dt[0] /= rt;
        dt[1] /= rt;
        dt[2] /= rt;

        // take dot & cross product
        w = (ds[0] * dt[0]) + (ds[1] * dt[1]) + (ds[2] * dt[2]);
        x = (ds[1] * dt[2]) - (ds[2] * dt[1]);
        y = (ds[2] * dt[0]) - (ds[0] * dt[2]);
        z = (ds[0] * dt[1]) - (ds[1] * dt[0]);

        let r = Math.sqrt((x * x) + (y * y) + (z * z));
        const theta = Math.atan2(r, w);

        // construct quaternion
        w = Math.cos(theta / 2);
        if (r !== 0) {
          r = Math.sin(theta / 2) / r;
          x *= r;
          y *= r;
          z *= r;
        } else { // rotation by 180 degrees : special case
          // Rotate around a vector perpendicular to ds
          vtkMath.perpendiculars(ds, dt, 0, 0);
          r = Math.sin(theta / 2);
          x = dt[0] * r;
          y = dt[1] * r;
          z = dt[2] * r;
        }
      } else { // points are not collinear
        w = eigenVectors[0][0];
        x = eigenVectors[1][0];
        y = eigenVectors[2][0];
        z = eigenVectors[3][0];
      }

      // convert quaternion to a rotation matrix

      const ww = w * w;
      const wx = w * x;
      const wy = w * y;
      const wz = w * z;

      const xx = x * x;
      const yy = y * y;
      const zz = z * z;

      const xy = x * y;
      const xz = x * z;
      const yz = y * z;

      model.matrix[0] = ww + xx - yy - zz;
      model.matrix[1] = 2.0 * (wz + xy);
      model.matrix[2] = 2.0 * (-wy + xz);

      model.matrix[4] = 2.0 * (-wz + xy);
      model.matrix[5] = ww - xx + yy - zz;
      model.matrix[6] = 2.0 * (wx + yz);

      model.matrix[8] = 2.0 * (wy + xz);
      model.matrix[9] = 2.0 * (-wx + yz);
      model.matrix[10] = ww - xx - yy + zz;

      // add in the scale factor (if desired)
      if (model.mode !== Mode.RIGID_BODY) {
        for (let i = 0; i < 3; i++) {
          model.matrix[(4 * 0) + i] = model.matrix[(4 * 0) + i] * scale;
          model.matrix[(4 * 1) + i] = model.matrix[(4 * 1) + i] * scale;
          model.matrix[(4 * 2) + i] = model.matrix[(4 * 2) + i] * scale;
        }
      }
    }

    // the translation is given by the difference in the transformed source
    // centroid and the target centroid
    const sx = (model.matrix[0] * sourceCentroid[0]) +
               (model.matrix[4] * sourceCentroid[1]) +
               (model.matrix[8] * sourceCentroid[2]);
    const sy = (model.matrix[1] * sourceCentroid[0]) +
               (model.matrix[5] * sourceCentroid[1]) +
               (model.matrix[9] * sourceCentroid[2]);
    const sz = (model.matrix[2] * sourceCentroid[0]) +
               (model.matrix[6] * sourceCentroid[1]) +
               (model.matrix[10] * sourceCentroid[2]);

    model.matrix[12] = targetCentroid[0] - sx;
    model.matrix[13] = targetCentroid[1] - sy;
    model.matrix[14] = targetCentroid[2] - sz;

    // fill the bottom row of the 4x4 matrix
    model.matrix[3] = 0.0;
    model.matrix[7] = 0.0;
    model.matrix[11] = 0.0;
    model.matrix[15] = 1.0;

    return model.matrix;
  }

  // Expose method
  publicAPI.update = update;
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  mode: Mode.SIMILARITY,
};

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

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);
  macro.obj(publicAPI, model);

  // Internal objects initialization
  model.matrix = mat4.create(); // identity

  macro.setGet(publicAPI, model, ['sourceLandmark', 'targetLandmark', 'mode']);
  macro.get(publicAPI, model, ['matrix']);

  vtkLandmarkTransform(publicAPI, model);
}

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

export const newInstance = macro.newInstance(extend, 'vtkLandmarkTransform');

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

export default { newInstance, extend };
<|endoftext|>


<commit_before>module.exports = function(req, res) {
    res.send('pong');
};<commit_msg>offsetting to next event loop tick<commit_after>module.exports = function(req, res) {
    /* intentionally throwing into event loop */
    setTimeout(function() {
        res.send('pong');
    }, 1);
};<|endoftext|>


<commit_before>function AJAX(params) {
    this.async = params.async || true;
    this.error = params.error;
    this.method = params.method || 'GET';
    this.success = params.success;
    this.form = params.form;
    this.url = params.url;

    this.request = new XMLHttpRequest();
    this.request.open(this.method, this.url, this.async);

    if (this.success) {
        this.request.onload = this.success;
    }

    if (this.error) {
        this.request.onerror = this.error;
    }

    if (this.form) {
        var params = this.serializeForm(this.form);
        this.request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        this.request.send(params);
    } else {
        this.request.send();
    }

}

AJAX.prototype.serializeForm = function(form) {
    if (!form || form.nodeName !== "FORM") {
        return;
    }

    var i, j, q = [];
    for (i = form.elements.length - 1; i >= 0; i = i - 1) {
        if (form.elements[i].name === "") {
            continue;
        }
        switch (form.elements[i].nodeName) {
        case 'INPUT':
            switch (form.elements[i].type) {
            case 'text':
            case 'hidden':
            case 'password':
            case 'button':
            case 'reset':
            case 'submit':
                q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
                break;
            case 'checkbox':
            case 'radio':
                if (form.elements[i].checked) {
                    q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
                }
                break;
            case 'file':
                break;
            }
            break;
        case 'TEXTAREA':
            q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
            break;
        case 'SELECT':
            switch (form.elements[i].type) {
            case 'select-one':
                q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
                break;
            case 'select-multiple':
                for (j = form.elements[i].options.length - 1; j >= 0; j = j - 1) {
                    if (form.elements[i].options[j].selected) {
                        q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].options[j].value));
                    }
                }
                break;
            }
            break;
        case 'BUTTON':
            switch (form.elements[i].type) {
            case 'reset':
            case 'submit':
            case 'button':
                q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
                break;
            }
            break;
        }
    }

    return q.join("&");
};

function $(query, callback) {
    var node = document.querySelector(query);

    if (callback && node) {
        callback(node);
    }

    return node;
}

function $$(query, callback) {
    var nodeList = document.querySelectorAll(query);
    var nodes = Array.prototype.slice.call(nodeList);

    if (callback) {
        nodes.forEach(callback);
    }

    return nodes;
}

// Setup AJAX form submissions
function modal_show(id) {
    var overlayNode = document.getElementById(id);
    overlayNode.style.display = 'table';
    setTimeout(function() {
        overlayNode.className = overlayNode.className.replace(/ ?invisible ?/, ' ');
    }, 50);
};
function modal_hide(id) {
    var overlayNode = document.getElementById(id);
    overlayNode.className += 'invisible';
    setTimeout(function() {
        overlayNode.style.display = 'none';
    }, 400);
}

var form = $('#form');
form.addEventListener('submit', function(e) {
    e.preventDefault();

    $('.signup').style.display = 'none';
    $('.signup-thanks').style.display = 'inline-block';

    new AJAX({
        form: form,
        method: 'POST',
        success: function(res) {
            console.log(res);
        },
        url: form.getAttribute('action')
    });
    if (ga) ga('send', 'event', 'form', 'submit', 'countdown_email');
}, false);

document.getElementById('twitter-button').addEventListener('click', function(e) {
    modal_show('twitter_modal');
    if (ga) ga('send', 'event', 'button', 'click', 'connect_twitter');
}, false);

var modal = document.getElementById('twitter_modal');

modal.querySelector('.gutter').addEventListener('click', function(e) {
    if (e.target === e.currentTarget) {
        e.preventDefault();
        modal_hide(modal.id);
    }
}.bind(this), false);

modal.querySelector('.modal .close').addEventListener('click', function(e) {
    e.preventDefault();
    modal_hide(modal.id);
}.bind(this), false);

modal.querySelector('.modal .no_thanks').addEventListener('click', function(e) {
    e.preventDefault();
    modal_hide(modal.id);
    if (ga) ga('send', 'event', 'button', 'click', 'dismiss_twitter');
}.bind(this), false);

var tweets = document.getElementsByClassName('twitter');

var bindTweetEvents = function(link) {
    link.addEventListener('click', function(e) {
        e.preventDefault();
        window.open('https://twitter.com/intent/tweet?text='+ encodeURIComponent(GLOBAL_TWEET_TEXT) +'&related=fightfortheftr');
        if (ga) ga('send', 'event', 'button', 'click', 'share_twitter');
    }, false);
}

for (var i = 0; i < tweets.length; i++) {
    if (tweets[i].tagName == 'A')
        bindTweetEvents(tweets[i]);
}

var facebooks = document.getElementsByClassName('facebook');

var bindFacebookEvents = function(link) {
    link.addEventListener('click', function(e) {
        if (ga) ga('send', 'event', 'button', 'click', 'share_facebook');
    }, false);
}

for (var i = 0; i < facebooks.length; i++) {
    if (facebooks[i].tagName == 'A')
        bindFacebookEvents(facebooks[i]);
}

// Rotate organizations
(function(){
    var loc = window.location.href;
    random_org = null;
    if (loc.indexOf('org=') == -1) {
        var coin_toss = Math.random();
        if (coin_toss < 0) {
            random_org = 'fp';
        } else if (coin_toss < 0.5) {
            random_org = 'dp';
        } else {
            random_org = 'fftf';
        }
    }

    if (loc.indexOf('org=fp') != -1 || random_org == 'fp') {
        document.getElementById('org').value = 'fp';
        document.getElementById('randomize_disclosure').style.display = 'none';
        document.getElementById('fp_disclosure').style.display = 'block';
    } else if (loc.indexOf('org=dp') != -1 || random_org == 'dp') {
        document.getElementById('org').value = 'dp';
        document.getElementById('randomize_disclosure').style.display = 'none';
        document.getElementById('dp_disclosure').style.display = 'block';
    } else if (loc.indexOf('org=fftf') != -1 || random_org == 'fftf') {
        document.getElementById('org').value = 'fftf';
        document.getElementById('randomize_disclosure').style.display = 'none';
        document.getElementById('fftf_disclosure').style.display = 'block';
    }

    if (document.referrer.indexOf('//t.co') != -1)
        modal_show('twitter_modal');

})();
<commit_msg>fixed stupid javascript error, jeez<commit_after>function AJAX(params) {
    this.async = params.async || true;
    this.error = params.error;
    this.method = params.method || 'GET';
    this.success = params.success;
    this.form = params.form;
    this.url = params.url;

    this.request = new XMLHttpRequest();
    this.request.open(this.method, this.url, this.async);

    if (this.success) {
        this.request.onload = this.success;
    }

    if (this.error) {
        this.request.onerror = this.error;
    }

    if (this.form) {
        var params = this.serializeForm(this.form);
        this.request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        this.request.send(params);
    } else {
        this.request.send();
    }

}

AJAX.prototype.serializeForm = function(form) {
    if (!form || form.nodeName !== "FORM") {
        return;
    }

    var i, j, q = [];
    for (i = form.elements.length - 1; i >= 0; i = i - 1) {
        if (form.elements[i].name === "") {
            continue;
        }
        switch (form.elements[i].nodeName) {
        case 'INPUT':
            switch (form.elements[i].type) {
            case 'text':
            case 'hidden':
            case 'password':
            case 'button':
            case 'reset':
            case 'submit':
                q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
                break;
            case 'checkbox':
            case 'radio':
                if (form.elements[i].checked) {
                    q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
                }
                break;
            case 'file':
                break;
            }
            break;
        case 'TEXTAREA':
            q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
            break;
        case 'SELECT':
            switch (form.elements[i].type) {
            case 'select-one':
                q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
                break;
            case 'select-multiple':
                for (j = form.elements[i].options.length - 1; j >= 0; j = j - 1) {
                    if (form.elements[i].options[j].selected) {
                        q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].options[j].value));
                    }
                }
                break;
            }
            break;
        case 'BUTTON':
            switch (form.elements[i].type) {
            case 'reset':
            case 'submit':
            case 'button':
                q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
                break;
            }
            break;
        }
    }

    return q.join("&");
};

function $(query, callback) {
    var node = document.querySelector(query);

    if (callback && node) {
        callback(node);
    }

    return node;
}

function $$(query, callback) {
    var nodeList = document.querySelectorAll(query);
    var nodes = Array.prototype.slice.call(nodeList);

    if (callback) {
        nodes.forEach(callback);
    }

    return nodes;
}

// Setup AJAX form submissions
function modal_show(id) {
    var overlayNode = document.getElementById(id);
    overlayNode.style.display = 'table';
    setTimeout(function() {
        overlayNode.className = overlayNode.className.replace(/ ?invisible ?/, ' ');
    }, 50);
};
function modal_hide(id) {
    var overlayNode = document.getElementById(id);
    overlayNode.className += 'invisible';
    setTimeout(function() {
        overlayNode.style.display = 'none';
    }, 400);
}

var form = $('#form');
form.addEventListener('submit', function(e) {
    e.preventDefault();

    $('.signup').style.display = 'none';
    $('.signup-thanks').style.display = 'inline-block';

    new AJAX({
        form: form,
        method: 'POST',
        success: function(res) {
            console.log(res);
        },
        url: form.getAttribute('action')
    });
    if (ga) ga('send', 'event', 'form', 'submit', 'countdown_email');
}, false);

document.getElementById('twitter-button').addEventListener('click', function(e) {
    modal_show('twitter_modal');
    if (ga) ga('send', 'event', 'button', 'click', 'connect_twitter');
}, false);

var modal = document.getElementById('twitter_modal');

modal.querySelector('.gutter').addEventListener('click', function(e) {
    if (e.target === e.currentTarget) {
        e.preventDefault();
        modal_hide(modal.id);
    }
}.bind(this), false);

modal.querySelector('.modal .close').addEventListener('click', function(e) {
    e.preventDefault();
    modal_hide(modal.id);
}.bind(this), false);

/*
modal.querySelector('.modal .no_thanks').addEventListener('click', function(e) {
    e.preventDefault();
    modal_hide(modal.id);
    if (ga) ga('send', 'event', 'button', 'click', 'dismiss_twitter');
}.bind(this), false);
*/

var tweets = document.getElementsByClassName('twitter');

var bindTweetEvents = function(link) {
    link.addEventListener('click', function(e) {
        e.preventDefault();
        window.open('https://twitter.com/intent/tweet?text='+ encodeURIComponent(GLOBAL_TWEET_TEXT) +'&related=fightfortheftr');
        if (ga) ga('send', 'event', 'button', 'click', 'share_twitter');
    }, false);
}

for (var i = 0; i < tweets.length; i++) {
    if (tweets[i].tagName == 'A')
        bindTweetEvents(tweets[i]);
}

var facebooks = document.getElementsByClassName('facebook');

var bindFacebookEvents = function(link) {
    link.addEventListener('click', function(e) {
        if (ga) ga('send', 'event', 'button', 'click', 'share_facebook');
    }, false);
}

for (var i = 0; i < facebooks.length; i++) {
    if (facebooks[i].tagName == 'A')
        bindFacebookEvents(facebooks[i]);
}

// Rotate organizations
(function(){
    var loc = window.location.href;
    random_org = null;
    if (loc.indexOf('org=') == -1) {
        var coin_toss = Math.random();
        if (coin_toss < 0) {
            random_org = 'fp';
        } else if (coin_toss < 0.5) {
            random_org = 'dp';
        } else {
            random_org = 'fftf';
        }
    }

    if (loc.indexOf('org=fp') != -1 || random_org == 'fp') {
        document.getElementById('org').value = 'fp';
        document.getElementById('randomize_disclosure').style.display = 'none';
        document.getElementById('fp_disclosure').style.display = 'block';
    } else if (loc.indexOf('org=dp') != -1 || random_org == 'dp') {
        document.getElementById('org').value = 'dp';
        document.getElementById('randomize_disclosure').style.display = 'none';
        document.getElementById('dp_disclosure').style.display = 'block';
    } else if (loc.indexOf('org=fftf') != -1 || random_org == 'fftf') {
        document.getElementById('org').value = 'fftf';
        document.getElementById('randomize_disclosure').style.display = 'none';
        document.getElementById('fftf_disclosure').style.display = 'block';
    }

    if (document.referrer.indexOf('//t.co') != -1)
        modal_show('twitter_modal');

})();
<|endoftext|>


<commit_before>if(typeof(console)=='undefined')console={log:function(){}};
if(typeof(DBTableEditor)=='undefined') DBTableEditor={};

DBTableEditor.commandQueue =[];
DBTableEditor.queueAndExecuteCommand = function(item, column, editCommand){
  DBTableEditor.commandQueue.push(editCommand);
  editCommand.execute();
};

DBTableEditor.saveFailCB = function(err, resp){
  console.log('SAVE FAILED', err, resp);
  jQuery('button.save').attr("disabled", null);
  var src = jQuery('button.save img').attr('src');
  jQuery('button.save img').attr('src',src.replace('loading.gif','accept.png'));

};
DBTableEditor.saveCB = function(data){
  console.log('Save Success');
  jQuery('button.save').attr("disabled", null);
  var src = jQuery('button.save img').attr('src');
  jQuery('button.save img').attr('src',src.replace('loading.gif','accept.png'));

  var pair;
  while((pair = data.pop())){
    var item = DBTableEditor.dataView.getItemById( pair.rowId );
    item[DBTableEditor.columnMap['id']] = pair.dbid;
    DBTableEditor.dataView.updateItem(pair.rowId, item);
  }
};

DBTableEditor.clearFilters = function(){
  DBTableEditor.columnFilters = {};
  jQuery(DBTableEditor.grid.getHeaderRow())
   .find(':input').each(function(){jQuery(this).val('');});
  DBTableEditor.dataView.refresh();
};

DBTableEditor.save = function(){
  jQuery('button.save').attr("disabled", "disabled");
  var src = jQuery('button.save img').attr('src');
  jQuery('button.save img').attr('src',src.replace('accept.png','loading.gif'));

  // the last time we modified a row should contain all the final modifications
  var h = {},i,r, toSave=[], mod = DBTableEditor.modifiedRows.slice(0);
  while(( r = mod.pop() )){
    if(h[r.item.id]) continue;
    h[r.item.id] = true;
    toSave.push(r.item);
  }
  //console.log(toSave);
  var cols = DBTableEditor.data.columns.map(function(c){return c.name;});
  cols.shift(); // remove buttons
  var toSend = JSON.stringify({
    columns:cols,
    rows:toSave
  });

  jQuery.post(ajaxurl, {action:'dbte_save', data:toSend, table:DBTableEditor.table})
    .success(DBTableEditor.saveCB)
    .error(DBTableEditor.saveFailCB);

};

DBTableEditor.undo = function () {
  var command = DBTableEditor.commandQueue.pop();
  if (command && Slick.GlobalEditorLock.cancelCurrentEdit()) {
    command.undo();
    DBTableEditor.popPendingSaves(2);// remove the undo, and the undone thing
    DBTableEditor.grid.gotoCell(command.row, command.cell, false);
  }
  return false;
};
DBTableEditor.gotoNewRow = function () {
  DBTableEditor.grid.gotoCell(DBTableEditor.grid.getDataLength(), 0, true);
};

DBTableEditor.filterRow = function (item) {
  //console.log(item);
  var columnFilters = DBTableEditor.columnFilters,
      grid = DBTableEditor.grid;
  for (var columnId in columnFilters) {
    if (columnId !== undefined && columnFilters[columnId] !== "") {
      var c = grid.getColumns()[grid.getColumnIndex(columnId)];
      var filterVal = columnFilters[columnId];
      var re = new RegExp(filterVal,'i');
      if (item[c.field].toString().search(re) < 0) {
        return false;
      }
    }
  }
  return true;
};

DBTableEditor.deleteSuccess = function(data, id, rowId){
  console.log('Removed', data, id, rowId);
  DBTableEditor.dataView.deleteItem(rowId);
};

DBTableEditor.deleteFail = function(err, resp){
  console.log('delete failed', err, resp);
};

DBTableEditor.deleteHandler = function(el){
  var btn = jQuery(el);
  var id = btn.data('id');
  var rowid = btn.data('rowid');
  btn.parents('.slick-row').addClass('active');
  if(!id) return;
  if(!btn.is('button'))btn = btn.parents('button');
  if (!confirm('Are you sure you wish to remove this row')) return;
  jQuery.post(ajaxurl, {action:'dbte_delete', dataid:id, rowid:rowid, table:DBTableEditor.table})
   .success(function(data){DBTableEditor.deleteSuccess(data, id, rowid);})
   .error(DBTableEditor.deleteFail);
  return false;
};
DBTableEditor.extraButtons=[];
DBTableEditor.rowButtonFormatter = function(row, cell, value, columnDef, dataContext) {
  // if(row==0)console.log(row,cell, value, columnDef, dataContext);
  var id = dataContext[DBTableEditor.columnMap['id']];
  var rowid = dataContext['id'];
  if(!id) return null;
  var url = DBTableEditor.baseUrl+'/assets/images/delete.png';
  var out = '<button title="Delete this Row" class="delete" onclick="DBTableEditor.deleteHandler(this);return false;"'+
    ' data-rowid="'+rowid+'" '+
    ' data-id="'+id+'" />'+
    '</button>';
  jQuery.each(DBTableEditor.extraButtons, function(i,fn){
    out += fn(row, cell, value, columnDef, dataContext);
  });
  return out;
};

DBTableEditor.exportCSV = function(){
  var url = jQuery(DBTableEditor.grid.getHeaderRow())
   .find(':input').filter(function(){return jQuery(this).val().length>0;})
   .serialize();
  var url = ajaxurl+'?action=dbte_export_csv&table='+DBTableEditor.table+'&'+url;
  console.log('Redirecting to export:', url);
  window.location=url;
};

DBTableEditor.updatePagingInfo = function(){
  var cnt = DBTableEditor.dataView.getPagingInfo()["totalRows"];
  jQuery('.db-table-editor-row-count').text ("Showing "+cnt+" of "+DBTableEditor.data.rows.length+" rows");
};

DBTableEditor._ids_ ={};
DBTableEditor.newId = function(id){
  var newid=id;
  while(!newid || DBTableEditor._ids_[newid]){
    newid = Math.floor(Math.random() * 100000)*100000;}
  DBTableEditor._ids_[newid]=true;
  return newid;
};

DBTableEditor.popPendingSaves = function(n){
  if(n==null) n = 1;
  var rtn, it;
  if(n == 1)
    rtn = DBTableEditor.modifiedRows.pop();
  else {
    rtn=[];
    // while we havent popped enough and there are things to pop
    while(n-->0 && (it=DBTableEditor.modifiedRows.pop())) rtn.push(it);
  }
  jQuery('.pending-save-count').text(DBTableEditor.modifiedRows.length);
  return rtn;
};

DBTableEditor.clearPendingSaves = function(){
  DBTableEditor.modifiedRows = [];
  jQuery('.pending-save-count').text(DBTableEditor.modifiedRows.length);
};
DBTableEditor.addPendingSave = function(args){
  DBTableEditor.modifiedRows.push(args);
  jQuery('.pending-save-count').text(DBTableEditor.modifiedRows.length);
};

DBTableEditor.onload = function(opts){
  //console.log('Loading db table');
  jQuery.extend(DBTableEditor, opts);
  if(!DBTableEditor.data){ return console.log("No Data for DBTableEditor");}
  var rows = DBTableEditor.data.rows;
  var columns = DBTableEditor.data.columns;
  var columnMap = DBTableEditor.columnMap = {};

  // init columns
  for( var i=0, c ; c=columns[i] ; i++){
    c.id=c.name.toLowerCase();
    c.field = i;
    c.sortable = true;
    //account for buttons column at 0 if needed
    columnMap[c.id] = DBTableEditor.noedit ? i : i+1;

    if(c.id!="id" && !c.editor){
      if(c.id.search('date')>=0){
        c.editor = Slick.Editors.Date;
      }
      var maxLen = 0;
      for(var j=0 ; j < 100 ; j++){
        if(rows[j] && rows[j][c.field]){
          maxLen = Math.max(rows[j][c.field].toString().length, maxLen);
        }
        else{
          // console.log(j, rows[j], c.field, rows[j][c.field]);
        }
      }
      if(maxLen < 65) c.editor = Slick.Editors.Text;
      else c.editor = Slick.Editors.LongText;
    }
  }
  if(columnMap['id']==null) DBTableEditor.noedit = true;
  if(!DBTableEditor.noedit)
    columns.unshift({id: 'buttons', formatter:DBTableEditor.rowButtonFormatter, width:75});

  //init rows
  for(var i=0, r ; r=rows[i] ; i++){
    //r.shift(null);
    var rid = DBTableEditor.newId((columnMap["id"]!=null) && r[columnMap["id"]]);
    r["id"] = rid;
    if(!DBTableEditor.noedit) r.push(null);
  }

  var options = {
    enableCellNavigation: true,
    enableColumnReorder: true,
    editable: true,
    enableAddRow: true,
    multiColumnSort:true,
    autoEdit:false,
    editCommandHandler: DBTableEditor.queueAndExecuteCommand,
    showHeaderRow: true,
    headerRowHeight: 30,
    defaultColumnWidth:120,
    explicitInitialization: true
  };
  var columnFilters = DBTableEditor.columnFilters = DBTableEditor.columnFilters || {};
  var dataView = DBTableEditor.dataView = new Slick.Data.DataView({ inlineFilters: true });
  var grid = DBTableEditor.grid = new Slick.Grid('.db-table-editor', dataView, columns, options);
  grid.setSelectionModel(new Slick.CellSelectionModel());
  var nextCell = function (args){
    var ri = args.row === null ? rows.length-1 : args.row,
        ci = args.cell=== null ? 1 : args.cell + 1 ;
    if(ci >= columns.length){
      ci=0;
      ri++;
    }
    //console.log("going to:", ri, ci, args);
    grid.gotoCell(ri, ci, true);
  };

  DBTableEditor.clearPendingSaves();
  grid.onAddNewRow.subscribe(function (e, args) {
    var item = args.item;
    grid.invalidateRow(rows.length);
    item.id = DBTableEditor.newId();
    dataView.addItem(item);
    grid.updateRowCount();
    grid.render();
    DBTableEditor.addPendingSave(args);
    DBTableEditor.mostRecentEdit = new Date();
    nextCell(args);
  });

  grid.onCellChange.subscribe(function(e, args){
    var item = args.item;
    //console.log('edit', e, args, item);
    DBTableEditor.addPendingSave(args);
    DBTableEditor.mostRecentEdit = new Date();
    nextCell(args);
  });

  grid.onSort.subscribe(function(e, args){ // args: sort information.
    var cols = args.sortCols;
    var typedVal = function(c, r, n){
      var v = r[n];
      if(c.type == 'int') return Number(v);
      else if(c.id.search('date')>=0) return new Date(v);
      return v && v.toLowerCase();
    };
    var rowSorter = function (r1, r2) {
      for (var c, i=0; c=cols[i]; i++) {
        var field = c.sortCol.field;
        var sign = c.sortAsc ? 1 : -1;
        var value1 = typedVal(c.sortCol,r1,field),
            value2 = typedVal(c.sortCol,r2,field);
        var result = (value1 == value2 ? 0 : (value1 > value2 ? 1 : -1)) * sign;
        if (result != 0) {
          return result;
        }
      }
      return 0;
    };
    dataView.sort(rowSorter);
    grid.invalidate();
    grid.render();
  });

  dataView.onRowCountChanged.subscribe(function (e, args) {
    grid.updateRowCount();
    grid.render();
    DBTableEditor.updatePagingInfo();
  });

  dataView.onRowsChanged.subscribe(function (e, args) {
    grid.invalidateRows(args.rows);
    grid.render();
    DBTableEditor.updatePagingInfo();
  });

  jQuery(grid.getHeaderRow()).delegate(":input", "change keyup", function (e) {
    var columnId = jQuery(this).data("columnId");
    if (columnId != null) {
      columnFilters[columnId] = jQuery.trim(jQuery(this).val());
      dataView.refresh();
    }
  });

  grid.onHeaderRowCellRendered.subscribe(function(e, args) {
      jQuery(args.node).empty();
      if(args.column.id == "buttons") return;
      DBTableEditor.$filterRow = jQuery(args.node);
      jQuery("<input type='text'>")
         .data("columnId", args.column.id)
         .val(DBTableEditor.columnFilters[args.column.id])
         .attr('name','filter-'+args.column.id)
         .appendTo(args.node);
  });

  grid.init();
  if(columns.length < 8) grid.autosizeColumns();
  dataView.beginUpdate();
  dataView.setItems(rows);
  dataView.setFilter(DBTableEditor.filterRow);
  dataView.endUpdate();
  dataView.refresh();
  DBTableEditor.updatePagingInfo();

  jQuery('button.save').attr("disabled", null);

  //console.log('Finished loading db table');
};
<commit_msg>remove local columnFilters that got inadvertently closed re Design:#2478<commit_after>if(typeof(console)=='undefined')console={log:function(){}};
if(typeof(DBTableEditor)=='undefined') DBTableEditor={};

DBTableEditor.commandQueue =[];
DBTableEditor.queueAndExecuteCommand = function(item, column, editCommand){
  DBTableEditor.commandQueue.push(editCommand);
  editCommand.execute();
};

DBTableEditor.saveFailCB = function(err, resp){
  console.log('SAVE FAILED', err, resp);
  jQuery('button.save').attr("disabled", null);
  var src = jQuery('button.save img').attr('src');
  jQuery('button.save img').attr('src',src.replace('loading.gif','accept.png'));

};
DBTableEditor.saveCB = function(data){
  console.log('Save Success');
  jQuery('button.save').attr("disabled", null);
  var src = jQuery('button.save img').attr('src');
  jQuery('button.save img').attr('src',src.replace('loading.gif','accept.png'));

  var pair;
  while((pair = data.pop())){
    var item = DBTableEditor.dataView.getItemById( pair.rowId );
    item[DBTableEditor.columnMap['id']] = pair.dbid;
    DBTableEditor.dataView.updateItem(pair.rowId, item);
  }
};

DBTableEditor.clearFilters = function(){
  DBTableEditor.columnFilters = {};
  jQuery(DBTableEditor.grid.getHeaderRow())
   .find(':input').each(function(){jQuery(this).val('');});
  DBTableEditor.dataView.refresh();
};

DBTableEditor.save = function(){
  jQuery('button.save').attr("disabled", "disabled");
  var src = jQuery('button.save img').attr('src');
  jQuery('button.save img').attr('src',src.replace('accept.png','loading.gif'));

  // the last time we modified a row should contain all the final modifications
  var h = {},i,r, toSave=[], mod = DBTableEditor.modifiedRows.slice(0);
  while(( r = mod.pop() )){
    if(h[r.item.id]) continue;
    h[r.item.id] = true;
    toSave.push(r.item);
  }
  //console.log(toSave);
  var cols = DBTableEditor.data.columns.map(function(c){return c.name;});
  cols.shift(); // remove buttons
  var toSend = JSON.stringify({
    columns:cols,
    rows:toSave
  });

  jQuery.post(ajaxurl, {action:'dbte_save', data:toSend, table:DBTableEditor.table})
    .success(DBTableEditor.saveCB)
    .error(DBTableEditor.saveFailCB);

};

DBTableEditor.undo = function () {
  var command = DBTableEditor.commandQueue.pop();
  if (command && Slick.GlobalEditorLock.cancelCurrentEdit()) {
    command.undo();
    DBTableEditor.popPendingSaves(2);// remove the undo, and the undone thing
    DBTableEditor.grid.gotoCell(command.row, command.cell, false);
  }
  return false;
};
DBTableEditor.gotoNewRow = function () {
  DBTableEditor.grid.gotoCell(DBTableEditor.grid.getDataLength(), 0, true);
};

DBTableEditor.filterRow = function (item) {
  //console.log(item);
  var columnFilters = DBTableEditor.columnFilters,
      grid = DBTableEditor.grid;
  for (var columnId in columnFilters) {
    if (columnId !== undefined && columnFilters[columnId] !== "") {
      var c = grid.getColumns()[grid.getColumnIndex(columnId)];
      var filterVal = columnFilters[columnId];
      var re = new RegExp(filterVal,'i');
      if (item[c.field].toString().search(re) < 0) {
        return false;
      }
    }
  }
  return true;
};

DBTableEditor.deleteSuccess = function(data, id, rowId){
  console.log('Removed', data, id, rowId);
  DBTableEditor.dataView.deleteItem(rowId);
};

DBTableEditor.deleteFail = function(err, resp){
  console.log('delete failed', err, resp);
};

DBTableEditor.deleteHandler = function(el){
  var btn = jQuery(el);
  var id = btn.data('id');
  var rowid = btn.data('rowid');
  btn.parents('.slick-row').addClass('active');
  if(!id) return;
  if(!btn.is('button'))btn = btn.parents('button');
  if (!confirm('Are you sure you wish to remove this row')) return;
  jQuery.post(ajaxurl, {action:'dbte_delete', dataid:id, rowid:rowid, table:DBTableEditor.table})
   .success(function(data){DBTableEditor.deleteSuccess(data, id, rowid);})
   .error(DBTableEditor.deleteFail);
  return false;
};
DBTableEditor.extraButtons=[];
DBTableEditor.rowButtonFormatter = function(row, cell, value, columnDef, dataContext) {
  // if(row==0)console.log(row,cell, value, columnDef, dataContext);
  var id = dataContext[DBTableEditor.columnMap['id']];
  var rowid = dataContext['id'];
  if(!id) return null;
  var url = DBTableEditor.baseUrl+'/assets/images/delete.png';
  var out = '<button title="Delete this Row" class="delete" onclick="DBTableEditor.deleteHandler(this);return false;"'+
    ' data-rowid="'+rowid+'" '+
    ' data-id="'+id+'" />'+
    '</button>';
  jQuery.each(DBTableEditor.extraButtons, function(i,fn){
    out += fn(row, cell, value, columnDef, dataContext);
  });
  return out;
};

DBTableEditor.exportCSV = function(){
  var url = jQuery(DBTableEditor.grid.getHeaderRow())
   .find(':input').filter(function(){return jQuery(this).val().length>0;})
   .serialize();
  var url = ajaxurl+'?action=dbte_export_csv&table='+DBTableEditor.table+'&'+url;
  console.log('Redirecting to export:', url);
  window.location=url;
};

DBTableEditor.updatePagingInfo = function(){
  var cnt = DBTableEditor.dataView.getPagingInfo()["totalRows"];
  jQuery('.db-table-editor-row-count').text ("Showing "+cnt+" of "+DBTableEditor.data.rows.length+" rows");
};

DBTableEditor._ids_ ={};
DBTableEditor.newId = function(id){
  var newid=id;
  while(!newid || DBTableEditor._ids_[newid]){
    newid = Math.floor(Math.random() * 100000)*100000;}
  DBTableEditor._ids_[newid]=true;
  return newid;
};

DBTableEditor.popPendingSaves = function(n){
  if(n==null) n = 1;
  var rtn, it;
  if(n == 1)
    rtn = DBTableEditor.modifiedRows.pop();
  else {
    rtn=[];
    // while we havent popped enough and there are things to pop
    while(n-->0 && (it=DBTableEditor.modifiedRows.pop())) rtn.push(it);
  }
  jQuery('.pending-save-count').text(DBTableEditor.modifiedRows.length);
  return rtn;
};

DBTableEditor.clearPendingSaves = function(){
  DBTableEditor.modifiedRows = [];
  jQuery('.pending-save-count').text(DBTableEditor.modifiedRows.length);
};
DBTableEditor.addPendingSave = function(args){
  DBTableEditor.modifiedRows.push(args);
  jQuery('.pending-save-count').text(DBTableEditor.modifiedRows.length);
};

DBTableEditor.onload = function(opts){
  //console.log('Loading db table');
  jQuery.extend(DBTableEditor, opts);
  if(!DBTableEditor.data){ return console.log("No Data for DBTableEditor");}
  var rows = DBTableEditor.data.rows;
  var columns = DBTableEditor.data.columns;
  var columnMap = DBTableEditor.columnMap = {};

  // init columns
  for( var i=0, c ; c=columns[i] ; i++){
    c.id=c.name.toLowerCase();
    c.field = i;
    c.sortable = true;
    //account for buttons column at 0 if needed
    columnMap[c.id] = DBTableEditor.noedit ? i : i+1;

    if(c.id!="id" && !c.editor){
      if(c.id.search('date')>=0){
        c.editor = Slick.Editors.Date;
      }
      var maxLen = 0;
      for(var j=0 ; j < 100 ; j++){
        if(rows[j] && rows[j][c.field]){
          maxLen = Math.max(rows[j][c.field].toString().length, maxLen);
        }
        else{
          // console.log(j, rows[j], c.field, rows[j][c.field]);
        }
      }
      if(maxLen < 65) c.editor = Slick.Editors.Text;
      else c.editor = Slick.Editors.LongText;
    }
  }
  if(columnMap['id']==null) DBTableEditor.noedit = true;
  if(!DBTableEditor.noedit)
    columns.unshift({id: 'buttons', formatter:DBTableEditor.rowButtonFormatter, width:75});

  //init rows
  for(var i=0, r ; r=rows[i] ; i++){
    //r.shift(null);
    var rid = DBTableEditor.newId((columnMap["id"]!=null) && r[columnMap["id"]]);
    r["id"] = rid;
    if(!DBTableEditor.noedit) r.push(null);
  }

  var options = {
    enableCellNavigation: true,
    enableColumnReorder: true,
    editable: true,
    enableAddRow: true,
    multiColumnSort:true,
    autoEdit:false,
    editCommandHandler: DBTableEditor.queueAndExecuteCommand,
    showHeaderRow: true,
    headerRowHeight: 30,
    defaultColumnWidth:120,
    explicitInitialization: true
  };
  DBTableEditor.columnFilters = DBTableEditor.columnFilters || {};
  var dataView = DBTableEditor.dataView = new Slick.Data.DataView({ inlineFilters: true });
  var grid = DBTableEditor.grid = new Slick.Grid('.db-table-editor', dataView, columns, options);
  grid.setSelectionModel(new Slick.CellSelectionModel());
  var nextCell = function (args){
    var ri = args.row === null ? rows.length-1 : args.row,
        ci = args.cell=== null ? 1 : args.cell + 1 ;
    if(ci >= columns.length){
      ci=0;
      ri++;
    }
    //console.log("going to:", ri, ci, args);
    grid.gotoCell(ri, ci, true);
  };

  DBTableEditor.clearPendingSaves();
  grid.onAddNewRow.subscribe(function (e, args) {
    var item = args.item;
    grid.invalidateRow(rows.length);
    item.id = DBTableEditor.newId();
    dataView.addItem(item);
    grid.updateRowCount();
    grid.render();
    DBTableEditor.addPendingSave(args);
    DBTableEditor.mostRecentEdit = new Date();
    nextCell(args);
  });

  grid.onCellChange.subscribe(function(e, args){
    var item = args.item;
    //console.log('edit', e, args, item);
    DBTableEditor.addPendingSave(args);
    DBTableEditor.mostRecentEdit = new Date();
    nextCell(args);
  });

  grid.onSort.subscribe(function(e, args){ // args: sort information.
    var cols = args.sortCols;
    var typedVal = function(c, r, n){
      var v = r[n];
      if(c.type == 'int') return Number(v);
      else if(c.id.search('date')>=0) return new Date(v);
      return v && v.toLowerCase();
    };
    var rowSorter = function (r1, r2) {
      for (var c, i=0; c=cols[i]; i++) {
        var field = c.sortCol.field;
        var sign = c.sortAsc ? 1 : -1;
        var value1 = typedVal(c.sortCol,r1,field),
            value2 = typedVal(c.sortCol,r2,field);
        var result = (value1 == value2 ? 0 : (value1 > value2 ? 1 : -1)) * sign;
        if (result != 0) {
          return result;
        }
      }
      return 0;
    };
    dataView.sort(rowSorter);
    grid.invalidate();
    grid.render();
  });

  dataView.onRowCountChanged.subscribe(function (e, args) {
    grid.updateRowCount();
    grid.render();
    DBTableEditor.updatePagingInfo();
  });

  dataView.onRowsChanged.subscribe(function (e, args) {
    grid.invalidateRows(args.rows);
    grid.render();
    DBTableEditor.updatePagingInfo();
  });

  jQuery(grid.getHeaderRow()).delegate(":input", "change keyup", function (e) {
    var columnId = jQuery(this).data("columnId");
    if (columnId != null) {
      DBTableEditor.columnFilters[columnId] = jQuery.trim(jQuery(this).val());
      dataView.refresh();
    }
  });

  grid.onHeaderRowCellRendered.subscribe(function(e, args) {
      jQuery(args.node).empty();
      if(args.column.id == "buttons") return;
      jQuery("<input type='text'>")
         .data("columnId", args.column.id)
         .val(DBTableEditor.columnFilters[args.column.id])
         .attr('name','filter-'+args.column.id)
         .appendTo(args.node);
  });

  grid.init();
  if(columns.length < 8) grid.autosizeColumns();
  dataView.beginUpdate();
  dataView.setItems(rows);
  dataView.setFilter(DBTableEditor.filterRow);
  dataView.endUpdate();
  dataView.refresh();
  DBTableEditor.updatePagingInfo();

  jQuery('button.save').attr("disabled", null);

  //console.log('Finished loading db table');
};
<|endoftext|>