<commit_before>pc.extend(pc.input, function () {
    /**
     * Create a new Mouse object
     * @class Capture and respond to mouse events.
     * @param {DOMElement} [element] The DOMElement that the mouse events are attached to
     * @name pc.input.Mouse
     */
    var Mouse = function(element) {
            // Clear the mouse state
            this._positionY    = 0;
            this._positionX    = 0;
            this._offsetX      = 0;
            this._offsetY      = 0;
            this._deltaX       = 0;
            this._deltaY       = 0;
            this._buttons      = [false,false,false];
            this._lastbuttons  = [];

            this._upHandler = pc.callback(this, this._handleUp);
            this._downHandler = pc.callback(this, this._handleDown);
            this._moveHandler = pc.callback(this, this._handleMove);
            this._wheelHandler = pc.callback(this, this._handleWheel);
            this._contextMenuHandler = function (event) { event.preventDefault(); };

            this._element = null;

            if(element) {
                this.attach(element);
            }

            // Add events
            pc.extend(this, pc.events);
        };

    /**
     * @function
     * @name pc.input.Mouse#attach
     * @description Attach mouse events to a DOMElement.
     * @param {Object} element
     */
    Mouse.prototype.attach = function (element) {
        // Store which DOM element the mouse is handling
        this._element = element;

        this._element.addEventListener("mouseup", this._upHandler, false);
        this._element.addEventListener("mousedown", this._downHandler, false);
        this._element.addEventListener("mousemove", this._moveHandler, false);
        this._element.addEventListener("mousewheel", this._wheelHandler, false); // WekKit
        this._element.addEventListener("DOMMouseScroll", this._wheelHandler, false); // Gecko
    };

    /**
     * @function
     * @name pc.input.Mouse#detach
     * @description Remove mouse events from the DOMElement
     */
    Mouse.prototype.detach = function () {
        this._element.removeEventListener("mouseup", this._upHandler);
        this._element.removeEventListener("mousedown", this._downHandler);
        this._element.removeEventListener("mousemove", this._moveHandler);
        this._element.removeEventListener("mousewheel", this._wheelHandler); // WekKit
        this._element.removeEventListener("DOMMouseScroll", this._wheelHandler); // Gecko

        this._element = null;
    };

    /**
     * @function
     * @name pc.input.Mouse#disableContextMenu
     * @description Disable the context menu usually activated with right-click
     */
    Mouse.prototype.disableContextMenu = function () {
        this._element.addEventListener("contextmenu", this._contextMenuHandler);
    };

    /**
     * @function
     * @name pc.input.Mouse#enableContextMenu
     * @description Enable the context menu usually activated with right-click. This option is active by default.
     */
    Mouse.prototype.enableContextMenu = function () {
        this._element.removeEventListener("contextmenu", this._contextMenuHandler);
    };

    /**
     * @function
     * @name pc.input.Mouse#update
     * @description Update method, should be called once per frame
     * @param {Object} dt
     */
    Mouse.prototype.update = function (dt) {
        // Copy current button state
        this._lastbuttons = this._buttons.slice(0);
    };

    /**
     * @function
     * @name pc.input.Mouse#isPressed
     * @description Returns true if the mouse button is currently pressed
     * @param {Object} button
     */
    Mouse.prototype.isPressed = function (button) {
        return this._buttons[button];
    };

    /**
     * @function
     * @name pc.input.Mouse#wasPressed
     * @description Returns true if the mouse button was pressed this frame (since the last call to update).
     * @param {Object} button
     */
    Mouse.prototype.wasPressed = function (button) {
        return (this._buttons[button] && !this._lastbuttons[button]);
    };

    Mouse.prototype._handleUp = function (event) {
        // disable released button
        this._buttons[event.button] = false;

        // send 'mouseup' event
        this.fire("mouseup", {
            type: "mouseup",
            positionX: this._positionX,
            positionY: this._positionY,
            offsetX: this._offsetX,
            offsetY: this._offsetY,
            button: event.button,
            buttons: this._buttons,
            event: event
        });
    };

    Mouse.prototype._handleDown = function (event) {
        // Store which button has affected
        this._buttons[event.button] = true;

        this.fire("mousedown", {
            type: "mousedown",
            positionX: this._positionX,
            positionY: this._positionY,
            offsetX: this._offsetX,
            offsetY: this._offsetY,
            button: event.button,
            buttons: this._buttons,
            event: event
        });
    };

    Mouse.prototype._handleMove = function (event) {
        var type = "mousemove";

        if(this._buttons[pc.input.MOUSE_BUTTON_LEFT] ||
                this._buttons[pc.input.MOUSE_BUTTON_MIDDLE] ||
                this._buttons[pc.input.MOUSE_BUTTON_RIGHT]) {
                type = "mousedrag";
        }

        // Calculate the mouse movement
        this._deltaX = event.clientX - this._positionX;
        this._deltaY = event.clientY - this._positionY;

        // Update the current position
        this._positionX = event.clientX;
        this._positionY = event.clientY;
        offset = pc.input.getOffsetCoords(event);
        this._offsetX = offset.x;
        this._offsetY = offset.y;

        this.fire(type, {
            type: type,
            positionX: this._positionX,
            positionY: this._positionY,
            offsetX: this._offsetX,
            offsetY: this._offsetY,
            deltaX: this._deltaX,
            deltaY: this._deltaY,
            buttons: this._buttons,
            event: event
        });
    };

    Mouse.prototype._handleWheel = function (event) {
        // Store the wheel movement
        if(event.wheelDelta) {
            this.deltaWheel = event.wheelDelta / 120; // Convert to -1 to 1
        } else {
            this.deltaWheel = event.detail / -3; // Convert to -1 to 1
        }

        this.fire("mousewheel", {
            type: "mousewheel",
            positionX: this._positionX,
            positionY: this._positionY,
            offsetX: this._offsetX,
            offsetY: this._offsetY,
            deltaWheel: this.deltaWheel,
            buttons: this._buttons,
            event: event
        });
    };

    // Public Interface
    return  {
        /** mouseup event name */
        EVENT_MOUSE_UP: "mouseup",
        EVENT_MOUSE_DOWN: "mousedown",
        EVENT_MOUSE_MOVE: "mousemove",
        EVENT_MOUSE_DRAG: "mousedrag",
        EVENT_MOUSE_WHEEL: "mousewheel",

        MOUSE_BUTTON_NONE: -1,
        MOUSE_BUTTON_LEFT: 0,
        MOUSE_BUTTON_MIDDLE: 1,
        MOUSE_BUTTON_RIGHT: 2,
        Mouse: Mouse,

        /**
         * offsetX/Y are not cross-browser compatible so we generate a set of offset coords here
         * from pageX/Y which are the same on all browsers
         * @param {MouseEvent} event
         * @function
         * @name pc.input.getOffsetCoords
         */
        getOffsetCoords: function getOffsetCoords(event) {
            var coords = { x: 0, y: 0};

            var element = event.target ;
            var totalOffsetLeft = 0;
            var totalOffsetTop = 0 ;

            while (element.offsetParent)
            {
                totalOffsetLeft += element.offsetLeft;
                totalOffsetTop += element.offsetTop;
                element = element.offsetParent;
            }
            coords.x = event.pageX - totalOffsetLeft;
            coords.y = event.pageY - totalOffsetTop;

            return coords;
        }
    };
} ());

<commit_msg>Added pc.input.MouseEvent with documentation. MouseEvent object now has x,y fields instead of offsetX, offsetY. MouseEvent object no longer has positionX, positionY fields.<commit_after>pc.extend(pc.input, function () {

    /**
     * @name pc.input.MouseEvent
     * @class The object passed into Mouse Event handlers
     * @params {Object} [options] Data used to initialize the fields of the Event. See the fields for details
     */
    var MouseEvent = function (options) {
        options = options || {};
        /**
         * @field
         * @name pc.input.MouseEvent#type
         * @description Type of the mouse event: pc.input.EVENT_MOUSE_UP, pc.input.EVENT_MOUSE_DOWN, pc.input.EVENT_MOUSE_MOVE, pc.input.EVENT_MOUSE_DRAG, pc.input.EVENT_MOUSE_WHEEL
         */
        this.type = options.type || "";
        //this.positionX = options.positionX || 0;
        //this.positionY = options.positionY || 0;

        /**
         * @field
         * @name pc.input.MouseEvent#x
         * @description Horizontal co-ordinate of the event, relative to the DOM Element the Mouse object is attached to, often the canvas element.
         */
        this.x = options.x || 0;
        /**
         * @field
         * @name pc.input.MouseEvent#y
         * @description Vertical co-ordinate of the event, relative to the DOM Element the Mouse object is attached to, often the canvas element.
         */
        this.y = options.y || 0;

        /**
         * @field
         * @name pc.input.MouseEvent#deltaX
         * @description Change in horizonal co-ordinate value since the last event
         */
        this.deltaX = options.deltaX || 0;
        /**
         * @field
         * @name pc.input.MouseEvent#deltaY
         * @description Change in vertical co-ordinate value since the last event
         */
        this.deltaY = options.deltaY || 0;

        /**
         * @field
         * @name pc.input.MouseEvent#deltaWheel
         * @description Change in value of the mouse wheel since the last event. This is a normalized value in the range -1 to 1.
         */
        this.deltaWheel = options.deltaWheel || 0;

        /**
         * @field
         * @name pc.input.MouseEvent#button
         * @description The individual button to which the event refers. Only valid for pc.input.EVENT_MOUSE_UP and pc.input.EVENT_MOUSE_DOWN
         */
        this.button = options.button || pc.input.MOUSE_BUTTON_NONE;

        /**
         * @field
         * @name pc.input.MouseEvent#buttons
         * @description Boolean array of button states. A value of true indicates the button is currently pressed.
         * The array is in this order [pc.input.MOUSE_BUTTON_LEFT, pc.input.MOUSE_BUTTON_MIDDLE, pc.input.MOUSE_BUTTON_RIGHT]
         */
        this.buttons = options.buttons || [false, false, false];

        /**
         * @field
         * @name pc.input.MouseEvent#event
         * @description The original DOM MouseEvent
         */
        this.event = options.event || null;
    };
    /**
     * Create a new Mouse object
     * @class Capture and respond to mouse events.
     * @param {DOMElement} [element] The DOMElement that the mouse events are attached to
     * @name pc.input.Mouse
     */
    var Mouse = function(element) {
            // Clear the mouse state
            this._positionY    = 0;
            this._positionX    = 0;
            this._offsetX      = 0;
            this._offsetY      = 0;
            this._deltaX       = 0;
            this._deltaY       = 0;
            this._buttons      = [false,false,false];
            this._lastbuttons  = [];

            this._upHandler = pc.callback(this, this._handleUp);
            this._downHandler = pc.callback(this, this._handleDown);
            this._moveHandler = pc.callback(this, this._handleMove);
            this._wheelHandler = pc.callback(this, this._handleWheel);
            this._contextMenuHandler = function (event) { event.preventDefault(); };

            this._element = null;

            if(element) {
                this.attach(element);
            }

            // Add events
            pc.extend(this, pc.events);
        };

    /**
     * @function
     * @name pc.input.Mouse#attach
     * @description Attach mouse events to a DOMElement.
     * @param {Object} element
     */
    Mouse.prototype.attach = function (element) {
        // Store which DOM element the mouse is handling
        this._element = element;

        this._element.addEventListener("mouseup", this._upHandler, false);
        this._element.addEventListener("mousedown", this._downHandler, false);
        this._element.addEventListener("mousemove", this._moveHandler, false);
        this._element.addEventListener("mousewheel", this._wheelHandler, false); // WekKit
        this._element.addEventListener("DOMMouseScroll", this._wheelHandler, false); // Gecko
    };

    /**
     * @function
     * @name pc.input.Mouse#detach
     * @description Remove mouse events from the DOMElement
     */
    Mouse.prototype.detach = function () {
        this._element.removeEventListener("mouseup", this._upHandler);
        this._element.removeEventListener("mousedown", this._downHandler);
        this._element.removeEventListener("mousemove", this._moveHandler);
        this._element.removeEventListener("mousewheel", this._wheelHandler); // WekKit
        this._element.removeEventListener("DOMMouseScroll", this._wheelHandler); // Gecko

        this._element = null;
    };

    /**
     * @function
     * @name pc.input.Mouse#disableContextMenu
     * @description Disable the context menu usually activated with right-click
     */
    Mouse.prototype.disableContextMenu = function () {
        this._element.addEventListener("contextmenu", this._contextMenuHandler);
    };

    /**
     * @function
     * @name pc.input.Mouse#enableContextMenu
     * @description Enable the context menu usually activated with right-click. This option is active by default.
     */
    Mouse.prototype.enableContextMenu = function () {
        this._element.removeEventListener("contextmenu", this._contextMenuHandler);
    };

    /**
     * @function
     * @name pc.input.Mouse#update
     * @description Update method, should be called once per frame
     * @param {Object} dt
     */
    Mouse.prototype.update = function (dt) {
        // Copy current button state
        this._lastbuttons = this._buttons.slice(0);
    };

    /**
     * @function
     * @name pc.input.Mouse#isPressed
     * @description Returns true if the mouse button is currently pressed
     * @param {Object} button
     */
    Mouse.prototype.isPressed = function (button) {
        return this._buttons[button];
    };

    /**
     * @function
     * @name pc.input.Mouse#wasPressed
     * @description Returns true if the mouse button was pressed this frame (since the last call to update).
     * @param {Object} button
     */
    Mouse.prototype.wasPressed = function (button) {
        return (this._buttons[button] && !this._lastbuttons[button]);
    };

    Mouse.prototype._handleUp = function (event) {
        // disable released button
        this._buttons[event.button] = false;

        // send 'mouseup' event
        this.fire(pc.input.EVENT_MOUSE_UP, new MouseEvent({
            type: pc.input.EVENT_MOUSE_UP,
            positionX: this._positionX,
            positionY: this._positionY,
            x: this._offsetX,
            y: this._offsetY,
            button: event.button,
            buttons: this._buttons,
            event: event
        }));
    };

    Mouse.prototype._handleDown = function (event) {
        // Store which button has affected
        this._buttons[event.button] = true;

        this.fire(pc.input.EVENT_MOUSE_DOWN, new MouseEvent({
            type: pc.input.EVENT_MOUSE_DOWN,
            positionX: this._positionX,
            positionY: this._positionY,
            x: this._offsetX,
            y: this._offsetY,
            button: event.button,
            buttons: this._buttons,
            event: event
        }));
    };

    Mouse.prototype._handleMove = function (event) {
        type = pc.input.EVENT_MOUSE_MOVE;

        // If button is down, change to a drag event.
        if(this._buttons[pc.input.MOUSE_BUTTON_LEFT] ||
                this._buttons[pc.input.MOUSE_BUTTON_MIDDLE] ||
                this._buttons[pc.input.MOUSE_BUTTON_RIGHT]) {
                type = pc.input.EVENT_MOUSE_DRAG;
        }

        // Calculate the mouse movement
        this._deltaX = event.clientX - this._positionX;
        this._deltaY = event.clientY - this._positionY;

        // Update the current position
        this._positionX = event.clientX;
        this._positionY = event.clientY;
        offset = pc.input.getOffsetCoords(event);
        this._offsetX = offset.x;
        this._offsetY = offset.y;

        this.fire(type, new MouseEvent({
            type: type,
            positionX: this._positionX,
            positionY: this._positionY,
            x: this._offsetX,
            y: this._offsetY,
            deltaX: this._deltaX,
            deltaY: this._deltaY,
            buttons: this._buttons,
            event: event
        }));
    };

    Mouse.prototype._handleWheel = function (event) {
        // Store the wheel movement
        if(event.wheelDelta) {
            this.deltaWheel = event.wheelDelta / 120; // Convert to -1 to 1
        } else {
            this.deltaWheel = event.detail / -3; // Convert to -1 to 1
        }

        this.fire(pc.input.EVENT_MOUSE_WHEEL, new MouseEvent({
            type: pc.input.EVENT_MOUSE_WHEEL,
            positionX: this._positionX,
            positionY: this._positionY,
            x: this._offsetX,
            y: this._offsetY,
            deltaWheel: this.deltaWheel,
            buttons: this._buttons,
            event: event
        }));
    };

    // Public Interface
    return  {
        /** mouseup event name */
        EVENT_MOUSE_UP: "mouseup",
        EVENT_MOUSE_DOWN: "mousedown",
        EVENT_MOUSE_MOVE: "mousemove",
        EVENT_MOUSE_DRAG: "mousedrag",
        EVENT_MOUSE_WHEEL: "mousewheel",

        MOUSE_BUTTON_NONE: -1,
        MOUSE_BUTTON_LEFT: 0,
        MOUSE_BUTTON_MIDDLE: 1,
        MOUSE_BUTTON_RIGHT: 2,
        Mouse: Mouse,
        MouseEvent: MouseEvent,
        /**
         * offsetX/Y are not cross-browser compatible so we generate a set of offset coords here
         * from pageX/Y which are the same on all browsers
         * @param {MouseEvent} event
         * @function
         * @name pc.input.getOffsetCoords
         */
        getOffsetCoords: function getOffsetCoords(event) {
            var coords = { x: 0, y: 0};

            var element = event.target ;
            var totalOffsetLeft = 0;
            var totalOffsetTop = 0 ;

            while (element.offsetParent)
            {
                totalOffsetLeft += element.offsetLeft;
                totalOffsetTop += element.offsetTop;
                element = element.offsetParent;
            }
            coords.x = event.pageX - totalOffsetLeft;
            coords.y = event.pageY - totalOffsetTop;

            return coords;
        }
    };
} ());

<|endoftext|>


<commit_before>/* global IntlPolyfill, Intl */
"use strict";

var packageName = "andylash:intljs";

var loadedLocales = { 'en-US': true };

/**
 * Dynamically load locale data from the server
 * @param  {String} locale name of locale to load
 * @param {Function} callback call this function when the load is complete with standard (error) params
 */
IntlPolyfill.__loadLocaleData = function(locale, callback) {
  //Safai doesn't capitalize the country part.  UGH, so normalizing that here
  var parts = locale.match(/(.+-)([a-zA-Z]+)$/);
  locale = parts[1] + parts[2].toUpperCase();

  if (loadedLocales[locale]) {
    //already loaded, exit happily
    callback && callback(undefined);
    return;
  }
  var fixedPackageName = packageName.replace(/:/, '_');

  var url = Meteor.absoluteUrl();
  var localeUrl = url + 'packages/' + fixedPackageName + '/Intl.js/locale-data/json/' + locale + '.json';
  console.log(packageName + ": loading locale from: " + localeUrl);
  HTTP.get(localeUrl, function(error, results) {
    if (error) {
      console.error(packageName + ": failed to load locale: " + locale, error);
      callback && callback(error);
    } else {
      var data = EJSON.parse(results.content);
      console.log(packageName + ": succeeeded in loading locale: " + locale);
      IntlPolyfill.__addLocaleData(data);
      loadedLocales[locale] = true;
      callback && callback(undefined);
    }

  });
};

if (!Intl.__loadLocaleData) {
  //if the method does not appear, that means the polyfill is NOT being used, let's create a dummy function
  Intl.__loadLocaleData = function() {};
}
<commit_msg>Loader should better handle different locale formats<commit_after>/* global IntlPolyfill, Intl */
"use strict";

var packageName = "andylash:intljs";

var loadedLocales = { 'en-US': true };

/**
 * Dynamically load locale data from the server
 * @param  {String} locale name of locale to load
 * @param {Function} callback call this function when the load is complete with standard (error) params
 */
IntlPolyfill.__loadLocaleData = function(locale, callback) {
  //Safai doesn't capitalize the country part.  UGH, so normalizing that here
  var parts = locale.match(/(.+-)([a-zA-Z]+)$/);
  if (parts && parts.length > 2) {
    locale = parts[1] + parts[2].toUpperCase();
  }

  if (loadedLocales[locale]) {
    //already loaded, exit happily
    callback && callback(undefined);
    return;
  }
  var fixedPackageName = packageName.replace(/:/, '_');

  var url = Meteor.absoluteUrl();
  var localeUrl = url + 'packages/' + fixedPackageName + '/Intl.js/locale-data/json/' + locale + '.json';
  console.log(packageName + ": loading locale from: " + localeUrl);
  HTTP.get(localeUrl, function(error, results) {
    if (error) {
      console.error(packageName + ": failed to load locale: " + locale, error);
      callback && callback(error);
    } else {
      var data = EJSON.parse(results.content);
      console.log(packageName + ": succeeeded in loading locale: " + locale);
      IntlPolyfill.__addLocaleData(data);
      loadedLocales[locale] = true;
      callback && callback(undefined);
    }

  });
};

if (!Intl.__loadLocaleData) {
  //if the method does not appear, that means the polyfill is NOT being used, let's create a dummy function
  Intl.__loadLocaleData = function() {};
}
<|endoftext|>


<commit_before>//Starting point of the application
const bodyParser = require('body-parser');
const express = require('express');
const http = require('http');
const morgan = require('morgan');
const mongoose = require('mongoose');
const app = express();
const router = require('./routes/index.js');

//App Setup
app.use(morgan('dev'));
app.use(bodyParser.json({type:'*/*'}));
router(app);

//Server Setup
const port = process.env.PORT || 3000;
const server = http.createServer(app);
server.listen(port,'0.0.0.0');
console.log('Server listening on: ', port);<commit_msg>Minor Bugfix<commit_after>//Starting point of the application
const bodyParser = require('body-parser');
const express = require('express');
const http = require('http');
const morgan = require('morgan');
const mongoose = require('mongoose');
const app = express();
const router = require('./routes/index.js');

//App Setup
app.use(morgan('dev'));
app.use(bodyParser.json({type:'*/*'}));
router(app);

//Server Setup
const port = process.env.PORT || 3000;
const server = http.createServer(app);
server.listen(port,'0.0.0.0');
console.log('Server listening on: ', port);
module.exports = server;<|endoftext|>


<commit_before>/* _TO_SVG_START_ */
fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {

  /**
   * Returns styles-string for svg-export
   * @return {String}
   */
  getSvgStyles: function() {

    var fill = this.fill
          ? (this.fill.toLive ? 'url(#SVGID_' + this.fill.id + ')' : this.fill)
          : 'none',

        stroke = this.stroke
          ? (this.stroke.toLive ? 'url(#SVGID_' + this.stroke.id + ')' : this.stroke)
          : 'none',

        strokeWidth = this.strokeWidth ? this.strokeWidth : '0',
        strokeDashArray = this.strokeDashArray ? this.strokeDashArray.join(' ') : '',
        strokeLineCap = this.strokeLineCap ? this.strokeLineCap : 'butt',
        strokeLineJoin = this.strokeLineJoin ? this.strokeLineJoin : 'miter',
        strokeMiterLimit = this.strokeMiterLimit ? this.strokeMiterLimit : '4',
        opacity = typeof this.opacity !== 'undefined' ? this.opacity : '1',

        visibility = this.visible ? '' : ' visibility: hidden;',
        filter = this.shadow && this.type !== 'text' ? 'filter: url(#SVGID_' + this.shadow.id + ');' : '';

    return [
      'stroke: ', stroke, '; ',
      'stroke-width: ', strokeWidth, '; ',
      'stroke-dasharray: ', strokeDashArray, '; ',
      'stroke-linecap: ', strokeLineCap, '; ',
      'stroke-linejoin: ', strokeLineJoin, '; ',
      'stroke-miterlimit: ', strokeMiterLimit, '; ',
      'fill: ', fill, '; ',
      'opacity: ', opacity, ';',
      filter,
      visibility
    ].join('');
  },

  /**
   * Returns transform-string for svg-export
   * @return {String}
   */
  getSvgTransform: function() {
    var toFixed = fabric.util.toFixed,
        angle = this.getAngle(),
        vpt = this.getViewportTransform(),
        center = fabric.util.transformPoint(this.getCenterPoint(), vpt),

        NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS,

        translatePart = 'translate(' +
                          toFixed(center.x, NUM_FRACTION_DIGITS) +
                          ' ' +
                          toFixed(center.y, NUM_FRACTION_DIGITS) +
                        ')',

        anglePart = angle !== 0
          ? (' rotate(' + toFixed(angle, NUM_FRACTION_DIGITS) + ')')
          : '',

        scalePart = (this.scaleX === 1 && this.scaleY === 1)
          ? '' :
          (' scale(' +
            toFixed(this.scaleX * vpt[0], NUM_FRACTION_DIGITS) +
            ' ' +
            toFixed(this.scaleY * vpt[3], NUM_FRACTION_DIGITS) +
          ')'),

        flipXPart = this.flipX ? 'matrix(-1 0 0 1 0 0) ' : '',

        flipYPart = this.flipY ? 'matrix(1 0 0 -1 0 0)' : '';

    return [
      translatePart, anglePart, scalePart, flipXPart, flipYPart
    ].join('');
  },

  /**
   * @private
   */
  _createBaseSVGMarkup: function() {
    var markup = [ ];

    if (this.fill && this.fill.toLive) {
      markup.push(this.fill.toSVG(this, false));
    }
    if (this.stroke && this.stroke.toLive) {
      markup.push(this.stroke.toSVG(this, false));
    }
    if (this.shadow) {
      markup.push(this.shadow.toSVG(this));
    }
    return markup;
  }
});
/* _TO_SVG_END_ */
<commit_msg>Fix ToSVG scaling<commit_after>/* _TO_SVG_START_ */
fabric.util.object.extend(fabric.Object.prototype, /** @lends fabric.Object.prototype */ {

  /**
   * Returns styles-string for svg-export
   * @return {String}
   */
  getSvgStyles: function() {

    var fill = this.fill
          ? (this.fill.toLive ? 'url(#SVGID_' + this.fill.id + ')' : this.fill)
          : 'none',

        stroke = this.stroke
          ? (this.stroke.toLive ? 'url(#SVGID_' + this.stroke.id + ')' : this.stroke)
          : 'none',

        strokeWidth = this.strokeWidth ? this.strokeWidth : '0',
        strokeDashArray = this.strokeDashArray ? this.strokeDashArray.join(' ') : '',
        strokeLineCap = this.strokeLineCap ? this.strokeLineCap : 'butt',
        strokeLineJoin = this.strokeLineJoin ? this.strokeLineJoin : 'miter',
        strokeMiterLimit = this.strokeMiterLimit ? this.strokeMiterLimit : '4',
        opacity = typeof this.opacity !== 'undefined' ? this.opacity : '1',

        visibility = this.visible ? '' : ' visibility: hidden;',
        filter = this.shadow && this.type !== 'text' ? 'filter: url(#SVGID_' + this.shadow.id + ');' : '';

    return [
      'stroke: ', stroke, '; ',
      'stroke-width: ', strokeWidth, '; ',
      'stroke-dasharray: ', strokeDashArray, '; ',
      'stroke-linecap: ', strokeLineCap, '; ',
      'stroke-linejoin: ', strokeLineJoin, '; ',
      'stroke-miterlimit: ', strokeMiterLimit, '; ',
      'fill: ', fill, '; ',
      'opacity: ', opacity, ';',
      filter,
      visibility
    ].join('');
  },

  /**
   * Returns transform-string for svg-export
   * @return {String}
   */
  getSvgTransform: function() {
    var toFixed = fabric.util.toFixed,
        angle = this.getAngle(),
        vpt = this.getViewportTransform(),
        center = fabric.util.transformPoint(this.getCenterPoint(), vpt),

        NUM_FRACTION_DIGITS = fabric.Object.NUM_FRACTION_DIGITS,

        translatePart = 'translate(' +
                          toFixed(center.x, NUM_FRACTION_DIGITS) +
                          ' ' +
                          toFixed(center.y, NUM_FRACTION_DIGITS) +
                        ')',

        anglePart = angle !== 0
          ? (' rotate(' + toFixed(angle, NUM_FRACTION_DIGITS) + ')')
          : '',

        scalePart = (this.scaleX === 1 && this.scaleY === 1 && vpt[0] === 1 && vpt[3] === 1)
          ? '' :
          (' scale(' +
            toFixed(this.scaleX * vpt[0], NUM_FRACTION_DIGITS) +
            ' ' +
            toFixed(this.scaleY * vpt[3], NUM_FRACTION_DIGITS) +
          ')'),

        flipXPart = this.flipX ? 'matrix(-1 0 0 1 0 0) ' : '',

        flipYPart = this.flipY ? 'matrix(1 0 0 -1 0 0)' : '';

    return [
      translatePart, anglePart, scalePart, flipXPart, flipYPart
    ].join('');
  },

  /**
   * @private
   */
  _createBaseSVGMarkup: function() {
    var markup = [ ];

    if (this.fill && this.fill.toLive) {
      markup.push(this.fill.toSVG(this, false));
    }
    if (this.stroke && this.stroke.toLive) {
      markup.push(this.stroke.toSVG(this, false));
    }
    if (this.shadow) {
      markup.push(this.shadow.toSVG(this));
    }
    return markup;
  }
});
/* _TO_SVG_END_ */
<|endoftext|>


<commit_before>/**
 * author: Alexander Lex - alex@seas.harvard.edu
 * author: Nils Gehlenborg - nils@hms.harvard.edu
 * author: Hendrik Srtobelt - strobelt@seas.harvard.edu.
 * author: Romain Vuillemot - romain.vuillemot@gmail.com
 */

var dataSetDescriptions;

$.when($.ajax({ url: 'datasets.json', dataType: 'json' })).then(function (data, textStatus, jqXHR) {
    loadDataSetDescriptions(data);
});

function loadDataSetDescriptions(dataSetList) {

    var descriptions = [];
    var descriptionDeferreds = [];

    // launch requests to load data set descriptions
    for (var i = 0; i < dataSetList.length; ++i) {
        console.log("Loading " + dataSetList[i])

        descriptionDeferreds.push(
            $.ajax({ url: dataSetList[i], dataType: 'json' })
        );
    }

    // when all requests have finished, process the responses
    $.when.apply($, descriptionDeferreds).then(
        function () {
            for (var j = 0; j < arguments.length; ++j) {
                var description = arguments[j][0];

                // preprend data file path (based on path to description in data set list)
                description.file = dataSetList[j].substring(0, dataSetList[j].lastIndexOf('/')) + '/' + description.file;

                descriptions.push(description);
            }

            load(descriptions);
        },
        function (object, status, error) {
            console.error('Unable to load ' + object.responseText);
            console.error(error.message);
        }
    );
}

function load(descriptions) {

    dataSetDescriptions = descriptions;

    // Variables from query string
    var queryParameters = {}, queryString = location.search.substring(1),
        re = /([^&=]+)=([^&]*)/g, m;

    // Creates a map with the query string parameters
    while (m = re.exec(queryString)) {
        queryParameters[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
    }

    queryParameters['dataset'] = parseInt(queryParameters['dataset']) || 0;

    var header = d3.select('#header');

    header.append('div').html('↓ # intersections.').attr({id: 'sortIntersect',
        class: 'myButton'});

    header.append('div').html('Group by set size.').attr({id: 'groupSetSize',
        class: 'myButton'});

    header.append('div').html('Group by Sets.').attr({id: 'groupSet',
        class: 'myButton'});

    header.append('div').html('Toggle Collapse of All Groups.').attr({id: 'collapseGroups',
        class: 'myButton'});

    var dataSelect = header.append('div').text('Choose Dataset');

    var select = dataSelect.append('select');
    select.on('change', change)
        .selectAll('option').data(dataSetDescriptions).enter().append('option')
        .attr('value', function (d, i) {
            return i;
        })
        .attr('id', 'dataSetSelector')
        .text(function (d) {
            return d.name + ' ' + '(' + getNumberOfSets(d) + ' sets, ' + getNumberOfAttributes(d) + ' attributes' + ')';
        })
        .property('selected', function (d, i) {
            return (i === queryParameters['dataset'])
        });

    loadDataSet(queryParameters['dataset']);
}

function loadDataSet(index) {
    processDataSet(dataSetDescriptions[index]);
}

function processDataSet(dataSetDescription) {
    d3.text(dataSetDescription.file, 'text/csv', function (data) {
        parseDataSet(data, dataSetDescription);
        run();
    });
}

function clearSelections() {
    selections = new SelectionList();
}

function createInitialSelection() {
    var selection = new Selection(allItems);
    var filterList = [];

    for (var a = 0; a < attributes.length - 1; ++a) {
        if (attributes[a].type === 'integer' || attributes[a].type === 'float') {
            filterList.push({ attributeId: a, id: "numericRange", parameters: { min: attributes[a].min, max: attributes[a].max }, uuid: Utilities.generateUuid() });
        }

        if (attributes[a].type === 'string' || attributes[a].type === 'id') {
            filterList.push({ attributeId: a, id: "stringRegex", parameters: { pattern: "." }, uuid: Utilities.generateUuid() });
        }
    }

    selection.filters = filterList;
    selections.addSelection(selection);
}

function run() {
    setUpSubSets();
    setUpGroupings();
    updateState();
    plot();
    plotSetSelection();
    createInitialSelection();
}

function getNumberOfSets(dataSetDescription) {
    var sets = 0;

    for (var i = 0; i < dataSetDescription.sets.length; ++i) {
        var setDefinitionBlock = dataSetDescription.sets[i];

        if (setDefinitionBlock.format === 'binary') {
            sets += setDefinitionBlock.end - setDefinitionBlock.start + 1;
        }
        else {
            console.error('Set definition format "' + setDefinitionBlock.format + '" not supported');
        }
    }

    return ( sets );
}

function getNumberOfAttributes(dataSetDescription) {
    return ( dataSetDescription.meta.length );
}

function getIdColumn(dataSetDescription) {
    for (var i = 0; i < dataSetDescription.meta.length; ++i) {
        if (dataSetDescription.meta[i].type === "id") {
            return dataSetDescription.meta[i].index;
        }
    }

    // id column not defined, assume 0
    return 0;
}

function parseDataSet(data, dataSetDescription) {

    var dsv = d3.dsv(dataSetDescription.separator, 'text/plain');

    // the raw set arrays
    var rawSets = [];
    var setNames = [];

    var file = dsv.parseRows(data);

    // the names of the sets are in the columns
    var header = file[dataSetDescription.header];

    // remove header
    file.splice(dataSetDescription.header, 1);

    // load set assignments
    var processedSetsCount = 0;
    for (var i = 0; i < dataSetDescription.sets.length; ++i) {
        var setDefinitionBlock = dataSetDescription.sets[i];

        if (setDefinitionBlock.format === 'binary') {
            var setDefinitionBlockLength = setDefinitionBlock.end - setDefinitionBlock.start + 1;

            // initialize the raw set arrays
            for (var setCount = 0; setCount < setDefinitionBlockLength; ++setCount) {
                rawSets.push(new Array());
            }

            var rows = file.map(function (row, rowIndex) {
                return row.map(function (value, columnIndex) {

                    if (columnIndex >= setDefinitionBlock.start && columnIndex <= setDefinitionBlock.end) {
                        var intValue = parseInt(value, 10);

                        if (isNaN(intValue)) {
                            console.error('Unable to convert "' + value + '" to integer (row ' + rowIndex + ', column ' + columnIndex + ')');
                        }

                        return intValue;
                    }

                    return null;
                });
            });
            // iterate over columns defined by this set definition block
            for (var r = 0; r < rows.length; r++) {
                // increment number of items in data set
                // only increment depth when we are processing the first set definition block (we will already iterate overall rows)
                if (i === 0) {
                    allItems.push(depth++);
                }

                for (var s = 0; s < setDefinitionBlockLength; ++s) {
                    rawSets[processedSetsCount + s].push(rows[r][setDefinitionBlock.start + s]);

                    if (r === 1) {
                        setNames.push(header[setDefinitionBlock.start + s]);
                    }
                }
            }

            processedSetsCount += setDefinitionBlockLength;
        }
        else {
            console.error('Set definition format "' + setDefinitionBlock.format + '" not supported');
        }
    }

    // initialize attribute data structure
    attributes.length = 0;
    for (var i = 0; i < dataSetDescription.meta.length; ++i) {
        var metaDefinition = dataSetDescription.meta[i];

        attributes.push({
            name: metaDefinition.name || header[metaDefinition.index],
            type: metaDefinition.type,
            values: [],
            sort: 1
        });
    }

    // add implicit attributes
    var setCountAttribute = {
        name: 'Set Count',
        type: 'integer',
        values: [],
        sort: 1,
        min: 0
    };

    for (var d = 0; d < depth; ++d) {
        var setCount = 0;
        for (var s = 0; s < rawSets.length; s++) {
            setCount += rawSets[s][d];
        }
        setCountAttribute.values[d] = setCount;
    }
    attributes.push(setCountAttribute);

    var setsAttribute = {
        name: 'Sets',
        type: 'sets',
        values: [],
        sort: 1
    };

    for (var d = 0; d < depth; ++d) {
        var setList = [];
        for (var s = 0; s < rawSets.length; s++) {
            if (rawSets[s][d] === 1) {
                setList.push(Math.floor(Math.pow(2, s)));
            }
        }
        setsAttribute.values[d] = setList;
    }
    attributes.push(setsAttribute);

    // load meta data
    for (var i = 0; i < dataSetDescription.meta.length; ++i) {
        var metaDefinition = dataSetDescription.meta[i];

        attributes[i].values = file.map(function (row, rowIndex) {
            var value = row[metaDefinition.index];
            switch (metaDefinition.type) {
                case 'integer':
                    var intValue = parseInt(value, 10);
                    if (isNaN(intValue)) {
                        console.error('Unable to convert "' + value + '" to integer.');
                        return NaN;
                    }
                    return intValue;
                case 'float':
                    var floatValue = parseFloat(value, 10);
                    if (isNaN(floatValue)) {
                        console.error('Unable to convert "' + value + '" to float.');
                        return NaN;
                    }
                    return floatValue;
                case 'id':
                // fall-through
                case 'string':
                // fall-through
                default:
                    return value;
            }

        });
    }

    // add meta data summary statistics
    for (var i = 0; i < attributes.length; ++i) {

        if (attributes[i].type === "float" || attributes[i].type === "integer") {
            // explictly defined attributes might have user-defined ranges
            if (i < dataSetDescription.meta.length) {
                attributes[i].min = dataSetDescription.meta[i].min || Math.min.apply(null, attributes[i].values);
                attributes[i].max = dataSetDescription.meta[i].max || Math.max.apply(null, attributes[i].values);
            }
            // implicitly defined attributes
            else {
                attributes[i].min = attributes[i].min || Math.min.apply(null, attributes[i].values);
                attributes[i].max = attributes[i].max || Math.max.apply(null, attributes[i].values);
            }
        }
    }

    var setID = 1;
    for (var i = 0; i < rawSets.length; i++) {
        var combinedSets = Array.apply(null, new Array(rawSets.length)).map(Number.prototype.valueOf, 0);
        combinedSets[i] = 1;
        var set = new Set(setID, setNames[i], combinedSets, rawSets[i]);
        setIdToSet[setID] = set;
        sets.push(set);
        if (i < nrDefaultSets) {
            set.isSelected = true;
            usedSets.push(set);
        }
        setID = setID << 1;
    }
}

function setUpSubSets() {

    combinations = Math.pow(2, usedSets.length) - 1;

    // the max value for the cut-off
    console.log("LENGTH = " + attributes[attributes.length - 2].max);
    for (var i = 0; i <= combinations; i++) {
        makeSubSet(i)
    }

    // dataRows = subSets.slice(0);

    // sort by size of set overlap
//    dataRows.sort(function (a, b) {
//        return b.setSize - a.setSize;
//    });

}

function setUpGroupings() {
    groupBySetSize();
    groupBySet();
}

function change() {
    sets.length = 0;
    subSets.length = 0;
    usedSets.length = 0;
    dataRows.length = 0;
    depth = 0;
    allItems.length = 0;
    attributes.length = 0;
    selectedAttributes = {};

    loadDataSet(this.options[this.selectedIndex].value);
    history.replaceState({}, 'Upset', window.location.origin + window.location.pathname + '?dataset=' + this.selectedIndex);

    clearSelections();

    console.log( selections.palette );
}

function updateSetContainment(set) {
    if (!set.isSelected) {
        set.isSelected = true;
        usedSets.push(set);
    }
    else {
        set.isSelected = false;

        var index = usedSets.indexOf(set);
        if (index > -1) {
            usedSets.splice(index, 1);
        }
    }
    subSets.length = 0;
    dataRows.length = 0;
    setUpSubSets();
    setUpGroupings();
    updateState();
    plot();
    plotSetSelection();

}

function addSet(set) {

}

function removeSet(set) {
    console.log('Not implemented');
}
<commit_msg>Activating initial selection.<commit_after>/**
 * author: Alexander Lex - alex@seas.harvard.edu
 * author: Nils Gehlenborg - nils@hms.harvard.edu
 * author: Hendrik Srtobelt - strobelt@seas.harvard.edu.
 * author: Romain Vuillemot - romain.vuillemot@gmail.com
 */

var dataSetDescriptions;

$.when($.ajax({ url: 'datasets.json', dataType: 'json' })).then(function (data, textStatus, jqXHR) {
    loadDataSetDescriptions(data);
});

function loadDataSetDescriptions(dataSetList) {

    var descriptions = [];
    var descriptionDeferreds = [];

    // launch requests to load data set descriptions
    for (var i = 0; i < dataSetList.length; ++i) {
        console.log("Loading " + dataSetList[i])

        descriptionDeferreds.push(
            $.ajax({ url: dataSetList[i], dataType: 'json' })
        );
    }

    // when all requests have finished, process the responses
    $.when.apply($, descriptionDeferreds).then(
        function () {
            for (var j = 0; j < arguments.length; ++j) {
                var description = arguments[j][0];

                // preprend data file path (based on path to description in data set list)
                description.file = dataSetList[j].substring(0, dataSetList[j].lastIndexOf('/')) + '/' + description.file;

                descriptions.push(description);
            }

            load(descriptions);
        },
        function (object, status, error) {
            console.error('Unable to load ' + object.responseText);
            console.error(error.message);
        }
    );
}

function load(descriptions) {

    dataSetDescriptions = descriptions;

    // Variables from query string
    var queryParameters = {}, queryString = location.search.substring(1),
        re = /([^&=]+)=([^&]*)/g, m;

    // Creates a map with the query string parameters
    while (m = re.exec(queryString)) {
        queryParameters[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
    }

    queryParameters['dataset'] = parseInt(queryParameters['dataset']) || 0;

    var header = d3.select('#header');

    header.append('div').html('↓ # intersections.').attr({id: 'sortIntersect',
        class: 'myButton'});

    header.append('div').html('Group by set size.').attr({id: 'groupSetSize',
        class: 'myButton'});

    header.append('div').html('Group by Sets.').attr({id: 'groupSet',
        class: 'myButton'});

    header.append('div').html('Toggle Collapse of All Groups.').attr({id: 'collapseGroups',
        class: 'myButton'});

    var dataSelect = header.append('div').text('Choose Dataset');

    var select = dataSelect.append('select');
    select.on('change', change)
        .selectAll('option').data(dataSetDescriptions).enter().append('option')
        .attr('value', function (d, i) {
            return i;
        })
        .attr('id', 'dataSetSelector')
        .text(function (d) {
            return d.name + ' ' + '(' + getNumberOfSets(d) + ' sets, ' + getNumberOfAttributes(d) + ' attributes' + ')';
        })
        .property('selected', function (d, i) {
            return (i === queryParameters['dataset'])
        });

    loadDataSet(queryParameters['dataset']);
}

function loadDataSet(index) {
    processDataSet(dataSetDescriptions[index]);
}

function processDataSet(dataSetDescription) {
    d3.text(dataSetDescription.file, 'text/csv', function (data) {
        parseDataSet(data, dataSetDescription);
        run();
    });
}

function clearSelections() {
    selections = new SelectionList();
}

function createInitialSelection() {
    var selection = new Selection(allItems);
    var filterList = [];

    for (var a = 0; a < attributes.length - 1; ++a) {
        if (attributes[a].type === 'integer' || attributes[a].type === 'float') {
            filterList.push({ attributeId: a, id: "numericRange", parameters: { min: attributes[a].min, max: attributes[a].max }, uuid: Utilities.generateUuid() });
        }

        if (attributes[a].type === 'string' || attributes[a].type === 'id') {
            filterList.push({ attributeId: a, id: "stringRegex", parameters: { pattern: "." }, uuid: Utilities.generateUuid() });
        }
    }

    selection.filters = filterList;
    selections.addSelection(selection);
    selections.setActive( selection );
}

function run() {
    setUpSubSets();
    setUpGroupings();
    updateState();
    plot();
    plotSetSelection();
    createInitialSelection();
}

function getNumberOfSets(dataSetDescription) {
    var sets = 0;

    for (var i = 0; i < dataSetDescription.sets.length; ++i) {
        var setDefinitionBlock = dataSetDescription.sets[i];

        if (setDefinitionBlock.format === 'binary') {
            sets += setDefinitionBlock.end - setDefinitionBlock.start + 1;
        }
        else {
            console.error('Set definition format "' + setDefinitionBlock.format + '" not supported');
        }
    }

    return ( sets );
}

function getNumberOfAttributes(dataSetDescription) {
    return ( dataSetDescription.meta.length );
}

function getIdColumn(dataSetDescription) {
    for (var i = 0; i < dataSetDescription.meta.length; ++i) {
        if (dataSetDescription.meta[i].type === "id") {
            return dataSetDescription.meta[i].index;
        }
    }

    // id column not defined, assume 0
    return 0;
}

function parseDataSet(data, dataSetDescription) {

    var dsv = d3.dsv(dataSetDescription.separator, 'text/plain');

    // the raw set arrays
    var rawSets = [];
    var setNames = [];

    var file = dsv.parseRows(data);

    // the names of the sets are in the columns
    var header = file[dataSetDescription.header];

    // remove header
    file.splice(dataSetDescription.header, 1);

    // load set assignments
    var processedSetsCount = 0;
    for (var i = 0; i < dataSetDescription.sets.length; ++i) {
        var setDefinitionBlock = dataSetDescription.sets[i];

        if (setDefinitionBlock.format === 'binary') {
            var setDefinitionBlockLength = setDefinitionBlock.end - setDefinitionBlock.start + 1;

            // initialize the raw set arrays
            for (var setCount = 0; setCount < setDefinitionBlockLength; ++setCount) {
                rawSets.push(new Array());
            }

            var rows = file.map(function (row, rowIndex) {
                return row.map(function (value, columnIndex) {

                    if (columnIndex >= setDefinitionBlock.start && columnIndex <= setDefinitionBlock.end) {
                        var intValue = parseInt(value, 10);

                        if (isNaN(intValue)) {
                            console.error('Unable to convert "' + value + '" to integer (row ' + rowIndex + ', column ' + columnIndex + ')');
                        }

                        return intValue;
                    }

                    return null;
                });
            });
            // iterate over columns defined by this set definition block
            for (var r = 0; r < rows.length; r++) {
                // increment number of items in data set
                // only increment depth when we are processing the first set definition block (we will already iterate overall rows)
                if (i === 0) {
                    allItems.push(depth++);
                }

                for (var s = 0; s < setDefinitionBlockLength; ++s) {
                    rawSets[processedSetsCount + s].push(rows[r][setDefinitionBlock.start + s]);

                    if (r === 1) {
                        setNames.push(header[setDefinitionBlock.start + s]);
                    }
                }
            }

            processedSetsCount += setDefinitionBlockLength;
        }
        else {
            console.error('Set definition format "' + setDefinitionBlock.format + '" not supported');
        }
    }

    // initialize attribute data structure
    attributes.length = 0;
    for (var i = 0; i < dataSetDescription.meta.length; ++i) {
        var metaDefinition = dataSetDescription.meta[i];

        attributes.push({
            name: metaDefinition.name || header[metaDefinition.index],
            type: metaDefinition.type,
            values: [],
            sort: 1
        });
    }

    // add implicit attributes
    var setCountAttribute = {
        name: 'Set Count',
        type: 'integer',
        values: [],
        sort: 1,
        min: 0
    };

    for (var d = 0; d < depth; ++d) {
        var setCount = 0;
        for (var s = 0; s < rawSets.length; s++) {
            setCount += rawSets[s][d];
        }
        setCountAttribute.values[d] = setCount;
    }
    attributes.push(setCountAttribute);

    var setsAttribute = {
        name: 'Sets',
        type: 'sets',
        values: [],
        sort: 1
    };

    for (var d = 0; d < depth; ++d) {
        var setList = [];
        for (var s = 0; s < rawSets.length; s++) {
            if (rawSets[s][d] === 1) {
                setList.push(Math.floor(Math.pow(2, s)));
            }
        }
        setsAttribute.values[d] = setList;
    }
    attributes.push(setsAttribute);

    // load meta data
    for (var i = 0; i < dataSetDescription.meta.length; ++i) {
        var metaDefinition = dataSetDescription.meta[i];

        attributes[i].values = file.map(function (row, rowIndex) {
            var value = row[metaDefinition.index];
            switch (metaDefinition.type) {
                case 'integer':
                    var intValue = parseInt(value, 10);
                    if (isNaN(intValue)) {
                        console.error('Unable to convert "' + value + '" to integer.');
                        return NaN;
                    }
                    return intValue;
                case 'float':
                    var floatValue = parseFloat(value, 10);
                    if (isNaN(floatValue)) {
                        console.error('Unable to convert "' + value + '" to float.');
                        return NaN;
                    }
                    return floatValue;
                case 'id':
                // fall-through
                case 'string':
                // fall-through
                default:
                    return value;
            }

        });
    }

    // add meta data summary statistics
    for (var i = 0; i < attributes.length; ++i) {

        if (attributes[i].type === "float" || attributes[i].type === "integer") {
            // explictly defined attributes might have user-defined ranges
            if (i < dataSetDescription.meta.length) {
                attributes[i].min = dataSetDescription.meta[i].min || Math.min.apply(null, attributes[i].values);
                attributes[i].max = dataSetDescription.meta[i].max || Math.max.apply(null, attributes[i].values);
            }
            // implicitly defined attributes
            else {
                attributes[i].min = attributes[i].min || Math.min.apply(null, attributes[i].values);
                attributes[i].max = attributes[i].max || Math.max.apply(null, attributes[i].values);
            }
        }
    }

    var setID = 1;
    for (var i = 0; i < rawSets.length; i++) {
        var combinedSets = Array.apply(null, new Array(rawSets.length)).map(Number.prototype.valueOf, 0);
        combinedSets[i] = 1;
        var set = new Set(setID, setNames[i], combinedSets, rawSets[i]);
        setIdToSet[setID] = set;
        sets.push(set);
        if (i < nrDefaultSets) {
            set.isSelected = true;
            usedSets.push(set);
        }
        setID = setID << 1;
    }
}

function setUpSubSets() {

    combinations = Math.pow(2, usedSets.length) - 1;

    // the max value for the cut-off
    console.log("LENGTH = " + attributes[attributes.length - 2].max);
    for (var i = 0; i <= combinations; i++) {
        makeSubSet(i)
    }

    // dataRows = subSets.slice(0);

    // sort by size of set overlap
//    dataRows.sort(function (a, b) {
//        return b.setSize - a.setSize;
//    });

}

function setUpGroupings() {
    groupBySetSize();
    groupBySet();
}

function change() {
    sets.length = 0;
    subSets.length = 0;
    usedSets.length = 0;
    dataRows.length = 0;
    depth = 0;
    allItems.length = 0;
    attributes.length = 0;
    selectedAttributes = {};

    loadDataSet(this.options[this.selectedIndex].value);
    history.replaceState({}, 'Upset', window.location.origin + window.location.pathname + '?dataset=' + this.selectedIndex);

    clearSelections();
}

function updateSetContainment(set) {
    if (!set.isSelected) {
        set.isSelected = true;
        usedSets.push(set);
    }
    else {
        set.isSelected = false;

        var index = usedSets.indexOf(set);
        if (index > -1) {
            usedSets.splice(index, 1);
        }
    }
    subSets.length = 0;
    dataRows.length = 0;
    setUpSubSets();
    setUpGroupings();
    updateState();
    plot();
    plotSetSelection();

}

function addSet(set) {

}

function removeSet(set) {
    console.log('Not implemented');
}
<|endoftext|>


<commit_before>/* eslint max-len:0 */
define(function(require, exports) {
    'use strict';

    var partials  = require('handlebars').partials;
    require('./helpers/handlebars.partials');
    var paragraph = partials.paragraph;
    var code      = partials.code;
    var gist      = partials.gist;
    var demo      = partials.demo;
    var image     = partials.image;
    var banner    = partials.banner;
    var quote     = partials.quote;
    var list      = partials.list;

    exports.feed = [
        {
            type: 'post',
            postId: '1',
            name: 'foo',
            date: '201609291800',
            title: 'Really Long Test Announcement #1',
            subtitle: 'This is a test of the news section',
            body: [
                paragraph('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.')
            ]
        },
        {
            type: 'post',
            postId: '2',
            name: 'bar',
            date: '20160926',
            title: 'Test Announcement #2',
            subtitle: 'This is a test of the news section',
            body: [
                paragraph('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'),
                paragraph('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'),
                paragraph('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.')
            ]
        },
        {
            type: 'post',
            postId: '3',
            name: 'baz',
            date: '20160927',
            title: 'Test Announcement #3',
            subtitle: 'This is a test of the news section',
            body: [
                // banner('../assets/images/banners/clouds.jpg'),
                demo('boom'),
                gist('80b30714c33b197df0b6'),
                // banner('../assets/images/banners/corn.jpg'),
                code('var boom = \'dynamite\''),
                quote('If you are not growing, you are dying.'),
                code(
                    'function getArgs() {',
                    '\treturn Array.prototype.slice.apply(arguments);',
                    '}',
                    'var printArgs = _.flow(getArgs, console.log);',
                    '',
                    'printArgs(1, 2, 3); // [1, 2, 3]'
                ),
                paragraph('...that is some quote'),
                image(null, {height: 300}),
                banner('../assets/images/clouds.jpg'),
                list('List Title',
                    [
                        '[Google](https://google.com)',
                        'https://google.com',
                        'My favorite color is Red'
                    ]
                ),
                paragraph('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'),
                paragraph('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'),
                quote('Watashi no namae wa, Jason desu.'),
                image(null, {position: 'center bottom'}),
                paragraph('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.')
            ]
        }
    ];
    exports.code = [
        {
            order: 1,
            type: 'project',
            tags: ['yeoman', 'node', 'CLI', 'scaffold'],
            technology: 'yeoman',
            date: '',
            name: 'generator-omaha',
            url: 'https://github.com/omahajs/generator-omaha',
            title: 'Omaha Generator',
            subtitle: 'Yeoman generator for projects, web apps, and servers'
        },
        {
            order: 2,
            type: 'project',
            tags: ['eslint', 'linting', 'quality'],
            technology: 'eslint',
            date: '',
            name: 'eslint-config-omaha-prime-grade',
            url: 'https://github.com/omahajs/eslint-config-omaha-prime-grade',
            title: 'Code Quality Rules',
            subtitle: '"Prime Grade" ESLint Shareable Config'
        }
    ];
    exports.about = [
        {
            type: 'about',
            body: [
                paragraph('Omaha JS is about crafting sustainable, high-quality software with modern front-end technologies.  In simple terms, Omaha JS seeks to make it easier to write tested, linted, functional code.  With this simple mission in mind, we have some key ideals driving us:'),
                quote('Writing great code is a process that must be practiced.'),
                paragraph('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'),
                quote('The process of writing great code must be sustainable in order to be viable in real-world situations.'),
                paragraph('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'),
                quote('Writing great code is fun and rewarding.'),
                code(
                    'const STUFF = [',
                    '\t\'JavaScript\',',
                    '\t\'Node\',',
                    '\t\'HTML\',',
                    '\t\'CSS\'',
                    '];',
                    'const CODE_IS_FUN = STUFF',
                    '\t.map(isAwesome)',
                    '\t.every(x => (x === true));',
                    '',
                    'function isAwesome(thing) {',
                    '\treturn STUFF.includes(thing);',
                    '}',
                    '',
                    'console.log(CODE_IS_FUN);// true'
                ),
                paragraph('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'),
                list('Credits',
                    [
                        '[Nebraska Font by Daniel Heikkinen](http://www.dafont.com/nebraska.font)',
                        '[IcoMoon Icon font](http://www.icomoon.io)',
                        '[SVG Hero Patterns](http://www.heropatterns.com/)',
                        '[highlight.js (syntax highlighting for code blocks)](https://highlightjs.org/)'
                    ]
                ),
                image('../assets/images/cornjs.png', {height: 250})
            ]
        }
    ];
});
<commit_msg>More about snippet tweaks<commit_after>/* eslint max-len:0 */
define(function(require, exports) {
    'use strict';

    var partials  = require('handlebars').partials;
    require('./helpers/handlebars.partials');
    var paragraph = partials.paragraph;
    var code      = partials.code;
    var gist      = partials.gist;
    var demo      = partials.demo;
    var image     = partials.image;
    var banner    = partials.banner;
    var quote     = partials.quote;
    var list      = partials.list;

    exports.feed = [
        {
            type: 'post',
            postId: '1',
            name: 'foo',
            date: '201609291800',
            title: 'Really Long Test Announcement #1',
            subtitle: 'This is a test of the news section',
            body: [
                paragraph('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.')
            ]
        },
        {
            type: 'post',
            postId: '2',
            name: 'bar',
            date: '20160926',
            title: 'Test Announcement #2',
            subtitle: 'This is a test of the news section',
            body: [
                paragraph('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'),
                paragraph('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'),
                paragraph('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.')
            ]
        },
        {
            type: 'post',
            postId: '3',
            name: 'baz',
            date: '20160927',
            title: 'Test Announcement #3',
            subtitle: 'This is a test of the news section',
            body: [
                // banner('../assets/images/banners/clouds.jpg'),
                demo('boom'),
                gist('80b30714c33b197df0b6'),
                // banner('../assets/images/banners/corn.jpg'),
                code('var boom = \'dynamite\''),
                quote('If you are not growing, you are dying.'),
                code(
                    'function getArgs() {',
                    '\treturn Array.prototype.slice.apply(arguments);',
                    '}',
                    'var printArgs = _.flow(getArgs, console.log);',
                    '',
                    'printArgs(1, 2, 3); // [1, 2, 3]'
                ),
                paragraph('...that is some quote'),
                image(null, {height: 300}),
                banner('../assets/images/clouds.jpg'),
                list('List Title',
                    [
                        '[Google](https://google.com)',
                        'https://google.com',
                        'My favorite color is Red'
                    ]
                ),
                paragraph('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'),
                paragraph('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'),
                quote('Watashi no namae wa, Jason desu.'),
                image(null, {position: 'center bottom'}),
                paragraph('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.')
            ]
        }
    ];
    exports.code = [
        {
            order: 1,
            type: 'project',
            tags: ['yeoman', 'node', 'CLI', 'scaffold'],
            technology: 'yeoman',
            date: '',
            name: 'generator-omaha',
            url: 'https://github.com/omahajs/generator-omaha',
            title: 'Omaha Generator',
            subtitle: 'Yeoman generator for projects, web apps, and servers'
        },
        {
            order: 2,
            type: 'project',
            tags: ['eslint', 'linting', 'quality'],
            technology: 'eslint',
            date: '',
            name: 'eslint-config-omaha-prime-grade',
            url: 'https://github.com/omahajs/eslint-config-omaha-prime-grade',
            title: 'Code Quality Rules',
            subtitle: '"Prime Grade" ESLint Shareable Config'
        }
    ];
    exports.about = [
        {
            type: 'about',
            body: [
                paragraph('Omaha JS is about crafting sustainable, high-quality software with modern front-end technologies.  In simple terms, Omaha JS seeks to make it easier to write tested, linted, functional code.  With this simple mission in mind, we have some key ideals driving us:'),
                quote('Writing great code is a process that must be practiced.'),
                paragraph('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'),
                quote('The process of writing great code must be sustainable in order to be viable in real-world situations.'),
                paragraph('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'),
                quote('Writing great code is fun and rewarding.'),
                code(
                    'const _ = require(\'lodash\');',
                    'const STUFF = [',
                    '\t\'JavaScript\',',
                    '\t\'Node\',',
                    '\t\'HTML\',',
                    '\t\'CSS\'',
                    '];',
                    'let isAwesome = _.partial(_.includes, STUFF);',
                    'const CODE_IS_FUN = STUFF',
                    '\t.map(isAwesome)',
                    '\t.every(x => (x === true));',
                    '',
                    'console.log(CODE_IS_FUN);// true'
                ),
                paragraph('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'),
                list('Credits',
                    [
                        '[Nebraska Font by Daniel Heikkinen](http://www.dafont.com/nebraska.font)',
                        '[IcoMoon Icon font](http://www.icomoon.io)',
                        '[SVG Hero Patterns](http://www.heropatterns.com/)',
                        '[highlight.js (syntax highlighting for code blocks)](https://highlightjs.org/)'
                    ]
                ),
                image('../assets/images/cornjs.png', {height: 250})
            ]
        }
    ];
});
<|endoftext|>