<commit_before>/**
 *  KitScript - A User Script Safari Extension
 *
 *  Greasemonkey.js - Javascript file containing Greasemonkey classes
 *  (by Prototype.js) used globally in the extension & implementing core
 *  Greasemonkey API.
 *
 *  @author Seraf Dos Santos <webmaster@cyb3r.ca>
 *  @copyright 2011-2012 Seraf Dos Santos - All rights reserved.
 *  @license MIT License
 *  @version 0.1
 */

/**
 *  KSGMException (KitScript Greasemonkey Exception Class)
 */
var KSGMException = Class.create({

    initialize: function (msg) {

        this._msg = msg;
    },
    getMessage: function () {

        return this._msg;
    }
});

/**
 *  KSGreasemonkeyMetadata (KitScript Greasemonkey Metadata Class)
 */
var KSGreasemonkeyMetadata = Class.create({

    initialize: function () {

        this._isHeaderValid = false;
        this._script = "";
    },
    loadScript: function (scriptStr) {

        this._script = scriptStr;

        if (!this.isHeaderValid()) {

            throw new KSGMException("User script metadata block is invalid.");
        }
    },
    isHeaderValid: function () {

        this._isValid = /[\/]{2} ==UserScript==[^=]*==[\/]{1}UserScript==/m.test(this._script);

        return this._isValid;
    },

    /**
     *  =================
     *  SUPPORTED IN v0.1
     *  =================
     */

    /**
     *  @name string – KS Mandatory
     *
     *  - The combination of namespace and name is the unique identifier for a Greasemonkey script.
     *
     *  @returns string
     */
    getName: function () {

        if (/[\/]{2} \@name (.*)/g.test(this._script) === true) {

            var matches = /[\/]{2} \@name (.*)/g.exec(this._script);

            return matches[1];
        } else {

            throw new KSGMException("No mandatory @name in metadata block.");
        }
    },
    /**
     *  @namespace string – KS Mandatory
     *
     *  - The combination of namespace and name is the unique identifier for a Greasemonkey script.
     *
     *  @returns string
     */
    getNamespace: function () {

        if (/[\/]{2} \@namespace (.*)/g.test(this._script) === true) {

            var matches = /[\/]{2} \@namespace (.*)/g.exec(this._script);

            return matches[1];
        } else {

            throw new KSGMException("No mandatory @namesapce in metadata block.");
        }
    },
    /**
     *  @description string – KS Mandatory
     *
     *  @returns string
     */
    getDescription: function () {

        if (/[\/]{2} \@description (.*)/g.test(this._script) === true) {

            var matches = /[\/]{2} \@description (.*)/g.exec(this._script);

            return matches[1];
        } else {

            throw new KSGMException("No mandatory @description in metadata block.");
        }
    },
    /**
     *  @requires url – Optional
     *
     *  @returns Array
     */
    getRequires: function () {

        var _requires = [];

        if (/[\/]{2} \@match (.*)/g.test(this._script) === true) {

            var matches = /[\/]{2} \@require (.*)/g.exec(this._script);

            for (var i = 1; i < matches.length; i++) {

                _requires.push(matches[i]);
            }
        }

        return _requires;
    },
    /**
     *  @includes pattern – Optional
     *
     *  - There can be any number of @include rules in a script.
     *  - If no include rule is provided, @include * is assumed.
     *
     *  @returns Array
     */
    getIncludes: function () {

        var _includes = [];

        if (/[\/]{2} \@include (.*)/g.test(this._script) === true) {

            var matches = /[\/]{2} \@include (.*)/g.exec(this._script);

            if (matches.length > 0) {

                for (var i = 1; i < matches.length; i++) {

                    _includes.push(matches[i]);
                }
            } else {

                _includes.push('*');
            }
        }

        return _includes;
    },
    /**
     *  @excludes pattern – Optional
     *
     *  - There can be any number of @exclude rules in a script.
     *
     *  @returns Array
     */
    getExcludes: function () {

        var _excludes = [];

        if (/[\/]{2} \@exclude (.*)/g.test(this._script) === true) {

            var matches = /[\/]{2} \@exclude (.*)/g.exec(this._script);

            if (matches.length > 0) {

                for (var i = 1; i < matches.length; i++) {

                    _excludes.push(matches[i]);
                }
            }
        }

        return _excludes;
    },
    /**
     *  @version float – Optional
     *
     *  - This is the version of the script, which should be treated like a
     *      firefox extension version, and maintain the same syntax.
     *
     *  KS v0.1:
     *  - No auto-update implemented
     *
     *  @returns string
     */
    getVersion: function () {

        if (/[\/]{2} \@version (.*)/g.test(this._script) === true) {

            var matches = /[\/]{2} \@version (.*)/g.exec(this._script);

            return matches[1];
        } else {

            return "";
        }
    },

    /**
     *  ===========================
     *  SUPPORTED IN FUTUR VERSIONS
     *  ===========================
     */

    /**
     *  @icon url
     *
     *
     */
    getIcon: function () {

        var matches = /[\/]{2} \@icon (.*)/g.exec(this._script);

        return matches[1];
    },
    /**
     *  @match pattern
     *
     *
     */
    getMatches: function () {

        var _matches = [];

        var matches = /[\/]{2} \@match (.*)/g.exec(this._script);

        for (var i = 1; i < matches.length; i++) {

            _matches.push(matches[i]);
        }

        return _matches;
    },
    /**
     *  @resource url
     *
     *
     */
    getResources: function () {

        var _resources = [];

        var matches = /[\/]{2} \@resource (.*) (.*)/g.exec(this._script);

        for (var i = 1; i < matches.length; i++) {

            _resources.push(new Array(matches[i], matches[i+1]));
        }

        return _resources;
    },
    /**
     *  @run-at "document-end" | "document-start"
     *
     *  - Supports two values: document-end and document-start.
     */
    getRunAt: function () {

        var matches = /[\/]{2} \@run-at (.*)/g.exec(this._script);

        // throw Exception if no match one or the other

        return matches[1];
    },
    /**
     *  @unwrap void
     *
     *  - This key is strongly recommended to only be used for debugging purposes.
     */
    hasUnwrap: function () {

        var _hasUnwrap = /[\/]{2} \@unwrap (.*)/g.test(this._script);

        return _hasUnwrap;
    }
});

//
// Greasemonkey
//

/**
 *  @param string name
 */
function GM_deleteValue(name) {

}

/**
 *  @param string name
 *  @param mixed defaultVal Default result to be returned
 */
function GM_getValue(name, defaultVal) {

}

function GM_listValues() {

}

/**
 *  @param string name
 *  @param string value
 */
function GM_setValues(name, value) {

}

/**
 *  @param string resource Resource name
 */
function GM_getResourceText(resource) {

}

/**
 *  @param string resource Resource name
 */
function GM_getResourceURL(resource) {

}

/**
 *  @param string css String of CSS
 */
function GM_addStyle(css) {

}

/**
 *  @param boolean binary
 *  @param string data
 *  @param object headers
 *  @param string method
 *  @param function onAbort
 *  @param function onError
 *  @param function onLoad
 *  @param function onProgress
 *  @param function onReadyStateChange
 *  @param string overideMimeType
 *  @param string password
 *  @param boolean synchronous
 *  @param object upload
 *  @param string url
 *  @param string user
 */
function GM_xmlhttpRequest(binary,data,headers,method,onAbort,onError,onLoad,onProgress,onReadyStateChange,overideMimeType,password,synchronous,upload,url,user) {

}

/**
 *  @param string message
 */
function GM_log(message) {

}

/**
 *  @param string url
 */
function GM_openInTab(url) {

}

/**
 *  @param string caption
 *  @param function commandFunc
 *  @param string accessKey
 */
function GMregisterMenuCommand(caption,commandFunc,accessKey) {

}
<commit_msg>Empty GreasemonkeyAPI class<commit_after>/**
 *  KitScript - A User Script Safari Extension
 *
 *  Greasemonkey.js - Javascript file containing Greasemonkey classes
 *  (by Prototype.js) used globally in the extension & implementing core
 *  Greasemonkey API.
 *
 *  @author Seraf Dos Santos <webmaster@cyb3r.ca>
 *  @copyright 2011-2012 Seraf Dos Santos - All rights reserved.
 *  @license MIT License
 *  @version 0.1
 */

/**
 *  KSGMException (KitScript Greasemonkey Exception Class)
 */
var KSGMException = Class.create({

    initialize: function (msg) {

        this._msg = msg;
    },
    getMessage: function () {

        return this._msg;
    }
});

/**
 *  KSGreasemonkeyMetadata (KitScript Greasemonkey Metadata Class)
 */
var KSGreasemonkeyMetadata = Class.create({

    initialize: function () {

        this._isHeaderValid = false;
        this._script = "";
    },
    loadScript: function (scriptStr) {

        this._script = scriptStr;

        if (!this.isHeaderValid()) {

            throw new KSGMException("User script metadata block is invalid.");
        }
    },
    isHeaderValid: function () {

        this._isValid = /[\/]{2} ==UserScript==[^=]*==[\/]{1}UserScript==/m.test(this._script);

        return this._isValid;
    },

    /**
     *  =================
     *  SUPPORTED IN v0.1
     *  =================
     */

    /**
     *  @name string – KS Mandatory
     *
     *  - The combination of namespace and name is the unique identifier for a Greasemonkey script.
     *
     *  @returns string
     */
    getName: function () {

        if (/[\/]{2} \@name (.*)/g.test(this._script) === true) {

            var matches = /[\/]{2} \@name (.*)/g.exec(this._script);

            return matches[1];
        } else {

            throw new KSGMException("No mandatory @name in metadata block.");
        }
    },
    /**
     *  @namespace string – KS Mandatory
     *
     *  - The combination of namespace and name is the unique identifier for a Greasemonkey script.
     *
     *  @returns string
     */
    getNamespace: function () {

        if (/[\/]{2} \@namespace (.*)/g.test(this._script) === true) {

            var matches = /[\/]{2} \@namespace (.*)/g.exec(this._script);

            return matches[1];
        } else {

            throw new KSGMException("No mandatory @namesapce in metadata block.");
        }
    },
    /**
     *  @description string – KS Mandatory
     *
     *  @returns string
     */
    getDescription: function () {

        if (/[\/]{2} \@description (.*)/g.test(this._script) === true) {

            var matches = /[\/]{2} \@description (.*)/g.exec(this._script);

            return matches[1];
        } else {

            throw new KSGMException("No mandatory @description in metadata block.");
        }
    },
    /**
     *  @requires url – Optional
     *
     *  @returns Array
     */
    getRequires: function () {

        var _requires = [];

        if (/[\/]{2} \@match (.*)/g.test(this._script) === true) {

            var matches = /[\/]{2} \@require (.*)/g.exec(this._script);

            for (var i = 1; i < matches.length; i++) {

                _requires.push(matches[i]);
            }
        }

        return _requires;
    },
    /**
     *  @includes pattern – Optional
     *
     *  - There can be any number of @include rules in a script.
     *  - If no include rule is provided, @include * is assumed.
     *
     *  @returns Array
     */
    getIncludes: function () {

        var _includes = [];

        if (/[\/]{2} \@include (.*)/g.test(this._script) === true) {

            var matches = /[\/]{2} \@include (.*)/g.exec(this._script);

            if (matches.length > 0) {

                for (var i = 1; i < matches.length; i++) {

                    _includes.push(matches[i]);
                }
            } else {

                _includes.push('*');
            }
        }

        return _includes;
    },
    /**
     *  @excludes pattern – Optional
     *
     *  - There can be any number of @exclude rules in a script.
     *
     *  @returns Array
     */
    getExcludes: function () {

        var _excludes = [];

        if (/[\/]{2} \@exclude (.*)/g.test(this._script) === true) {

            var matches = /[\/]{2} \@exclude (.*)/g.exec(this._script);

            if (matches.length > 0) {

                for (var i = 1; i < matches.length; i++) {

                    _excludes.push(matches[i]);
                }
            }
        }

        return _excludes;
    },
    /**
     *  @version float – Optional
     *
     *  - This is the version of the script, which should be treated like a
     *      firefox extension version, and maintain the same syntax.
     *
     *  KS v0.1:
     *  - No auto-update implemented
     *
     *  @returns string
     */
    getVersion: function () {

        if (/[\/]{2} \@version (.*)/g.test(this._script) === true) {

            var matches = /[\/]{2} \@version (.*)/g.exec(this._script);

            return matches[1];
        } else {

            return "";
        }
    },

    /**
     *  ===========================
     *  SUPPORTED IN FUTUR VERSIONS
     *  ===========================
     */

    /**
     *  @icon url
     *
     *
     */
    getIcon: function () {

        var matches = /[\/]{2} \@icon (.*)/g.exec(this._script);

        return matches[1];
    },
    /**
     *  @match pattern
     *
     *
     */
    getMatches: function () {

        var _matches = [];

        var matches = /[\/]{2} \@match (.*)/g.exec(this._script);

        for (var i = 1; i < matches.length; i++) {

            _matches.push(matches[i]);
        }

        return _matches;
    },
    /**
     *  @resource url
     *
     *
     */
    getResources: function () {

        var _resources = [];

        var matches = /[\/]{2} \@resource (.*) (.*)/g.exec(this._script);

        for (var i = 1; i < matches.length; i++) {

            _resources.push(new Array(matches[i], matches[i+1]));
        }

        return _resources;
    },
    /**
     *  @run-at "document-end" | "document-start"
     *
     *  - Supports two values: document-end and document-start.
     */
    getRunAt: function () {

        var matches = /[\/]{2} \@run-at (.*)/g.exec(this._script);

        // throw Exception if no match one or the other

        return matches[1];
    },
    /**
     *  @unwrap void
     *
     *  - This key is strongly recommended to only be used for debugging purposes.
     */
    hasUnwrap: function () {

        var _hasUnwrap = /[\/]{2} \@unwrap (.*)/g.test(this._script);

        return _hasUnwrap;
    }
});

/**
 *  ================
 *  Greasemonkey API
 *  ================
 */

var KSGGreasemonkeyAPI = Class.create({

    initialize: function () {

    }
});

/**
 *  @param string name
 */
function GM_deleteValue(name) {

}

/**
 *  @param string name
 *  @param mixed defaultVal Default result to be returned
 */
function GM_getValue(name, defaultVal) {

}

function GM_listValues() {

}

/**
 *  @param string name
 *  @param string value
 */
function GM_setValues(name, value) {

}

/**
 *  @param string resource Resource name
 */
function GM_getResourceText(resource) {

}

/**
 *  @param string resource Resource name
 */
function GM_getResourceURL(resource) {

}

/**
 *  @param string css String of CSS
 */
function GM_addStyle(css) {

}

/**
 *  @param boolean binary
 *  @param string data
 *  @param object headers
 *  @param string method
 *  @param function onAbort
 *  @param function onError
 *  @param function onLoad
 *  @param function onProgress
 *  @param function onReadyStateChange
 *  @param string overideMimeType
 *  @param string password
 *  @param boolean synchronous
 *  @param object upload
 *  @param string url
 *  @param string user
 */
function GM_xmlhttpRequest(binary,data,headers,method,onAbort,onError,onLoad,onProgress,onReadyStateChange,overideMimeType,password,synchronous,upload,url,user) {

}

/**
 *  @param string message
 */
function GM_log(message) {

}

/**
 *  @param string url
 */
function GM_openInTab(url) {

}

/**
 *  @param string caption
 *  @param function commandFunc
 *  @param string accessKey
 */
function GMregisterMenuCommand(caption,commandFunc,accessKey) {

}
<|endoftext|>


<commit_before>import {sleep} from './utils'
import Sentry from '../sentry'

// How many times do we retry an action.
const MAX_RETRIES = 30;

export default class ExpiredDataWorker {
  constructor(logger) {
    this.logger = logger;
  }

  async run(metadatum) {
    this.logger.info(`Processing metadatum w/ id ${metadatum.id}`);
    let count = 0;
    do {
      try {
        await this.performAction(metadatum);

        // Now, get rid of the entry.
        await this.removeEntry(metadatum);
        return;
      } catch (err) {
        // We only try to perform the action for
        Sentry.captureException(err);
        count++;
        const sleepPeriod = 60000 * (count + 1) + Math.floor((Math.random() * 100));

        this.logger.error("Error when performing action", err);
        this.logger.error(`Sleeping for ${sleepPeriod} ms`);
        await sleep(sleepPeriod);
      }
    } while (count < MAX_RETRIES);

    await this.removeEntry(metadatum);
  }

  async removeEntry(metadatum) {
    // Remove the object
    this.logger.info(`Destroying metadata for ${metadatum.id}`);
    await metadatum.destroy();
  }

  async performAction(metadatum) {
    // You need to override this one.
    throw new Error("You should override this!");
  }
}
<commit_msg>[cloud-workers] Don't delete metadata after processing it<commit_after>import {sleep} from './utils'
import Sentry from '../sentry'

// How many times do we retry an action.
const MAX_RETRIES = 30;

export default class ExpiredDataWorker {
  constructor(logger) {
    this.logger = logger;
  }

  async run(metadatum) {
    this.logger.info(`Processing metadatum w/ id ${metadatum.id}`);
    let count = 0;
    do {
      try {
        await this.performAction(metadatum);
        await this.nullifyEntry(metadatum); // So we don't try to process it again
        return;
      } catch (err) {
        // We only try to perform the action for
        Sentry.captureException(err);
        count++;
        const sleepPeriod = 60000 * (count + 1) + Math.floor((Math.random() * 100));

        this.logger.error("Error when performing action", err);
        this.logger.error(`Sleeping for ${sleepPeriod} ms`);
        await sleep(sleepPeriod);
      }
    } while (count < MAX_RETRIES);

    await this.removeEntry(metadatum);
  }

  async nullifyEntry(metadatum) {
    // Nylas Mail can't properly process delete deltas for metadata, because
    // the transactions don't store what the objectId and pluginId of the
    // metadata were. Instead, we just nullify the value.
    this.logger.info(`Nullifying metadata for ${metadatum.id}`);
    metadatum.value = {};
    metadatum.expiration = null;
    await metadatum.save();
  }

  async performAction(metadatum) {
    // You need to override this one.
    throw new Error("You should override this!");
  }
}
<|endoftext|>


<commit_before>var helpers = require('./global-setup')
var path = require('path')

var describe = global.describe
var it = global.it
var beforeEach = global.beforeEach
var afterEach = global.afterEach

describe.only('multiple windows', function () {
  helpers.setupTimeout(this)

  var app = null

  beforeEach(function () {
    return helpers.startApplication({
      args: [path.join(__dirname, 'fixtures', 'multi-window')]
    }).then(function (startedApp) { app = startedApp })
  })

  afterEach(function () {
    return helpers.stopApplication(app)
  })

  it('launches the application', function () {
    return app.client
      .getWindowCount().should.eventually.equal(2)
      .windowByIndex(1)
        .browserWindow.getBounds().should.eventually.deep.equal({
          x: 25,
          y: 35,
          width: 200,
          height: 100
        })
        .getTitle().should.eventually.equal('Top')
      .windowByIndex(0)
        .browserWindow.getBounds().should.eventually.deep.equal({
          x: 25,
          y: 135,
          width: 300,
          height: 50
        })
        .getTitle().should.eventually.equal('Bottom')
  })
})
<commit_msg>Remove .only call<commit_after>var helpers = require('./global-setup')
var path = require('path')

var describe = global.describe
var it = global.it
var beforeEach = global.beforeEach
var afterEach = global.afterEach

describe('multiple windows', function () {
  helpers.setupTimeout(this)

  var app = null

  beforeEach(function () {
    return helpers.startApplication({
      args: [path.join(__dirname, 'fixtures', 'multi-window')]
    }).then(function (startedApp) { app = startedApp })
  })

  afterEach(function () {
    return helpers.stopApplication(app)
  })

  it('launches the application', function () {
    return app.client
      .getWindowCount().should.eventually.equal(2)
      .windowByIndex(1)
        .browserWindow.getBounds().should.eventually.deep.equal({
          x: 25,
          y: 35,
          width: 200,
          height: 100
        })
        .getTitle().should.eventually.equal('Top')
      .windowByIndex(0)
        .browserWindow.getBounds().should.eventually.deep.equal({
          x: 25,
          y: 135,
          width: 300,
          height: 50
        })
        .getTitle().should.eventually.equal('Bottom')
  })
})
<|endoftext|>


<commit_before>// Copyright 2002-2014, University of Colorado Boulder

/**
 * Visual representation of a rectangular button.
 *
 * @author John Blanco
 * @author Sam Reid
 */
define( function( require ) {
  'use strict';

  // modules
  var ButtonListener = require( 'SUN/buttons/ButtonListener' );
  var Color = require( 'SCENERY/util/Color' );
  var inherit = require( 'PHET_CORE/inherit' );
  var LinearGradient = require( 'SCENERY/util/LinearGradient' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Rectangle = require( 'SCENERY/nodes/Rectangle' );
  var Shape = require( 'KITE/Shape' );

  // constants
  var VERTICAL_HIGHLIGHT_GRADIENT_LENGTH = 7; // In screen coords, which are roughly pixels.
  var HORIZONTAL_HIGHLIGHT_GRADIENT_LENGTH = 7; // In screen coords, which are roughly pixels.
  var SHADE_GRADIENT_LENGTH = 3; // In screen coords, which are roughly pixels.
  var DEFAULT_COLOR = new Color( 153, 206, 255 );

  /**
   * @param {ButtonModel} buttonModel - Model that defines the button's behavior.
   * @param {Property} interactionStateProperty - A property that is used to drive the visual appearance of the button.
   * @param {Object} options
   * @constructor
   */
  function RectangularButtonView( buttonModel, interactionStateProperty, options ) {
    this.buttonModel = buttonModel; // @protected
    var thisButton = this;

    options = _.extend( {
      // Default values.
      content: null,
      minWidth: 1,
      minHeight: 1,
      cursor: 'pointer',
      cornerRadius: 4,
      baseColor: DEFAULT_COLOR,
      disabledBaseColor: new Color( 220, 220, 220 ),
      xMargin: 7.5,
      yMargin: 5,
      fireOnDown: false,
      xTouchExpansion: 5,
      yTouchExpansion: 5,
      stroke: DEFAULT_COLOR.colorUtilsDarker( 0.4 ),
      lineWidth: 0.5, // Only meaningful if stroke is non-null

      // Strategy for controlling the button's appearance, excluding any
      // content.  This can be a stock strategy from this file or custom.  To
      // create a custom one, model it off of the stock strategies defined in
      // this file.
      buttonAppearanceStrategy: RectangularButtonView.threeDAppearanceStrategy,

      // Strategy for controlling the appearance of the button's content based
      // on the button's state.  This can be a stock strategy from this file,
      // or custom.  To create a custom one, model it off of the stock
      // version(s) defined in this file.
      contentAppearanceStrategy: RectangularButtonView.fadeContentWhenDisabled
    }, options );

    Node.call( thisButton );

    // Hook up the input listener
    this.addInputListener( new ButtonListener( buttonModel ) );

    // Figure out the size of the button.
    var content = options.content;
    var buttonWidth = Math.max( content ? content.width + options.xMargin * 2 : 0, options.minWidth );
    var buttonHeight = Math.max( content ? content.height + options.yMargin * 2 : 0, options.minHeight );

    // Create the basic button shape.
    var button = new Rectangle( 0, 0, buttonWidth, buttonHeight, options.cornerRadius, options.cornerRadius,
      {
        fill: options.baseColor,
        lineWidth: options.lineWidth
      } );
    this.addChild( button );

    // Hook up the strategy that will control the basic button appearance.
    options.buttonAppearanceStrategy( button, interactionStateProperty, options );

    // Add the content to the button.
    if ( content ) {
      content.center = button.center;
      thisButton.addChild( content );
    }

    // Hook up the strategy that will control the content appearance.
    options.contentAppearanceStrategy( content, interactionStateProperty );

    // Control the pointer state based on the interaction state.
    interactionStateProperty.link( function( state ) {
      thisButton.cursor = state === 'disabled' || state === 'disabled-pressed' ? null : 'pointer';
    } );

    // Add explicit mouse and touch areas so that the child nodes can all be non-pickable.
    this.mouseArea = Shape.rectangle( 0, 0, buttonWidth, buttonHeight );
    this.touchArea = Shape.rectangle( -options.xTouchExpansion, -options.yTouchExpansion, buttonWidth + options.xTouchExpansion * 2, buttonHeight + options.yTouchExpansion * 2 );

    // Mutate with the options after the layout is complete so that width-
    // dependent fields like centerX will work.
    thisButton.mutate( options );
  }

  /**
   * Strategy for making a button look 3D-ish by using gradients that create
   * the appearance of highlighted and shaded edges.
   *
   * @param {Node} button
   * @param {Property} interactionStateProperty
   * @param {Object} options
   * @constructor
   */
  RectangularButtonView.threeDAppearanceStrategy = function( button, interactionStateProperty, options ) {

    // Set up variables needed to create the various gradient fills
    var buttonWidth = button.width;
    var buttonHeight = button.height;
    var verticalHighlightStop = Math.min( VERTICAL_HIGHLIGHT_GRADIENT_LENGTH / buttonHeight, 1 );
    var verticalShadowStop = Math.max( 1 - SHADE_GRADIENT_LENGTH / buttonHeight, 0 );
    var horizontalHighlightStop = Math.min( HORIZONTAL_HIGHLIGHT_GRADIENT_LENGTH / buttonWidth, 1 );
    var horizontalShadowStop = Math.max( 1 - SHADE_GRADIENT_LENGTH / buttonWidth, 0 );
    var baseColor = Color.toColor( options.baseColor );
    var disabledBaseColor = Color.toColor( options.disabledBaseColor );
    var transparentBaseColor = new Color( baseColor.getRed(), baseColor.getGreen(), baseColor.getBlue(), 0 );
    var transparentDisabledBaseColor = new Color( disabledBaseColor.getRed(), disabledBaseColor.getGreen(), disabledBaseColor.getBlue(), 0 );
    var disabledStroke = null;
    if ( options.stroke ) {
      disabledStroke = disabledBaseColor.colorUtilsDarker( 0.4 );
    }
    var transparentWhite = new Color( 256, 256, 256, 0.7 );

    // Create the gradient fills used for various button states
    var upFillVertical = new LinearGradient( 0, 0, 0, buttonHeight )
      .addColorStop( 0, baseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( verticalHighlightStop, baseColor )
      .addColorStop( verticalShadowStop, baseColor )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

    var upFillHorizontal = new LinearGradient( 0, 0, buttonWidth, 0 )
      .addColorStop( 0, transparentWhite )
      .addColorStop( horizontalHighlightStop, transparentBaseColor )
      .addColorStop( horizontalShadowStop, transparentBaseColor )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

    var overFillVertical = new LinearGradient( 0, 0, 0, buttonHeight )
      .addColorStop( 0, baseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( verticalHighlightStop, baseColor.colorUtilsBrighter( 0.5 ) )
      .addColorStop( verticalShadowStop, baseColor.colorUtilsBrighter( 0.5 ) )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

    var overFillHorizontal = new LinearGradient( 0, 0, buttonWidth, 0 )
      .addColorStop( 0, transparentWhite )
      .addColorStop( horizontalHighlightStop / 2, new Color( 256, 256, 256, 0 ) )
      .addColorStop( horizontalShadowStop, transparentBaseColor )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.3 ) );

    var downFill = new LinearGradient( 0, 0, 0, buttonHeight )
      .addColorStop( 0, baseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( verticalHighlightStop * 0.67, baseColor.colorUtilsDarker( 0.3 ) )
      .addColorStop( verticalShadowStop, baseColor.colorUtilsBrighter( 0.2 ) )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

    var disabledFillVertical = new LinearGradient( 0, 0, 0, buttonHeight )
      .addColorStop( 0, disabledBaseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( verticalHighlightStop, disabledBaseColor.colorUtilsBrighter( 0.5 ) )
      .addColorStop( verticalShadowStop, disabledBaseColor.colorUtilsBrighter( 0.5 ) )
      .addColorStop( 1, disabledBaseColor.colorUtilsDarker( 0.5 ) );

    var disabledFillHorizontal = new LinearGradient( 0, 0, buttonWidth, 0 )
      .addColorStop( 0, disabledBaseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( horizontalHighlightStop, transparentDisabledBaseColor )
      .addColorStop( horizontalShadowStop, transparentDisabledBaseColor )
      .addColorStop( 1, disabledBaseColor.colorUtilsDarker( 0.5 ) );

    var disabledPressedFillVertical = new LinearGradient( 0, 0, 0, buttonHeight )
      .addColorStop( 0, disabledBaseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( verticalHighlightStop * 0.67, disabledBaseColor.colorUtilsDarker( 0.3 ) )
      .addColorStop( verticalShadowStop, disabledBaseColor.colorUtilsBrighter( 0.2 ) )
      .addColorStop( 1, disabledBaseColor.colorUtilsDarker( 0.5 ) );

    // Create the overlay that is used to add horizontal shading.
    var overlayForHorizGradient = new Rectangle( 0, 0, buttonWidth, buttonHeight, options.cornerRadius, options.cornerRadius,
      {
        fill: options.baseColor,
        stroke: options.stroke,
        lineWidth: options.lineWidth
      } );
    button.addChild( overlayForHorizGradient );

    interactionStateProperty.link( function( state ) {
      switch( state ) {

        case 'idle':
          button.fill = upFillVertical;
          overlayForHorizGradient.stroke = options.stroke;
          overlayForHorizGradient.fill = upFillHorizontal;
          break;

        case 'over':
          button.fill = overFillVertical;
          overlayForHorizGradient.stroke = options.stroke;
          overlayForHorizGradient.fill = overFillHorizontal;
          break;

        case 'pressed':
          button.fill = downFill;
          overlayForHorizGradient.stroke = options.stroke;
          overlayForHorizGradient.fill = overFillHorizontal;
          break;

        case 'disabled':
          button.fill = disabledFillVertical;
          button.stroke = disabledStroke;
          overlayForHorizGradient.stroke = disabledStroke;
          overlayForHorizGradient.fill = disabledFillHorizontal;
          break;

        case 'disabled-pressed':
          button.fill = disabledPressedFillVertical;
          button.stroke = disabledStroke;
          overlayForHorizGradient.stroke = disabledStroke;
          overlayForHorizGradient.fill = disabledFillHorizontal;
          break;
      }
    } );
  };

  /**
   * Strategy for buttons that look flat, i.e. no shading or highlighting, but
   * that change color on mouseover, press, etc.
   *
   * @param {Node} button
   * @param {Property} interactionStateProperty
   * @param {Object} options
   * @constructor
   */
  RectangularButtonView.flatAppearanceStrategy = function( button, interactionStateProperty, options ) {

    // Set up variables needed to create the various gradient fills
    var baseColor = Color.toColor( options.baseColor );
    var disabledBaseColor = Color.toColor( options.disabledBaseColor );
    var disabledStroke = null;
    if ( options.stroke ) {
      disabledStroke = disabledBaseColor.colorUtilsDarker( 0.4 );
    }

    // Create the fills used for various button states
    var upFill = baseColor;
    var overFill = baseColor.colorUtilsBrighter( 0.4 );
    var downFill = baseColor.colorUtilsDarker( 0.4 );
    var disabledFill = disabledBaseColor;
    var disabledPressedFillVertical = disabledFill;

    interactionStateProperty.link( function( state ) {
      switch( state ) {

        case 'idle':
          button.fill = upFill;
          button.stroke = options.stroke;
          break;

        case 'over':
          button.fill = overFill;
          button.stroke = options.stroke;
          break;

        case 'pressed':
          button.fill = downFill;
          button.stroke = options.stroke;
          break;

        case 'disabled':
          button.fill = disabledFill;
          button.stroke = disabledStroke;
          break;

        case 'disabled-pressed':
          button.fill = disabledPressedFillVertical;
          button.stroke = disabledStroke;
          break;
      }
    } );
  };

  /**
   * Basic strategy for controlling content appearance, fades the content by
   * making it transparent when disabled.
   *
   * @param {Node} content
   * @param {Property} interactionStateProperty
   * @constructor
   */
  RectangularButtonView.fadeContentWhenDisabled = function( content, interactionStateProperty ) {
    if ( content ) {
      interactionStateProperty.link( function( state ) {
        content.opacity = state === 'disabled' || state === 'disabled-pressed' ? 0.3 : 1;
      } );
    }
  };

  return inherit( Node, RectangularButtonView,
    {
      set enabled( value ) {
        assert && assert( typeof value === 'boolean', 'RectangularButtonView.enabled must be a boolean value' );
        this.buttonModel.enabled = value;
      },

      get enabled() { return this.buttonModel.enabled; }
    } );
} );<commit_msg>#109 increase xMargin from 5 to 8 for rectangular push buttons (for real this time, set it to 7.5 in previous commit)<commit_after>// Copyright 2002-2014, University of Colorado Boulder

/**
 * Visual representation of a rectangular button.
 *
 * @author John Blanco
 * @author Sam Reid
 */
define( function( require ) {
  'use strict';

  // modules
  var ButtonListener = require( 'SUN/buttons/ButtonListener' );
  var Color = require( 'SCENERY/util/Color' );
  var inherit = require( 'PHET_CORE/inherit' );
  var LinearGradient = require( 'SCENERY/util/LinearGradient' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Rectangle = require( 'SCENERY/nodes/Rectangle' );
  var Shape = require( 'KITE/Shape' );

  // constants
  var VERTICAL_HIGHLIGHT_GRADIENT_LENGTH = 7; // In screen coords, which are roughly pixels.
  var HORIZONTAL_HIGHLIGHT_GRADIENT_LENGTH = 7; // In screen coords, which are roughly pixels.
  var SHADE_GRADIENT_LENGTH = 3; // In screen coords, which are roughly pixels.
  var DEFAULT_COLOR = new Color( 153, 206, 255 );

  /**
   * @param {ButtonModel} buttonModel - Model that defines the button's behavior.
   * @param {Property} interactionStateProperty - A property that is used to drive the visual appearance of the button.
   * @param {Object} options
   * @constructor
   */
  function RectangularButtonView( buttonModel, interactionStateProperty, options ) {
    this.buttonModel = buttonModel; // @protected
    var thisButton = this;

    options = _.extend( {
      // Default values.
      content: null,
      minWidth: 1,
      minHeight: 1,
      cursor: 'pointer',
      cornerRadius: 4,
      baseColor: DEFAULT_COLOR,
      disabledBaseColor: new Color( 220, 220, 220 ),
      xMargin: 8,
      yMargin: 5,
      fireOnDown: false,
      xTouchExpansion: 5,
      yTouchExpansion: 5,
      stroke: DEFAULT_COLOR.colorUtilsDarker( 0.4 ),
      lineWidth: 0.5, // Only meaningful if stroke is non-null

      // Strategy for controlling the button's appearance, excluding any
      // content.  This can be a stock strategy from this file or custom.  To
      // create a custom one, model it off of the stock strategies defined in
      // this file.
      buttonAppearanceStrategy: RectangularButtonView.threeDAppearanceStrategy,

      // Strategy for controlling the appearance of the button's content based
      // on the button's state.  This can be a stock strategy from this file,
      // or custom.  To create a custom one, model it off of the stock
      // version(s) defined in this file.
      contentAppearanceStrategy: RectangularButtonView.fadeContentWhenDisabled
    }, options );

    Node.call( thisButton );

    // Hook up the input listener
    this.addInputListener( new ButtonListener( buttonModel ) );

    // Figure out the size of the button.
    var content = options.content;
    var buttonWidth = Math.max( content ? content.width + options.xMargin * 2 : 0, options.minWidth );
    var buttonHeight = Math.max( content ? content.height + options.yMargin * 2 : 0, options.minHeight );

    // Create the basic button shape.
    var button = new Rectangle( 0, 0, buttonWidth, buttonHeight, options.cornerRadius, options.cornerRadius,
      {
        fill: options.baseColor,
        lineWidth: options.lineWidth
      } );
    this.addChild( button );

    // Hook up the strategy that will control the basic button appearance.
    options.buttonAppearanceStrategy( button, interactionStateProperty, options );

    // Add the content to the button.
    if ( content ) {
      content.center = button.center;
      thisButton.addChild( content );
    }

    // Hook up the strategy that will control the content appearance.
    options.contentAppearanceStrategy( content, interactionStateProperty );

    // Control the pointer state based on the interaction state.
    interactionStateProperty.link( function( state ) {
      thisButton.cursor = state === 'disabled' || state === 'disabled-pressed' ? null : 'pointer';
    } );

    // Add explicit mouse and touch areas so that the child nodes can all be non-pickable.
    this.mouseArea = Shape.rectangle( 0, 0, buttonWidth, buttonHeight );
    this.touchArea = Shape.rectangle( -options.xTouchExpansion, -options.yTouchExpansion, buttonWidth + options.xTouchExpansion * 2, buttonHeight + options.yTouchExpansion * 2 );

    // Mutate with the options after the layout is complete so that width-
    // dependent fields like centerX will work.
    thisButton.mutate( options );
  }

  /**
   * Strategy for making a button look 3D-ish by using gradients that create
   * the appearance of highlighted and shaded edges.
   *
   * @param {Node} button
   * @param {Property} interactionStateProperty
   * @param {Object} options
   * @constructor
   */
  RectangularButtonView.threeDAppearanceStrategy = function( button, interactionStateProperty, options ) {

    // Set up variables needed to create the various gradient fills
    var buttonWidth = button.width;
    var buttonHeight = button.height;
    var verticalHighlightStop = Math.min( VERTICAL_HIGHLIGHT_GRADIENT_LENGTH / buttonHeight, 1 );
    var verticalShadowStop = Math.max( 1 - SHADE_GRADIENT_LENGTH / buttonHeight, 0 );
    var horizontalHighlightStop = Math.min( HORIZONTAL_HIGHLIGHT_GRADIENT_LENGTH / buttonWidth, 1 );
    var horizontalShadowStop = Math.max( 1 - SHADE_GRADIENT_LENGTH / buttonWidth, 0 );
    var baseColor = Color.toColor( options.baseColor );
    var disabledBaseColor = Color.toColor( options.disabledBaseColor );
    var transparentBaseColor = new Color( baseColor.getRed(), baseColor.getGreen(), baseColor.getBlue(), 0 );
    var transparentDisabledBaseColor = new Color( disabledBaseColor.getRed(), disabledBaseColor.getGreen(), disabledBaseColor.getBlue(), 0 );
    var disabledStroke = null;
    if ( options.stroke ) {
      disabledStroke = disabledBaseColor.colorUtilsDarker( 0.4 );
    }
    var transparentWhite = new Color( 256, 256, 256, 0.7 );

    // Create the gradient fills used for various button states
    var upFillVertical = new LinearGradient( 0, 0, 0, buttonHeight )
      .addColorStop( 0, baseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( verticalHighlightStop, baseColor )
      .addColorStop( verticalShadowStop, baseColor )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

    var upFillHorizontal = new LinearGradient( 0, 0, buttonWidth, 0 )
      .addColorStop( 0, transparentWhite )
      .addColorStop( horizontalHighlightStop, transparentBaseColor )
      .addColorStop( horizontalShadowStop, transparentBaseColor )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

    var overFillVertical = new LinearGradient( 0, 0, 0, buttonHeight )
      .addColorStop( 0, baseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( verticalHighlightStop, baseColor.colorUtilsBrighter( 0.5 ) )
      .addColorStop( verticalShadowStop, baseColor.colorUtilsBrighter( 0.5 ) )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

    var overFillHorizontal = new LinearGradient( 0, 0, buttonWidth, 0 )
      .addColorStop( 0, transparentWhite )
      .addColorStop( horizontalHighlightStop / 2, new Color( 256, 256, 256, 0 ) )
      .addColorStop( horizontalShadowStop, transparentBaseColor )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.3 ) );

    var downFill = new LinearGradient( 0, 0, 0, buttonHeight )
      .addColorStop( 0, baseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( verticalHighlightStop * 0.67, baseColor.colorUtilsDarker( 0.3 ) )
      .addColorStop( verticalShadowStop, baseColor.colorUtilsBrighter( 0.2 ) )
      .addColorStop( 1, baseColor.colorUtilsDarker( 0.5 ) );

    var disabledFillVertical = new LinearGradient( 0, 0, 0, buttonHeight )
      .addColorStop( 0, disabledBaseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( verticalHighlightStop, disabledBaseColor.colorUtilsBrighter( 0.5 ) )
      .addColorStop( verticalShadowStop, disabledBaseColor.colorUtilsBrighter( 0.5 ) )
      .addColorStop( 1, disabledBaseColor.colorUtilsDarker( 0.5 ) );

    var disabledFillHorizontal = new LinearGradient( 0, 0, buttonWidth, 0 )
      .addColorStop( 0, disabledBaseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( horizontalHighlightStop, transparentDisabledBaseColor )
      .addColorStop( horizontalShadowStop, transparentDisabledBaseColor )
      .addColorStop( 1, disabledBaseColor.colorUtilsDarker( 0.5 ) );

    var disabledPressedFillVertical = new LinearGradient( 0, 0, 0, buttonHeight )
      .addColorStop( 0, disabledBaseColor.colorUtilsBrighter( 0.7 ) )
      .addColorStop( verticalHighlightStop * 0.67, disabledBaseColor.colorUtilsDarker( 0.3 ) )
      .addColorStop( verticalShadowStop, disabledBaseColor.colorUtilsBrighter( 0.2 ) )
      .addColorStop( 1, disabledBaseColor.colorUtilsDarker( 0.5 ) );

    // Create the overlay that is used to add horizontal shading.
    var overlayForHorizGradient = new Rectangle( 0, 0, buttonWidth, buttonHeight, options.cornerRadius, options.cornerRadius,
      {
        fill: options.baseColor,
        stroke: options.stroke,
        lineWidth: options.lineWidth
      } );
    button.addChild( overlayForHorizGradient );

    interactionStateProperty.link( function( state ) {
      switch( state ) {

        case 'idle':
          button.fill = upFillVertical;
          overlayForHorizGradient.stroke = options.stroke;
          overlayForHorizGradient.fill = upFillHorizontal;
          break;

        case 'over':
          button.fill = overFillVertical;
          overlayForHorizGradient.stroke = options.stroke;
          overlayForHorizGradient.fill = overFillHorizontal;
          break;

        case 'pressed':
          button.fill = downFill;
          overlayForHorizGradient.stroke = options.stroke;
          overlayForHorizGradient.fill = overFillHorizontal;
          break;

        case 'disabled':
          button.fill = disabledFillVertical;
          button.stroke = disabledStroke;
          overlayForHorizGradient.stroke = disabledStroke;
          overlayForHorizGradient.fill = disabledFillHorizontal;
          break;

        case 'disabled-pressed':
          button.fill = disabledPressedFillVertical;
          button.stroke = disabledStroke;
          overlayForHorizGradient.stroke = disabledStroke;
          overlayForHorizGradient.fill = disabledFillHorizontal;
          break;
      }
    } );
  };

  /**
   * Strategy for buttons that look flat, i.e. no shading or highlighting, but
   * that change color on mouseover, press, etc.
   *
   * @param {Node} button
   * @param {Property} interactionStateProperty
   * @param {Object} options
   * @constructor
   */
  RectangularButtonView.flatAppearanceStrategy = function( button, interactionStateProperty, options ) {

    // Set up variables needed to create the various gradient fills
    var baseColor = Color.toColor( options.baseColor );
    var disabledBaseColor = Color.toColor( options.disabledBaseColor );
    var disabledStroke = null;
    if ( options.stroke ) {
      disabledStroke = disabledBaseColor.colorUtilsDarker( 0.4 );
    }

    // Create the fills used for various button states
    var upFill = baseColor;
    var overFill = baseColor.colorUtilsBrighter( 0.4 );
    var downFill = baseColor.colorUtilsDarker( 0.4 );
    var disabledFill = disabledBaseColor;
    var disabledPressedFillVertical = disabledFill;

    interactionStateProperty.link( function( state ) {
      switch( state ) {

        case 'idle':
          button.fill = upFill;
          button.stroke = options.stroke;
          break;

        case 'over':
          button.fill = overFill;
          button.stroke = options.stroke;
          break;

        case 'pressed':
          button.fill = downFill;
          button.stroke = options.stroke;
          break;

        case 'disabled':
          button.fill = disabledFill;
          button.stroke = disabledStroke;
          break;

        case 'disabled-pressed':
          button.fill = disabledPressedFillVertical;
          button.stroke = disabledStroke;
          break;
      }
    } );
  };

  /**
   * Basic strategy for controlling content appearance, fades the content by
   * making it transparent when disabled.
   *
   * @param {Node} content
   * @param {Property} interactionStateProperty
   * @constructor
   */
  RectangularButtonView.fadeContentWhenDisabled = function( content, interactionStateProperty ) {
    if ( content ) {
      interactionStateProperty.link( function( state ) {
        content.opacity = state === 'disabled' || state === 'disabled-pressed' ? 0.3 : 1;
      } );
    }
  };

  return inherit( Node, RectangularButtonView,
    {
      set enabled( value ) {
        assert && assert( typeof value === 'boolean', 'RectangularButtonView.enabled must be a boolean value' );
        this.buttonModel.enabled = value;
      },

      get enabled() { return this.buttonModel.enabled; }
    } );
} );<|endoftext|>


<commit_before>/**
 * Created by pomy on 11/5/16.
 */
'use sreict';

var path = require('path');

module.exports = {
    entry: {
        app:[path.resolve(__dirname, '../client/index.js')]
    },
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, '../public/assets/'),
        publicPath: path.resolve(__dirname, '/assets/')
    },
    module: {
        loaders: [
            {
                test: /\.vue$/,
                loader: 'vue'
            },
            {
                test: /\.js$/,
                loader: 'babel!eslint',
                exclude: /node_modules/
            },
            {
                test: /\.(png|jpg|gif|jpeg)$/,
                loader: 'url',
                query: {
                    limit: 10000,
                    name: '[name].[ext]?[hash]'
                }
            }
        ]
    },
    resolve:{
        extensions:["",".js",".vue"]
    },
    externals: {
        "jquery": "jQuery"
    },
    vue: {
        loaders: {
            js: 'babel!eslint'
        }
    }
}
<commit_msg>file loader<commit_after>/**
 * Created by pomy on 11/5/16.
 */
'use sreict';

var path = require('path');

module.exports = {
    entry: {
        app:[path.resolve(__dirname, '../client/index.js')]
    },
    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, '../public/assets/'),
        publicPath: path.resolve(__dirname, '/assets/')
    },
    module: {
        loaders: [
            {
                test: /\.vue$/,
                loader: 'vue'
            },
            {
                test: /\.js$/,
                loader: 'babel!eslint',
                exclude: /node_modules/
            },
            {
                test: /\.(png|jpg|gif|jpeg)$/,
                loader: 'url',
                query: {
                    limit: 10000,
                    name: '[name].[ext]?[hash]'
                }
            },
            {
                test: /\.(png|jpg|gif|jpeg)$/,
                loader: 'file-loader'
            }
        ]
    },
    resolve:{
        extensions:["",".js",".vue"]
    },
    externals: {
        "jquery": "jQuery"
    },
    vue: {
        loaders: {
            js: 'babel!eslint'
        }
    }
}
<|endoftext|>


<commit_before>var edges = [];
var vertices = {};
var WIDTH = 1000;
var HEIGHT = 1000;
var	AREA = WIDTH * HEIGHT;
var K;
var ITERATIONS = 1;
var inputDir;
var TEMPERATURE = 25;
var SIZE = 5;

function preload() {
	inputDir = loadStrings('data/facebook/', inputHandler);
}

function setup() {
	createCanvas(1000, 1000);

	for(var e in edges) {
		if (edges[e]) {
			var v1 = edges[e][0];
			var v2 = edges[e][1];
			if (!vertices[v1]) {
				vertices[v1] = [];
			} if (!vertices[v2]) {
				vertices[v2] = [];
			}
		}
	}

	K = Math.sqrt(AREA/Object.keys(vertices).length);

	assignRandom();

	for (var i = 0; i < ITERATIONS; i++) {
			calculateRepulsion();
			calculateAttraction();
			limitMaxTemp();
			TEMPERATURE -= 1;
			debugger
	};
}

function inputHandler(inputDir) {
	var re = new RegExp('(\\d+\.edges)');
	for (var i = inputDir.length - 1; i >= 0; i--) {
		if (inputDir[i].search(re)) {
			var file = inputDir[i].match(re);
			if (file !== null) {
				loadStrings("data/facebook/" + file[0], fileHandler);
			}
		}
	};
}

function fileHandler(r) {
	for (var i = 0; i < r.length; i++) {
		var stringData = r[i].split(" ");
		edges.push([parseInt(stringData[0]), parseInt(stringData[1])]);
	};
}

function draw () {
	for (var v in vertices) {
		var x = vertices[v][0];
		var y = vertices[v][1];
		fill(95, 160, 198, 125);
		noStroke();
		ellipse(x, y, SIZE, SIZE);
	}
	for (var e in edges) {
		v1 = edges[e][0];
		v2 = edges[e][1];
		x1 = vertices[v1][0];
		y1 = vertices[v1][1];
		x2 = vertices[v2][0];
		y2 = vertices[v2][1];
		stroke(95, 160, 198, 125);
		line(x1, y1, x2, y2);
	}

}

function assignRandom() {
	for (var v in vertices) {
		vertices[v] = [Math.floor(Math.random() * WIDTH),Math.floor(Math.random() * HEIGHT)];
	};
}

function fAttraction(x) {
	return x*x/K;
}

function fRepulsion(x) {
	return K*K/x;
}

function sortNum(a,b) {
    return a - b;
}

function calculateRepulsion() {
	for(var v in vertices) {
		var vdisp = 0;
		for(var u in vertices) {
			if (u != v) {
				var delta = dist(vertices[v][0], vertices[v][1], vertices[u][0], vertices[u][1]);
				vdisp = vdisp + (delta/Math.abs(delta))*fRepulsion(Math.abs(delta));
				vertices[v][2] = vdisp;
			}
		}
	}
}

function calculateAttraction () {
	for (var i = 0; i < edges.length; i++) {
		var vKey = edges[i][0];
		var uKey = edges[i][1];
		var v = vertices[vKey];
		var u = vertices[uKey];
		var delta = dist(v[0], v[1], u[0], u[1]);
		var vdisp = vertices[vKey][2] - (delta/Math.abs(delta)) * (fAttraction(Math.abs(delta)));
		var udisp = vertices[uKey][2] + (delta/Math.abs(delta)) * (fAttraction(Math.abs(delta)));;
		vertices[vKey][2] = vdisp;
		vertices[uKey][2] = udisp;
	}
}

function limitMaxTemp() {
	for(var v in vertices) {
		vertices[v][0] = vertices[v][0] + (vertices[v][2]/Math.abs(vertices[v][2])) * min(vertices[v][2], TEMPERATURE);
		vertices[v][1] = vertices[v][1] + (vertices[v][2]/Math.abs(vertices[v][2])) * min(vertices[v][2], TEMPERATURE);
		vertices[v][0] = min(WIDTH/2, max(-WIDTH/2, vertices[v][0]));
		vertices[v][1] = min(HEIGHT/2, max(-HEIGHT/2, vertices[v][1]));
	}
}<commit_msg>force layout in progress<commit_after>var edges = [];
var vertices = {};
var WIDTH = 800;
var HEIGHT = 800;
var	AREA = WIDTH * HEIGHT;
var K;
var ITERATIONS = 5;
var inputDir;
var TEMPERATURE = 25;
var SIZE = 5;

function preload() {
	inputDir = loadStrings('data/facebook/', inputHandler);
}

function setup() {
	createCanvas(1000, 1000);

	for(var e in edges) {
		if (edges[e]) {
			var v1 = edges[e][0];
			var v2 = edges[e][1];
			if (!vertices[v1]) {
				vertices[v1] = [];
			} if (!vertices[v2]) {
				vertices[v2] = [];
			}
		}
	}

	K = Math.sqrt(AREA/Object.keys(vertices).length);

	assignRandom();

	for (var j = 0; j < ITERATIONS; j++) {
			calculateRepulsion();
			calculateAttraction();
			limitMaxTemp();
			TEMPERATURE -= 1;
	};
}

function inputHandler(inputDir) {
	var re = new RegExp('(\\d+\.edges)');
	for (var i = inputDir.length - 1; i >= 0; i--) {
		if (inputDir[i].search(re)) {
			var file = inputDir[i].match(re);
			if (file !== null) {
				loadStrings("data/facebook/" + file[0], fileHandler);
			}
		}
	};
}

function fileHandler(r) {
	for (var i = 0; i < r.length; i++) {
		var stringData = r[i].split(" ");
		edges.push([parseInt(stringData[0]), parseInt(stringData[1])]);
	};
}

function draw () {
	clear();
	for (var v in vertices) {
		var x = vertices[v][0];
		var y = vertices[v][1];
		var d = dist(mouseX, mouseY, x, y);
		if (d < SIZE) {
			for (var e in edges) {
				if (edges[e][0] == v || edges[e][1] == v ) {
					x1 = vertices[edges[e][0]][0];
					y1 = vertices[edges[e][0]][1];
					x2 = vertices[edges[e][1]][0];
					y2 = vertices[edges[e][1]][1];
					stroke(95, 160, 198, 125);
					line(x1, y1, x2, y2);
				}
			}
			noStroke();
			fill('#2E4E60');
			ellipse(x, y, SIZE, SIZE);
			textSize(11);
			fill('#11100E');
			textAlign(CENTER);
			text(v, x, y-15);
		} else {
			fill(95, 160, 198, 125);
			noStroke();
			ellipse(x, y, SIZE, SIZE);
		}
	}
	// for (var e in edges) {
	// 	v1 = edges[e][0];
	// 	v2 = edges[e][1];
	// 	x1 = vertices[v1][0];
	// 	y1 = vertices[v1][1];
	// 	x2 = vertices[v2][0];
	// 	y2 = vertices[v2][1];
	// 	stroke(95, 160, 198, 125);
	// 	line(x1, y1, x2, y2);
	// }

}

function assignRandom() {
	for (var v in vertices) {
		vertices[v] = [Math.floor(Math.random() * WIDTH),Math.floor(Math.random() * HEIGHT)];
		// if (!vertices[v][0] || !vertices[v][1]) {
		// 	console.log("===================================");
		// 	console.log("vertices[v][0] " + vertices[v][0]);
		// 	console.log("vertices[v][1] " + vertices[v][1]);
		// 	console.log("===================================");
		// }
	};
}

function fAttraction(x) {
	return x*x/K;
}

function fRepulsion(x) {
	return K*K/x;
}

function sortNum(a,b) {
    return a - b;
}

function calculateRepulsion() {
	for(var v in vertices) {
		var vdisp = 0;
		for(var u in vertices) {
			if (u != v) {
				var delta = dist(vertices[v][0], vertices[v][1], vertices[u][0], vertices[u][1]);
				vdisp = vdisp + (delta/Math.abs(delta)) * fRepulsion(Math.abs(delta));
			}
		}
		vertices[v][2] = vdisp;
		// if (!vertices[v][2] || !(vertices[v][0] && vertices[v][1])) {
		// 	console.log("================================");
		// 	console.log("vertices[v][0] " + vertices[v][0]);
		// 	console.log("vertices[v][1] " + vertices[v][1]);
		// 	console.log("vertices[v][2] " + vertices[v][2]);
		// 	console.log("================================");
		// }
	}
}

function calculateAttraction () {
	for (var i = 0; i < edges.length; i++) {
		var vKey = edges[i][0];
		var uKey = edges[i][1];
		var v = vertices[vKey];
		var u = vertices[uKey];
		var delta = dist(v[0], v[1], u[0], u[1]);
		var vdisp = vertices[vKey][2] - (delta/Math.abs(delta)) * (fAttraction(Math.abs(delta)));
		var udisp = vertices[uKey][2] + (delta/Math.abs(delta)) * (fAttraction(Math.abs(delta)));;
		vertices[vKey][2] = vdisp;
		vertices[uKey][2] = udisp;
		// if (!vertices[vKey][2] || !vertices[uKey][2]) {
		// 	console.log("vertices[vKey][2] or vertices[uKey][2] was NaN");
		// 	console.log("vertices[vKey] " + vertices[vKey]);
		// 	console.log("vertices[uKey] " + vertices[uKey]);
		// 	console.log("delta " + delta);
		// 	console.log("vdisp " + vdisp);
		// 	console.log("udisp " + udisp);
		// 	console.log("vertices[vKey][2] " + vertices[vKey][2]);
		// 	console.log("vertices[uKey][2] " + vertices[uKey][2]);
		// }
	}
}

function limitMaxTemp() {
	for(var v in vertices) {
		var temp0 = vertices[v][0] + (vertices[v][2]/Math.abs(vertices[v][2])) * min(vertices[v][2], TEMPERATURE);
		var temp1 = vertices[v][1] + (vertices[v][2]/Math.abs(vertices[v][2])) * min(vertices[v][2], TEMPERATURE);
		vertices[v][0] = min(WIDTH, vertices[v][0]) ? min(WIDTH, vertices[v][0]) : WIDTH;
		vertices[v][1] = min(HEIGHT, vertices[v][1]) ? min(HEIGHT, vertices[v][1]) : HEIGHT;
		// if (!vertices[v][0] || !vertices[v][1]) {
		// 	console.log("vertices[v][0] or vertices[v][1] was NaN");
		// 	console.log("vertices[v][0] " + vertices[v][0]);
		// 	console.log("vertices[v][1] " + vertices[v][1]);
		// }
	}
}<|endoftext|>


<commit_before>/**
* This library ONLY WORKS IN AIR atm
*
* This is a conversion of the actionscript library from twstreamer <http://github.com/r/twstreamer/> into JavaScript.
* No license was listed on the git repo, so I am assuming something public domain or new-BSD-ish.
*
* @constructor
*/
var SpazTwitterStream = function(opts) {
	var that = this;

	var isReading    = false;
	var amountRead   = 0;
	var streamBuffer = '';

	this.opts = sch.defaults({
		'auth'		: null,
		'userstream_url': "https://userstream.twitter.com/2/user.json",
		'onData'	: null,
		'onError'	: null
	}, opts);

	this.stream = new air.URLStream;

	/**
	 * holds timeout ID for reconnect timer
	 */
	this.timeout;

	this.connect = function() {
		that.restartTimer();

		isReading    = false;
		amountRead   = 0;
		streamBuffer = "";

		var request = createStreamRequest(that.opts.userstream_url, that.opts.auth);
		that.stream = new air.URLStream();
		that.stream.addEventListener(air.IOErrorEvent.IO_ERROR, errorReceived);
		that.stream.addEventListener(air.ProgressEvent.PROGRESS, dataReceived);
		that.stream.load(request);
	};

	this.disconnect = function() {
		if (that.timeout) {
			clearTimeout(that.timeout);
		}

		that.stream.close();
		that.stream = null;
	};

	this.restartTimer = function() {
		sch.error('Restarting timer');

		if (this.timeout) {
			clearTimeout(this.timeout);
		}

		this.timeout = setTimeout(
			function() {
				sch.error('Reconnecting!');
				that.disconnect();
				that.connect();
			},
			90000 // 90 second timeout
		);
	};

	function createStreamRequest(username, pass) {
		var request = new air.URLRequest(that.opts.userstream_url);
		var auth_header = that.opts.auth.signRequest(air.URLRequestMethod.POST, that.opts.userstream_url, '');
		sch.debug('auth_header:'+auth_header);
		request.requestHeaders = new Array(new air.URLRequestHeader("Authorization", auth_header));
		request.method = air.URLRequestMethod.POST;
		request.data = '';
		return request;
	}

	function errorReceived(e) {
		sch.error("errorReceived in stream");
		if (that.opts.onError) {
			that.opts.onError.call(this, e);
		}
	}

	function dataReceived(e) {
		sch.debug("dataReceived");
		sch.debug(e.toString());

		that.restartTimer();

		var toRead = e.bytesLoaded - amountRead;
		sch.debug("toRead:"+toRead);
		var buffer = that.stream.readUTFBytes(toRead);
		sch.debug("buffer:"+buffer);
		amountRead = e.bytesLoaded;
		sch.debug("amountRead:"+amountRead);

		var parts = [];
		if (!isReading) {
			parts = buffer.split(/\n/);
			var firstPart = parts[0].replace(/[\s\n]*/, "");
			sch.debug("firstPart:"+firstPart);
			buffer = parts.slice(1).join("\n");
			sch.debug("buffer:"+buffer);
			isReading = true;
		}

		// pump the JSON pieces through
		if ((toRead > 0) && (amountRead > 0)) {
			streamBuffer += buffer;
			sch.debug("streamBuffer:"+streamBuffer);
			parts = streamBuffer.split(/\n/);
			sch.debug("parts:"+parts);
			var lastElement = parts.pop();
			for (var i=0; i < parts.length; i++) {
				sch.debug('parts['+i+']:'+parts[i]);
				if (that.opts.onData) {
					that.opts.onData.call(this, parts[i]);
				}
			}
			streamBuffer = lastElement;
			sch.debug("streamBuffer:"+streamBuffer);
		}
	}
};
<commit_msg>some jsdoc'in<commit_after>/**
* This library ONLY WORKS IN AIR atm
*
* This is a conversion of the actionscript library from twstreamer <http://github.com/r/twstreamer/> into JavaScript.
* No license was listed on the git repo, so I am assuming something public domain or new-BSD-ish.
*
* @constructor
*/
var SpazTwitterStream = function(opts) {
	var that = this;

	var isReading    = false;
	var amountRead   = 0;
	var streamBuffer = '';

	this.opts = sch.defaults({
		'auth'		: null,
		'userstream_url': "https://userstream.twitter.com/2/user.json",
		'onData'	: null,
		'onError'	: null
	}, opts);

	this.stream = new air.URLStream;

	/**
	 * holds timeout ID for reconnect timer
	 */
	this.timeout;

	/**
	 *
	 * @function
	 */
	this.connect = function() {
		that.restartTimer();

		// reset these values on connection
		isReading    = false;
		amountRead   = 0;
		streamBuffer = "";

		var request = createStreamRequest(that.opts.userstream_url, that.opts.auth);
		that.stream = new air.URLStream();
		that.stream.addEventListener(air.IOErrorEvent.IO_ERROR, errorReceived);
		that.stream.addEventListener(air.ProgressEvent.PROGRESS, dataReceived);
		that.stream.load(request);
	};

	/**
	 *
	 * @function
	 */
	this.disconnect = function() {
		if (that.timeout) {
			clearTimeout(that.timeout);
		}

		that.stream.close();
		that.stream = null;
	};

	/**
	 *
	 * @function
	 */
	this.restartTimer = function() {
		sch.error('Restarting timer');

		if (this.timeout) {
			clearTimeout(this.timeout);
		}

		this.timeout = setTimeout(
			function() {
				sch.error('Reconnecting!');
				that.disconnect();
				that.connect();
			},
			90000 // 90 second timeout
		);
	};

	function createStreamRequest(username, pass) {
		var request = new air.URLRequest(that.opts.userstream_url);
		var auth_header = that.opts.auth.signRequest(air.URLRequestMethod.POST, that.opts.userstream_url, '');
		sch.debug('auth_header:'+auth_header);
		request.requestHeaders = new Array(new air.URLRequestHeader("Authorization", auth_header));
		request.method = air.URLRequestMethod.POST;
		request.data = '';
		return request;
	}

	function errorReceived(e) {
		sch.error("errorReceived in stream");
		if (that.opts.onError) {
			that.opts.onError.call(this, e);
		}
	}

	function dataReceived(e) {
		sch.debug("dataReceived");
		sch.debug(e.toString());

		that.restartTimer();

		var toRead = e.bytesLoaded - amountRead;
		sch.debug("toRead:"+toRead);
		var buffer = that.stream.readUTFBytes(toRead);
		sch.debug("buffer:"+buffer);
		amountRead = e.bytesLoaded;
		sch.debug("amountRead:"+amountRead);

		var parts = [];
		if (!isReading) {
			parts = buffer.split(/\n/);
			var firstPart = parts[0].replace(/[\s\n]*/, "");
			sch.debug("firstPart:"+firstPart);
			buffer = parts.slice(1).join("\n");
			sch.debug("buffer:"+buffer);
			isReading = true;
		}

		// pump the JSON pieces through
		if ((toRead > 0) && (amountRead > 0)) {
			streamBuffer += buffer;
			sch.debug("streamBuffer:"+streamBuffer);
			parts = streamBuffer.split(/\n/);
			sch.debug("parts:"+parts);
			var lastElement = parts.pop();
			for (var i=0; i < parts.length; i++) {
				sch.debug('parts['+i+']:'+parts[i]);
				if (that.opts.onData) {
					that.opts.onData.call(this, parts[i]);
				}
			}
			streamBuffer = lastElement;
			sch.debug("streamBuffer:"+streamBuffer);
		}
	}
};
<|endoftext|>


<commit_before>const cloneDeep = require('lodash/cloneDeep');

const config = cloneDeep(require('../default.config'));

const { formats: { AccessToken: FORMAT } } = global.TEST_CONFIGURATION_DEFAULTS;

config.formats = {
  default: FORMAT,
};

module.exports = {
  config,
};
<commit_msg>test: fix not running the right formats<commit_after>const cloneDeep = require('lodash/cloneDeep');

const config = cloneDeep(require('../default.config'));

module.exports = {
  config,
};
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var extend = require('extend-shallow');
var debug = require('debug')('base:verb:generator');
var middleware = require('common-middleware');
var copyright = require('helper-copyright');
var reflinks = require('helper-reflinks');
var related = require('helper-related');
var apidocs = require('helper-apidocs');
var issue = require('helper-issue');

module.exports = function(verb, base) {
  // verb.invoke('verb-generate-templates');
  // verb.invoke('verb-generate-includes');
  verb.register('toc', require('./toc'));
  verb.invoke('toc');

  verb.task('data', function(cb) {
    verb.data({
      runner: {
        name: 'verb',
        url: 'https://github.com/verbose/verb',
        version: '0.9.0'
      }
    });

    verb.data({year: new Date().getFullYear()});
    verb.data(verb.pkg.data);
    verb.data({
      author: {
        name: 'Jon Schlinkert',
        username: 'jonschlinkert',
        twitter: 'jonschlinkert',
        url: 'https://github.com/jonschlinkert'
      }
    });

    // add "Released under..." statement
    formatLicense(verb);

    debug('data finished');
    cb();
  });

  verb.task('helpers', function(cb) {
    verb.asyncHelper('related', related({verbose: true}));
    verb.asyncHelper('reflinks', reflinks({verbose: true}));

    verb.helper('apidocs', apidocs());
    verb.helper('date', require('helper-date'));
    verb.helper('copyright', copyright({linkify: true}));
    verb.helper('issue', function(options) {
      var opts = extend({}, this.context, options);
      opts.owner = opts.owner || opts.author && opts.author.username;
      opts.repo = opts.name;
      return issue(opts);
    });

    cb();
  });

  verb.task('create', function(cb) {
    verb.use(middleware());

    verb.create('docs');
    verb.create('badges', {viewType: 'partial', engine: '*' });
    verb.create('includes', {viewType: 'partial', engine: '*' });
    verb.create('layouts', {viewType: 'layout', engine: '*' });
    cb();
  });

  verb.task('templates', ['create', 'helpers', 'data'], function(cb) {
    verb.engine('*', require('engine-base'), { delims: ['{%', '%}'] });

    debug('adding templates');
    verb.layout('default', {contents: read(verb, 'layout.md')});

    debug('adding templates');
    if (fs.existsSync(path.resolve(verb.cwd, '.verb.md'))) {
      verb.doc('readme.md', {contents: read(verb, '.verb.md', verb.cwd), layout: 'default'});
    } else {
      verb.doc('readme.md', {contents: read(verb, '.verb.md'), layout: 'default'});
    }

    debug('adding includes');
    verb.includes(require('./templates/includes'));
    verb.badges(require('./templates/badges'));

    debug('templates finished');
    cb();
  });

  verb.task('readme', ['templates'], function(cb) {
    var tocCreate = verb.plugin('toc.create');
    var tocInject = verb.plugin('toc.inject');

    return verb.src('.verb.md', {cwd: verb.cwd})
      .pipe(tocCreate)
      .pipe(verb.renderFile('*'))
      .pipe(verb.pipeline(verb.options.pipeline))
      .pipe(tocInject)
      .pipe(verb.dest(function(file) {
        file.basename = 'readme.md';
        return verb.cwd;
      }))
  });

  verb.task('default', ['readme']);
};

function read(app, fp, cwd) {
  return fs.readFileSync(path.resolve(cwd || app.env.templates, fp));
}

/**
 * Add "Released under..." statement to license from
 * package.json.
 *
 * @param {Object} `verb`
 * @return {undefined}
 */

function formatLicense(verb) {
  var license = verb.data('license') || 'MIT';
  var fp = path.resolve(verb.cwd, 'LICENSE');
  if (fs.existsSync(fp)) {
    var url = repoFile(verb.data('repository'), 'LICENSE');
    license = '[' + license + ' license](' + url + ').';
  } else {
    license += ' license.'
  }
  verb.data({license: 'Released under the ' + license});
}

function repoFile(repo, filename) {
  return 'https://github.com/' + repo + '/blob/master/' + filename;
}
<commit_msg>update verbfile with helpers, update toc logic<commit_after>'use strict';

var fs = require('fs');
var path = require('path');
var extend = require('extend-shallow');
var debug = require('debug')('base:verb:generator');
var middleware = require('common-middleware');
var copyright = require('helper-copyright');
var reflinks = require('helper-reflinks');
var related = require('helper-related');
var apidocs = require('helper-apidocs');
var issue = require('helper-issue');
var date = require('helper-date');
var engine = require('engine-base');
var getPkg = require('get-pkg');
var get = require('get-value');
var toc = require('./toc');

module.exports = function(verb, base) {
  verb.register('toc', toc);
  verb.invoke('toc');

  verb.task('data', function(cb) {
    verb.data({
      runner: {
        name: 'verb',
        url: 'https://github.com/verbose/verb',
        version: '0.9.0'
      }
    });

    verb.data({year: new Date().getFullYear()});
    verb.data(verb.pkg.data);
    verb.data({
      author: {
        name: 'Jon Schlinkert',
        username: 'jonschlinkert',
        twitter: 'jonschlinkert',
        url: 'https://github.com/jonschlinkert'
      }
    });

    // Create a license statement from license in from package.json
    formatLicense(verb);

    debug('data finished');
    cb();
  });

  verb.task('helpers', function(cb) {
    verb.asyncHelper('related', related({verbose: true}));
    verb.asyncHelper('reflinks', reflinks({verbose: true}));
    verb.asyncHelper('pkg', function(name, prop, cb) {
      if (typeof prop === 'function') {
        cb = prop;
        prop = null;
      }
      getPkg(name, function(err, pkg) {
        if (err) return cb(err);
        cb(null, prop ? get(pkg, prop) : pkg);
      });
    });

    verb.helper('apidocs', apidocs());
    verb.helper('date', date);
    verb.helper('copyright', copyright({linkify: true}));
    verb.helper('issue', function(options) {
      var opts = extend({}, this.context, options);
      opts.owner = opts.owner || opts.author && opts.author.username;
      opts.repo = opts.name;
      return issue(opts);
    });

    cb();
  });

  verb.task('create', function(cb) {
    verb.use(middleware());

    verb.create('docs');
    verb.create('badges', {viewType: 'partial', engine: '*' });
    verb.create('includes', {viewType: 'partial', engine: '*' });
    verb.create('layouts', {viewType: 'layout', engine: '*' });
    cb();
  });

  verb.task('templates', ['create', 'helpers', 'data'], function(cb) {
    verb.engine('*', engine, { delims: ['{%', '%}'] });

    debug('adding templates');
    verb.layout('default', {contents: read(verb, 'default.md')});

    debug('adding .verb.md');
    if (fs.existsSync(path.resolve(verb.cwd, '.verb.md'))) {
      verb.doc('readme.md', {contents: read(verb, '.verb.md', verb.cwd)});
    } else {
      verb.doc('readme.md', {contents: read(verb, '.verb.md'), layout: 'default'});
    }

    debug('adding includes');
    verb.includes(require('./templates/includes'));
    verb.badges(require('./templates/badges'));

    debug('templates finished');
    cb();
  });

  verb.task('readme', ['templates'], function(cb) {
    return verb.src('.verb.md', {cwd: verb.cwd})
      .pipe(verb.renderFile('*'))
      .pipe(verb.pipeline(verb.options.pipeline))
      .pipe(verb.dest(function(file) {
        file.basename = 'readme.md';
        return verb.cwd;
      }))
  });

  verb.task('default', ['readme']);
};

function read(app, fp, cwd) {
  cwd = cwd || app.env.templates || path.join(__dirname, 'templates');
  return fs.readFileSync(path.resolve(cwd, fp));
}

/**
 * Add "Released under..." statement to license from
 * package.json.
 *
 * @param {Object} `verb`
 * @return {undefined}
 */

function formatLicense(verb) {
  var license = verb.data('license') || 'MIT';
  var fp = path.resolve(verb.cwd, 'LICENSE');
  if (fs.existsSync(fp)) {
    var url = repoFile(verb.data('repository'), 'LICENSE');
    license = '[' + license + ' license](' + url + ').';
  } else {
    license += ' license.'
  }
  verb.data({license: 'Released under the ' + license});
}

function repoFile(repo, filename) {
  return 'https://github.com/' + repo + '/blob/master/' + filename;
}
<|endoftext|>


<commit_before>function solve() {
    const MAX_SYMB = 20,
        MIN_SYMB = 1,
        MAX_VOLT = 20,
        MIN_VOLT = 5;

    const validate = {
        ifNumber: function(val, name) {
            name = name || 'Value';
            if (typeof val !== 'number') {
                throw new Error(name + ' must be a number!');
            }
        },
        ifPositiveNumber: function(val, name) {
            name = name || 'Value';
            validate.ifNumber(val, name);
            if (val <= 0) {
                throw new Error(name + ' must be positive number above zero!');
            }
        },
        ifIsPositiveInteger: function(val, name) {
            name = name || 'Value';
            validate.ifPositiveNumber(val, name);
            if (!Number.isInteger(val)) {
                throw new Error(name + ' must be a positiwe integer above zero!');
            }
        },
        ifNumberBetween(val, v1, v2, name) {
            name = name || 'Value';
            validate.ifPositiveNumber(val, name);
            if (val < v1 || val > v2) {
                throw new Error(name + ' must be between ' + v1 + ' and ' + v2 + '!');
            }
        },
        ifString: function(val, name) {
            name = name || 'Value';
            if (typeof val !== 'string') {
                throw new Error(name + ' must be a string!');
            }
        },
        ifCorrectLength: function(val, name) {
            name = name || 'Value';
            validate.ifString(val, name);
            if (val.length < MIN_SYMB || val.length > MAX_SYMB) {
                throw new Error(name + ' must be between ' + MIN_SYMB + ' and ' + MAX_SYMB + ' symbols long!');
            }
        },
        ifCorrectOpSystem: function(val) {
            validate.ifString(val, 'OperatingSystem');
            if (val.length < MIN_SYMB || val.length > MAX_SYMB / 2) {
                throw new Error('OperatingSystem must be between ' + MIN_SYMB + ' and ' + MAX_SYMB / 2 + ' symbols long!');
            }
        },
        ifCorrectQuality: function(val) {
            validate.ifString(val, 'Quality');
            if (val !== 'high' && val !== 'mid' && val !== 'low') {
                throw new Error('Quality must be one of "high", "mid" or "low!"');
            }
        }
    };

    function clone(obj) {
        if (null === obj || "object" != typeof obj) return obj;
        var copy = {};
        for (var attr in obj) {
            if (obj.hasOwnProperty(attr)) {
                copy[attr] = obj[attr];
            }
        }
        return copy;
    }

    const getId = (function() {
        let id = 0;
        return function() {
            id += 1;
            return id;
        };
    }());

    class Product {
        constructor(manufacturer, model, price) {
            this.count = 0;
            this.id = getId();
            this.manufacturer = manufacturer;
            this.model = model;
            this.price = price;
        }

        get manufacturer() {
            return this._manufacturer;
        }

        set manufacturer(val) {
            validate.ifCorrectLength(val, 'manufacturer');
            this._manufacturer = val;
        }

        get model() {
            return this._model;
        }

        set model(val) {
            validate.ifCorrectLength(val, 'Model');
            this._model = val;
        }

        get price() {
            return this._price;
        }

        set price(val) {
            validate.ifPositiveNumber(val, 'Price');
            this._price = val;
        }

        getLabel() {
            return ' - ' + this.manufacturer + ' ' + this.model + ' - **' + this.price + '**';
        }
    }

    class SmartPhone extends Product {
        constructor(manufacturer, model, price, screenSize, operatingSystem) {
            super(manufacturer, model, price);
            this.count = 0;
            this.id = getId();
            this.screenSize = screenSize;
            this.operatingSystem = operatingSystem;
        }

        get screenSize() {
            return this._screenSize;
        }

        set screenSize(val) {
            validate.ifPositiveNumber(val, 'ScreenSize');
            this._screenSize = val;
        }

        get operatingSystem() {
            return this._operatingSystem;
        }

        set operatingSystem(val) {
            validate.ifCorrectOpSystem(val);
            this._operatingSystem = val;
        }

        getLabel() {
            return 'SmartPhone' + super.getLabel();
        }
    }

    class Charger extends Product {
        constructor(manufacturer, model, price, outputVoltage, outputCurrent) {
            super(manufacturer, model, price);
            this.count = 0;
            this.id = getId();
            this.outputVoltage = outputVoltage;
            this.outputCurrent = outputCurrent;
        }

        get outputVoltage() {
            return this._outputVoltage;
        }

        set outputVoltage(val) {
            validate.ifNumberBetween(val, 5, 20, 'Voltage');
            this._outputVoltage = val;
        }

        get outputCurrent() {
            return this._outputCurrent;
        }

        set outputCurrent(val) {
            validate.ifNumberBetween(val, 100, 3000, 'Current');
            this._outputCurrent = val;
        }

        getLabel() {
            return 'Charger' + super.getLabel();
        }
    }

    class Router extends Product {
        constructor(manufacturer, model, price, wifiRange, lanPorts) {
            super(manufacturer, model, price);
            this.count = 0;
            this.id = getId();
            this.wifiRange = wifiRange;
            this.lanPorts = lanPorts;
        }

        get wifiRange() {
            return this._wifiRange;
        }

        set wifiRange(val) {
            validate.ifPositiveNumber(val, 'WifiRange');
            this._wifiRange = val;
        }

        get lanPorts() {
            return this._lanPorts;
        }

        set lanPorts(val) {
            validate.ifIsPositiveInteger(val, 'LanPorts');
            this._lanPorts = val;
        }

        getLabel() {
            return 'Router' + super.getLabel();
        }
    }

    class Headphones extends Product {
        constructor(manufacturer, model, price, quality, hasMicrophone) {
            super(manufacturer, model, price);
            this.count = 0;
            this.id = getId();
            this.quality = quality;
            this.hasMicrophone = hasMicrophone;
        }

        get quality() {
            return this._quality;
        }

        set quality(val) {
            validate.ifCorrectQuality(val);
            this._quality = val;
        }

        get hasMicrophone() {
            return this._hasMicrophone;
        }

        set hasMicrophone(val) {
            this._hasMicrophone = (val) ? true : false;
        }

        getLabel() {
            return 'Headphones' + super.getLabel();
        }
    }

    class HardwareStore {
        constructor(name) {
            this.name = name;
            this.products = [];
            this.money = 0;
        }

        get name() {
            return this._name;
        }

        set name(val) {
            validate.ifCorrectLength(val, 'Name');
            this._name = val;
        }

        stock(product, quantity) {
            validate.ifIsPositiveInteger(quantity, 'Quantity');
            if (!(product instanceof Product)) {
                throw new Error('Product must be instance of Product!');
            }
            let searched = this.products.find(x => x.id === product.id);
            if (this.products.indexOf(searched) >= 0) {
                searched.count += quantity;
            } else {
                product.count = quantity;
                this.products.push(product);
            }
            return this;
        }

        sell(productId, quantity) {
            validate.ifIsPositiveInteger(quantity, 'Quantity');
            let foundProduct = this.products.find(x => x.id === productId);
            if (foundProduct.count < quantity) {
                throw new Error('Quantity is not enough to cell!');
            }

            let foundIndex = this.products.indexOf(foundProduct);
            if (foundProduct.count === quantity) {
                this.products.splice(foundIndex, 1);
            } else {
                foundProduct.count -= quantity;
            }
            this.money += foundProduct.price * quantity;
            return this;
        }

        getSold() {
            return this.money;
        }

        search(x) {
            if (typeof x === 'string') {
                x = x.toLowerCase();
                return this.products.filter(p => (p.manufacturer.toLowerCase().indexOf(x) >= 0 || p.model.toLowerCase().indexOf(x) >= 0)).map(function(f) {
                    return ({ product: f, quantity: f.count });
                });
            } else if (typeof x === 'object') {
                return this.products
                    .filter(function(p) {
                        let isProduct = true;
                        if (x.hasOwnProperty('manufacturerPattern')) {
                            isProduct = p.manufacturer.indexOf(x.manufacturerPattern) >= 0;
                            if (isProduct === false) return false;
                        }
                        if (x.hasOwnProperty('modelPattern')) {
                            isProduct = p.model.indexOf(x.modelPattern) >= 0;
                            if (isProduct === false) return false;
                        }
                        if (x.hasOwnProperty('type')) {
                            isProduct = p.constructor.name === x.type;
                            if (isProduct === false) return false;
                        }
                        if (x.hasOwnProperty('minPrice')) {
                            isProduct = p.price >= x.minPrice;
                            if (isProduct === false) return false;
                        }
                        if (x.hasOwnProperty('maxPrice')) {
                            isProduct = p.price <= x.maxPrice;
                            if (isProduct === false) return false;
                        }
                        return true;
                    })
                    .map(function(f) {
                        return ({ product: f, quantity: f.count });
                    });
            } else {
                throw new Error('Options are not set properly!');
            }
        }
    }

    return {
        getSmartPhone(manufacturer, model, price, screenSize, operatingSystem) {
            // returns SmarhPhone instance
            return new SmartPhone(manufacturer, model, price, screenSize, operatingSystem);
        },
        getCharger(manufacturer, model, price, outputVoltage, outputCurrent) {
            // returns Charger instance
            return new Charger(manufacturer, model, price, outputVoltage, outputCurrent);
        },
        getRouter(manufacturer, model, price, wifiRange, lanPorts) {
            // returns Router instance
            return new Router(manufacturer, model, price, wifiRange, lanPorts);
        },
        getHeadphones(manufacturer, model, price, quality, hasMicrophone) {
            // returns Headphones instance
            return new Headphones(manufacturer, model, price, quality, hasMicrophone);
        },
        getHardwareStore(name) {
            // returns HardwareStore instance
            return new HardwareStore(name);
        }
    };
}

// Submit the code above this line in bgcoder.com
module.exports = solve; // DO NOT SUBMIT THIS LINE

// tests

const result = solve();

const phone = result.getSmartPhone('HTC', 'One', 903, 5, 'Android');

console.log(phone.getLabel()); // SmartPhone - HTC One - **903**

const headphones = result.getHeadphones('Sennheiser', 'PXC 550 Wireless', 340, 'high', false);
const store = result.getHardwareStore('Magazin');

store.stock(phone, 1)
    .stock(headphones, 15);

console.log(store.search('senn'));
/*
[ { product:
     Headphones { ... },
    quantity: 15 } ]
*/

console.log(store.search({ type: 'SmartPhone', maxPrice: 1000 }));
/*
[ { product:
     SmartPhone { ... },
    quantity: 1 } ]
*/

console.log(store.search({ type: 'SmartPhone', maxPrice: 900 }));
/* [] */

store.sell(headphones.id, 2);
console.log(store.getSold()); // 680<commit_msg>remove lets in last HW for UI&DOM<commit_after>'use strict';

function solve() {
    const MAX_SYMB = 20,
        MIN_SYMB = 1,
        MAX_VOLT = 20,
        MIN_VOLT = 5;

    const validate = {
        ifNumber: function(val, name) {
            name = name || 'Value';
            if (typeof val !== 'number') {
                throw new Error(name + ' must be a number!');
            }
        },
        ifPositiveNumber: function(val, name) {
            name = name || 'Value';
            validate.ifNumber(val, name);
            if (val <= 0) {
                throw new Error(name + ' must be positive number above zero!');
            }
        },
        ifIsPositiveInteger: function(val, name) {
            name = name || 'Value';
            validate.ifPositiveNumber(val, name);
            if (!Number.isInteger(val)) {
                throw new Error(name + ' must be a positiwe integer above zero!');
            }
        },
        ifNumberBetween(val, v1, v2, name) {
            name = name || 'Value';
            validate.ifPositiveNumber(val, name);
            if (val < v1 || val > v2) {
                throw new Error(name + ' must be between ' + v1 + ' and ' + v2 + '!');
            }
        },
        ifString: function(val, name) {
            name = name || 'Value';
            if (typeof val !== 'string') {
                throw new Error(name + ' must be a string!');
            }
        },
        ifCorrectLength: function(val, name) {
            name = name || 'Value';
            validate.ifString(val, name);
            if (val.length < MIN_SYMB || val.length > MAX_SYMB) {
                throw new Error(name + ' must be between ' + MIN_SYMB + ' and ' + MAX_SYMB + ' symbols long!');
            }
        },
        ifCorrectOpSystem: function(val) {
            validate.ifString(val, 'OperatingSystem');
            if (val.length < MIN_SYMB || val.length > MAX_SYMB / 2) {
                throw new Error('OperatingSystem must be between ' + MIN_SYMB + ' and ' + MAX_SYMB / 2 + ' symbols long!');
            }
        },
        ifCorrectQuality: function(val) {
            validate.ifString(val, 'Quality');
            if (val !== 'high' && val !== 'mid' && val !== 'low') {
                throw new Error('Quality must be one of "high", "mid" or "low!"');
            }
        }
    };

    function clone(obj) {
        if (null === obj || "object" != typeof obj) return obj;
        var copy = {};
        for (var attr in obj) {
            if (obj.hasOwnProperty(attr)) {
                copy[attr] = obj[attr];
            }
        }
        return copy;
    }

    const getId = (function() {
        let id = 0;
        return function() {
            id += 1;
            return id;
        };
    }());

    class Product {
        constructor(manufacturer, model, price) {
            this.count = 0;
            this.id = getId();
            this.manufacturer = manufacturer;
            this.model = model;
            this.price = price;
        }

        get manufacturer() {
            return this._manufacturer;
        }

        set manufacturer(val) {
            validate.ifCorrectLength(val, 'manufacturer');
            this._manufacturer = val;
        }

        get model() {
            return this._model;
        }

        set model(val) {
            validate.ifCorrectLength(val, 'Model');
            this._model = val;
        }

        get price() {
            return this._price;
        }

        set price(val) {
            validate.ifPositiveNumber(val, 'Price');
            this._price = val;
        }

        getLabel() {
            return ' - ' + this.manufacturer + ' ' + this.model + ' - **' + this.price + '**';
        }
    }

    class SmartPhone extends Product {
        constructor(manufacturer, model, price, screenSize, operatingSystem) {
            super(manufacturer, model, price);
            this.count = 0;
            this.id = getId();
            this.screenSize = screenSize;
            this.operatingSystem = operatingSystem;
        }

        get screenSize() {
            return this._screenSize;
        }

        set screenSize(val) {
            validate.ifPositiveNumber(val, 'ScreenSize');
            this._screenSize = val;
        }

        get operatingSystem() {
            return this._operatingSystem;
        }

        set operatingSystem(val) {
            validate.ifCorrectOpSystem(val);
            this._operatingSystem = val;
        }

        getLabel() {
            return 'SmartPhone' + super.getLabel();
        }
    }

    class Charger extends Product {
        constructor(manufacturer, model, price, outputVoltage, outputCurrent) {
            super(manufacturer, model, price);
            this.count = 0;
            this.id = getId();
            this.outputVoltage = outputVoltage;
            this.outputCurrent = outputCurrent;
        }

        get outputVoltage() {
            return this._outputVoltage;
        }

        set outputVoltage(val) {
            validate.ifNumberBetween(val, 5, 20, 'Voltage');
            this._outputVoltage = val;
        }

        get outputCurrent() {
            return this._outputCurrent;
        }

        set outputCurrent(val) {
            validate.ifNumberBetween(val, 100, 3000, 'Current');
            this._outputCurrent = val;
        }

        getLabel() {
            return 'Charger' + super.getLabel();
        }
    }

    class Router extends Product {
        constructor(manufacturer, model, price, wifiRange, lanPorts) {
            super(manufacturer, model, price);
            this.count = 0;
            this.id = getId();
            this.wifiRange = wifiRange;
            this.lanPorts = lanPorts;
        }

        get wifiRange() {
            return this._wifiRange;
        }

        set wifiRange(val) {
            validate.ifPositiveNumber(val, 'WifiRange');
            this._wifiRange = val;
        }

        get lanPorts() {
            return this._lanPorts;
        }

        set lanPorts(val) {
            validate.ifIsPositiveInteger(val, 'LanPorts');
            this._lanPorts = val;
        }

        getLabel() {
            return 'Router' + super.getLabel();
        }
    }

    class Headphones extends Product {
        constructor(manufacturer, model, price, quality, hasMicrophone) {
            super(manufacturer, model, price);
            this.count = 0;
            this.id = getId();
            this.quality = quality;
            this.hasMicrophone = hasMicrophone;
        }

        get quality() {
            return this._quality;
        }

        set quality(val) {
            validate.ifCorrectQuality(val);
            this._quality = val;
        }

        get hasMicrophone() {
            return this._hasMicrophone;
        }

        set hasMicrophone(val) {
            this._hasMicrophone = (val) ? true : false;
        }

        getLabel() {
            return 'Headphones' + super.getLabel();
        }
    }

    class HardwareStore {
        constructor(name) {
            this.name = name;
            this.products = [];
            this.money = 0;
        }

        get name() {
            return this._name;
        }

        set name(val) {
            validate.ifCorrectLength(val, 'Name');
            this._name = val;
        }

        stock(product, quantity) {
            validate.ifIsPositiveInteger(quantity, 'Quantity');
            if (!(product instanceof Product)) {
                throw new Error('Product must be instance of Product!');
            }
            let searched = this.products.find(x => x.id === product.id);
            if (this.products.indexOf(searched) >= 0) {
                searched.count += quantity;
            } else {
                product.count = quantity;
                this.products.push(product);
            }
            return this;
        }

        sell(productId, quantity) {
            validate.ifIsPositiveInteger(quantity, 'Quantity');
            let foundProduct = this.products.find(x => x.id === productId);
            if (foundProduct.count < quantity) {
                throw new Error('Quantity is not enough to cell!');
            }

            let foundIndex = this.products.indexOf(foundProduct);
            if (foundProduct.count === quantity) {
                this.products.splice(foundIndex, 1);
            } else {
                foundProduct.count -= quantity;
            }
            this.money += foundProduct.price * quantity;
            return this;
        }

        getSold() {
            return this.money;
        }

        search(x) {
            if (typeof x === 'string') {
                x = x.toLowerCase();
                return this.products.filter(p => (p.manufacturer.toLowerCase().indexOf(x) >= 0 || p.model.toLowerCase().indexOf(x) >= 0)).map(function(f) {
                    return ({ product: f, quantity: f.count });
                });
            } else if (typeof x === 'object') {
                return this.products
                    .filter(function(p) {
                        let isProduct = true;
                        if (x.hasOwnProperty('manufacturerPattern')) {
                            isProduct = p.manufacturer.indexOf(x.manufacturerPattern) >= 0;
                            if (isProduct === false) return false;
                        }
                        if (x.hasOwnProperty('modelPattern')) {
                            isProduct = p.model.indexOf(x.modelPattern) >= 0;
                            if (isProduct === false) return false;
                        }
                        if (x.hasOwnProperty('type')) {
                            isProduct = p.constructor.name === x.type;
                            if (isProduct === false) return false;
                        }
                        if (x.hasOwnProperty('minPrice')) {
                            isProduct = p.price >= x.minPrice;
                            if (isProduct === false) return false;
                        }
                        if (x.hasOwnProperty('maxPrice')) {
                            isProduct = p.price <= x.maxPrice;
                            if (isProduct === false) return false;
                        }
                        return true;
                    })
                    .map(function(f) {
                        return ({ product: f, quantity: f.count });
                    });
            } else {
                throw new Error('Options are not set properly!');
            }
        }
    }

    return {
        getSmartPhone(manufacturer, model, price, screenSize, operatingSystem) {
            // returns SmarhPhone instance
            return new SmartPhone(manufacturer, model, price, screenSize, operatingSystem);
        },
        getCharger(manufacturer, model, price, outputVoltage, outputCurrent) {
            // returns Charger instance
            return new Charger(manufacturer, model, price, outputVoltage, outputCurrent);
        },
        getRouter(manufacturer, model, price, wifiRange, lanPorts) {
            // returns Router instance
            return new Router(manufacturer, model, price, wifiRange, lanPorts);
        },
        getHeadphones(manufacturer, model, price, quality, hasMicrophone) {
            // returns Headphones instance
            return new Headphones(manufacturer, model, price, quality, hasMicrophone);
        },
        getHardwareStore(name) {
            // returns HardwareStore instance
            return new HardwareStore(name);
        }
    };
}

// Submit the code above this line in bgcoder.com
module.exports = solve; // DO NOT SUBMIT THIS LINE

// tests

const result = solve();

const phone = result.getSmartPhone('HTC', 'One', 903, 5, 'Android');

console.log(phone.getLabel()); // SmartPhone - HTC One - **903**

const headphones = result.getHeadphones('Sennheiser', 'PXC 550 Wireless', 340, 'high', false);
const store = result.getHardwareStore('Magazin');

store.stock(phone, 1)
    .stock(headphones, 15);

console.log(store.search('senn'));
/*
[ { product:
     Headphones { ... },
    quantity: 15 } ]
*/

console.log(store.search({ type: 'SmartPhone', maxPrice: 1000 }));
/*
[ { product:
     SmartPhone { ... },
    quantity: 1 } ]
*/

console.log(store.search({ type: 'SmartPhone', maxPrice: 900 }));
/* [] */

store.sell(headphones.id, 2);
console.log(store.getSold()); // 680<|endoftext|>