<commit_before>import { virtualDom } from 'vdom';
import { DNATemplateComponent } from '../dna-template-component.js';
import { registry } from '../dna-helper.js';

function getCtr(node) {
    return registry(node.getAttribute('is')) || registry(node.tagName);
}

/**
 * A virtualDom hook for life cycle handling.
 * @private
 * @class DNALifeCycleHook
 */
class DNALifeCycleHook {
    hook(node) {
        if (node.__virtualDomCreated !== true) {
            this.define(node, '__virtualDomCreated', true, false);
            this.trigger('createdCallback');
        }
        this.isAttached(node);
    }

    isAttached(node) {
        if (this.parentNode && node.__virtualDomAttached !== true) {
            this.define(node, '__virtualDomAttached', true);
            this.trigger('attachedCallback');
        } else if (!this.parentNode && node.__virtualDomAttached === true) {
            this.define(node, '__virtualDomAttached', false);
            this.trigger('detachedCallback');
        }
    }

    trigger(name, ...args) {
        if (typeof this[name] === 'function') {
            this[name].apply(this, args);
        }
    }

    define(node, prop, value, writable = true) {
        Object.defineProperty(node, prop, {
            configurable: writable,
            value,
        });
    }
}

/**
 * A virtualDom hook for attributes handling.
 * @private
 * @class DNAAttributeHook
 */
class DNAAttributeHook {
    constructor(value, namespace) {
        this.value = value;
        this.namespace = namespace;
    }

    hook(node, propertyName, oldValue) {
        let value = this.value;
        let old = oldValue && oldValue.value;
        if (old !== value) {
            if (value !== undefined && value !== null) {
                if (this.namespace) {
                    node.removeAttribute(propertyName);
                    node.setAttributeNS(this.namespace, propertyName, value);
                } else {
                    node.setAttribute(propertyName, value);
                }
            } else if (oldValue) {
                if (this.namespace) {
                    node.removeAttributeNS(this.namespace, propertyName);
                } else {
                    node.removeAttribute(propertyName);
                }
            }
            if (typeof node.attributeChangedCallback === 'function') {
                node.attributeChangedCallback(propertyName, old, value);
            }
        }
    }
}

/**
 * Extract node's attributes.
 * @private
 * @param {Node} node The node to parse.
 * @return {Object} A key => value object with node's attributes.
 */
function attributesToProp(node, options = {}, hooks = true) {
    let res = {};
    Array.prototype.forEach.call(node.attributes || [], (attr) => {
        if (hooks && attr.name !== 'is') {
            res[attr.name] = new DNAAttributeHook(attr.value, options.namespace);
        } else {
            res[attr.name] = attr.value;
        }
    });
    return res;
}

/**
 * Convert a Node to a VDOM Node.
 * @private
 * @param {Node} node The node to convert.
 * @param {Object} parentOptions The node's parent options (optional).
 * @return {Object} A VDOM Node.
 */
function nodeToVDOM(node, parentOptions = {}) {
    if (typeof node === 'undefined' || node.nodeType === Node.COMMENT_NODE) {
        return false;
    } else if (node.nodeType === Node.TEXT_NODE) {
        return new virtualDom.VText(node.textContent);
    }
    let options = {};
    for (let k in parentOptions) {
        if (parentOptions.hasOwnProperty(k)) {
            options[k] = parentOptions[k];
        }
    }
    if (node.tagName && node.tagName.toLowerCase() === 'svg') {
        options.namespace = 'http://www.w3.org/2000/svg';
    }
    let Ctr = getCtr(node);
    let useHooks = options.hooks && typeof Ctr === 'function';
    let properties = attributesToProp(node, options, useHooks);
    if (useHooks) {
        properties['life-cycle-hook'] = new DNALifeCycleHook();
    } else {
        properties = {
            attributes: properties,
        };
    }
    let childNodes = Array.prototype.filter.call(node.childNodes || [], (n) =>
        n && n instanceof Node && n.nodeType !== Node.COMMENT_NODE
    );
    return new virtualDom.VNode(
        node.tagName,
        properties,
        childNodes.map((n) => nodeToVDOM(n, options)),
        undefined,
        options.namespace
    );
}

/**
 * Same as DNATemplateComponent, but with VDOM support.
 * This component is available only including /dna\.vdom(\-?.*)\.js/ libraries.
 * @class DNAVDomComponent
 * @extends DNATemplateComponent
 *
 * @example
 * my-component.js
 * ```js
 * import { DNAVDomComponent } from 'dna/component';
 * export class MyComponent extends DNAVDomComponent {
 *   static get template() {
 *     return `<h1>${this.name}</h1>`;
 *   }
 *   get name() {
 *     return 'Newton';
 *   }
 * }
 * ```
 * app.js
 * ```js
 * import { Register } from 'dna/component';
 * import { MyComponent } from './components/my-component/my-component.js';
 * var MyElement = Register(MyComponent);
 * var element = new MyElement();
 * console.log(element.innerHTML); // logs "<h1>Newton</h1>"
 * ```
 */
export class DNAVDomComponent extends DNATemplateComponent {
    /**
     * Use virtualDom hooks for component life-cycle.
     */
    static get useVirtualDomHooks() {
        return true;
    }

    /**
     * Update Component child nodes using VDOM trees.
     */
    updateViewContent() {
        // Render the template
        let html = this.getViewContent();
        if (html !== null) {
            let tmp = document.createElement('div');
            this._vtree = this._vtree || nodeToVDOM(tmp);
            tmp.innerHTML = html;
            let tree = nodeToVDOM(tmp, {
                hooks: registry(this.is).useVirtualDomHooks,
            });
            let diff = virtualDom.diff(this._vtree || nodeToVDOM(), tree);
            virtualDom.patch(this, diff);
            this._vtree = tree;
        }
    }
}
<commit_msg>refactor: use DOMParser instaed of instantiate a DOMNode in DNAVDomComponent #3<commit_after>import { virtualDom } from 'vdom';
import { DNATemplateComponent } from '../dna-template-component.js';
import { registry } from '../dna-helper.js';

function getCtr(node) {
    return registry(node.getAttribute('is')) || registry(node.tagName);
}

/**
 * A virtualDom hook for life cycle handling.
 * @private
 * @class DNALifeCycleHook
 */
class DNALifeCycleHook {
    hook(node) {
        if (node.__virtualDomCreated !== true) {
            this.define(node, '__virtualDomCreated', true, false);
            this.trigger('createdCallback');
        }
        this.isAttached(node);
    }

    isAttached(node) {
        if (this.parentNode && node.__virtualDomAttached !== true) {
            this.define(node, '__virtualDomAttached', true);
            this.trigger('attachedCallback');
        } else if (!this.parentNode && node.__virtualDomAttached === true) {
            this.define(node, '__virtualDomAttached', false);
            this.trigger('detachedCallback');
        }
    }

    trigger(name, ...args) {
        if (typeof this[name] === 'function') {
            this[name].apply(this, args);
        }
    }

    define(node, prop, value, writable = true) {
        Object.defineProperty(node, prop, {
            configurable: writable,
            value,
        });
    }
}

/**
 * A virtualDom hook for attributes handling.
 * @private
 * @class DNAAttributeHook
 */
class DNAAttributeHook {
    constructor(value, namespace) {
        this.value = value;
        this.namespace = namespace;
    }

    hook(node, propertyName, oldValue) {
        let value = this.value;
        let old = oldValue && oldValue.value;
        if (old !== value) {
            if (value !== undefined && value !== null) {
                if (this.namespace) {
                    node.removeAttribute(propertyName);
                    node.setAttributeNS(this.namespace, propertyName, value);
                } else {
                    node.setAttribute(propertyName, value);
                }
            } else if (oldValue) {
                if (this.namespace) {
                    node.removeAttributeNS(this.namespace, propertyName);
                } else {
                    node.removeAttribute(propertyName);
                }
            }
            if (typeof node.attributeChangedCallback === 'function') {
                node.attributeChangedCallback(propertyName, old, value);
            }
        }
    }
}

/**
 * Extract node's attributes.
 * @private
 * @param {Node} node The node to parse.
 * @return {Object} A key => value object with node's attributes.
 */
function attributesToProp(node, options = {}, hooks = true) {
    let res = {};
    Array.prototype.forEach.call(node.attributes || [], (attr) => {
        if (hooks && attr.name !== 'is') {
            res[attr.name] = new DNAAttributeHook(attr.value, options.namespace);
        } else {
            res[attr.name] = attr.value;
        }
    });
    return res;
}

/**
 * Convert a Node to a VDOM Node.
 * @private
 * @param {Node} node The node to convert.
 * @param {Object} parentOptions The node's parent options (optional).
 * @return {Object} A VDOM Node.
 */
function nodeToVDOM(node, parentOptions = {}) {
    if (typeof node === 'undefined' || node.nodeType === Node.COMMENT_NODE) {
        return false;
    } else if (node.nodeType === Node.TEXT_NODE) {
        return new virtualDom.VText(node.textContent);
    }
    let options = {};
    for (let k in parentOptions) {
        if (parentOptions.hasOwnProperty(k)) {
            options[k] = parentOptions[k];
        }
    }
    if (node.tagName && node.tagName.toLowerCase() === 'svg') {
        options.namespace = 'http://www.w3.org/2000/svg';
    }
    let Ctr = getCtr(node);
    let useHooks = options.hooks && typeof Ctr === 'function';
    let properties = attributesToProp(node, options, useHooks);
    if (useHooks) {
        properties['life-cycle-hook'] = new DNALifeCycleHook();
    } else {
        properties = {
            attributes: properties,
        };
    }
    let childNodes = Array.prototype.filter.call(node.childNodes || [], (n) =>
        n && n instanceof Node && n.nodeType !== Node.COMMENT_NODE
    );
    return new virtualDom.VNode(
        node.tagName,
        properties,
        childNodes.map((n) => nodeToVDOM(n, options)),
        undefined,
        options.namespace
    );
}

/**
 * Same as DNATemplateComponent, but with VDOM support.
 * This component is available only including /dna\.vdom(\-?.*)\.js/ libraries.
 * @class DNAVDomComponent
 * @extends DNATemplateComponent
 *
 * @example
 * my-component.js
 * ```js
 * import { DNAVDomComponent } from 'dna/component';
 * export class MyComponent extends DNAVDomComponent {
 *   static get template() {
 *     return `<h1>${this.name}</h1>`;
 *   }
 *   get name() {
 *     return 'Newton';
 *   }
 * }
 * ```
 * app.js
 * ```js
 * import { Register } from 'dna/component';
 * import { MyComponent } from './components/my-component/my-component.js';
 * var MyElement = Register(MyComponent);
 * var element = new MyElement();
 * console.log(element.innerHTML); // logs "<h1>Newton</h1>"
 * ```
 */
export class DNAVDomComponent extends DNATemplateComponent {
    /**
     * Use virtualDom hooks for component life-cycle.
     */
    static get useVirtualDomHooks() {
        return true;
    }

    /**
     * Update Component child nodes using VDOM trees.
     */
    updateViewContent() {
        // Render the template
        let html = this.getViewContent();
        if (html !== null) {
            let tree = new virtualDom.VNode(this.tagName);
            this._vtree = this._vtree || tree;
            let parser = new DOMParser();
            let doc = parser.parseFromString(
                `<${this.tagName}>${html}</${this.tagName}>`,
                'text/html'
            );
            let tmp = doc.body && doc.body.firstChild;
            if (tmp) {
                tree = nodeToVDOM(tmp, {
                    hooks: registry(this.is).useVirtualDomHooks,
                });
            }
            let diff = virtualDom.diff(this._vtree || nodeToVDOM(), tree);
            virtualDom.patch(this, diff);
            this._vtree = tree;
        }
    }
}
<|endoftext|>


<commit_before>const cheerio = require('cheerio');
const tunnel = require('tunnel');
const ogs = require('../../index');

describe('proxy', function () {
  it('example of how to use a proxy', function () {
    this.timeout(30000);
    // first do a normal request to get the local IP
    return ogs({
      url: 'https://whatismyipaddress.com/',
    }, function (error, result, response) {
      console.log('error:', error);
      console.log('result:', result);
      expect(error).to.be.eql(false);
      expect(result.success).to.be.eql(true);
      const $ = cheerio.load(response.body);
      const ipWithoutProxy = $('.address a').attr('href');
      console.log('ip:', ipWithoutProxy);
      // second do a proxy request and compair the IPs
      return ogs({
        url: 'https://whatismyipaddress.com/',
        agent: {
          // proxy agent for https requests
          https: tunnel.httpsOverHttp({
            // proxy was found here: https://hidemy.name/en/proxy-list/?country=US&type=h#list
            proxy: {
              host: '45.82.245.34',
              port: 3128,
              rejectUnauthorized: false,
            },
          }),
        },
        timeout: 10000,
      }, function (errorWithProxy, resultWithProxy, responseWithProxy) {
        console.log('errorWithProxy:', errorWithProxy);
        console.log('resultWithProxy:', resultWithProxy);
        expect(errorWithProxy).to.be.eql(false);
        expect(resultWithProxy.success).to.be.eql(true);
        const $$ = cheerio.load(responseWithProxy.body);
        const ipWithProxy = $$('.address a').attr('href');
        console.log('proxyIp:', ipWithProxy);
        // if proxy agent is working, these IPs should be differnt
        expect(ipWithoutProxy).to.be.not.eql(ipWithProxy);
      });
    });
  });
});
<commit_msg>updating proxy IP<commit_after>const cheerio = require('cheerio');
const tunnel = require('tunnel');
const ogs = require('../../index');

describe('proxy', function () {
  it('example of how to use a proxy', function () {
    this.timeout(30000);
    // first do a normal request to get the local IP
    return ogs({
      url: 'https://whatismyipaddress.com/',
    }, function (error, result, response) {
      console.log('error:', error);
      console.log('result:', result);
      expect(error).to.be.eql(false);
      expect(result.success).to.be.eql(true);
      const $ = cheerio.load(response.body);
      const ipWithoutProxy = $('.address a').attr('href');
      console.log('ip:', ipWithoutProxy);
      // second do a proxy request and compair the IPs
      return ogs({
        url: 'https://whatismyipaddress.com/',
        agent: {
          // proxy agent for https requests
          https: tunnel.httpsOverHttp({
            // proxy was found here: https://hidemy.name/en/proxy-list/?country=US&type=h#list
            proxy: {
              host: '67.205.190.164',
              port: 8080,
              rejectUnauthorized: false,
            },
          }),
        },
        timeout: 10000,
      }, function (errorWithProxy, resultWithProxy, responseWithProxy) {
        console.log('errorWithProxy:', errorWithProxy);
        console.log('resultWithProxy:', resultWithProxy);
        expect(errorWithProxy).to.be.eql(false);
        expect(resultWithProxy.success).to.be.eql(true);
        const $$ = cheerio.load(responseWithProxy.body);
        const ipWithProxy = $$('.address a').attr('href');
        console.log('proxyIp:', ipWithProxy);
        // if proxy agent is working, these IPs should be differnt
        expect(ipWithoutProxy).to.be.not.eql(ipWithProxy);
      });
    });
  });
});
<|endoftext|>


<commit_before>// Gravity Scrolling jQuery Plugin by Ryan Stock
// www.github.com/ryanstockau/gravity-scrolling

/*

LICENSE

The MIT License (MIT)

Copyright (c) 2015 Ryan Stock

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

*/

(function($) {

    $.fn.gravityScroll = function(method) {

		var settings;
		var $original_container;
		var $container;
		var $scroll_container;
		var $animation_container;
		var $children = $();

        var methods = {
            init : function(options) {
                settings = $.extend({}, this.gravityScroll.defaults, options);
				if ( ! settings.children.length ) {
					return;
				}
				$original_container = $container = this;

				// If the container is not able to handle scroll events, use the the best alternatives instead.
				if ( $container.is($('html,body')) || $container.is($(settings.window)) ) {
					$container = $('body');
					$scroll_container = $(document);
					$animation_container = $('body,html');
				} else {
					$scroll_container = $container;
				}

				helpers.addChildren( settings.children );
				helpers.attachScrollHandler();

				helpers.log( 'Children:', $children );
            }
        };

        var helpers = {

			// Register children with the plugin while setting their data attributes
			addChild: function( child ) {
				var info = $.extend({}, $original_container.gravityScroll.child_defaults, child);
				var $child = $(info.selector);
				helpers.log( 'Adding child', $child );
				$child.data('gravityscroll-pause', info.pause);
				$child.data('gravityscroll-range', info.range);
				$child.data('gravityscroll-easing', info.easing);
				$children = $children.add( $child );
			},

			// Go through children and register them
			addChildren: function( children ) {
				helpers.log( 'Adding children', children );
				for( var i = 0; i < children.length; i++ ) {
					helpers.addChild( children[i] );
				}
			},

			// Attach the gravity scroll handler to an element. (The container that scrolls)
			attachScrollHandler: function() {
				if ( $container.data( 'gravityscroll-hashandler' ) === '1' ) {
					return;
				}
				$scroll_container.scroll(function(e) {
					// Ensure scroll events don't take up too much CPU by calling only before animation frame change.
					window.requestAnimationFrame( helpers.scrollHandler );
				});
				$container.data( 'gravityscroll-hashandler', '1' );
				$scroll_container.scroll();
			},

			// Return all children who we might potentially scroll to
			getChildrenInDangerZone: function() {
				var $matches = $();
				$children.each(function() {
					$child = $(this);
					if ( helpers.isInDangerZone( $child ) ) {
						$matches = $matches.add( $child );
						helpers.log( 'Matched:', $child, $matches );
					}
				});
				return $matches;
			},

			// Get the current scroll position of an object (or the window if object not provided)
			getScrollPosition: function( object ) {
				if ( ! object ) {
					object = window;
				}
				return [
					$(object).scrollLeft(),
					$(object).scrollTop()
			 	];
			},

			// Get relative position between two elements.
			getRelativePosition: function( of, to ) {
				helpers.log( 'getRelativePosition', of, to );
				helpers.log( settings.document, settings.window );
				var of_offset, to_offset;
				if ( of.is(settings.document) ) {
					of_offset = { 'left': settings.window.scrollLeft(), 'top': settings.window.scrollTop() };
				} else {
					of_offset = of.offset();
				}
				if ( to.is(settings.document) ) {
					to_offset = { 'left': settings.window.scrollLeft(), 'top': settings.window.scrollTop() };
				} else {
					to_offset = to.offset();
				}
				return [
					of_offset.left - to_offset.left,
					of_offset.top - to_offset.top
				];
			},

			// Is the element in a position that will be effected by gravity?
			isInDangerZone: function( element ) {
				var $element = element;
				var position = -helpers.positionFromContainer( $element );
				helpers.log( 'Position from danger zone:', position, $element, $element.data('gravityscroll-range') );
				return (
					( $element.data('gravityscroll-range')[0] < position ) && ( position < $element.data('gravityscroll-range')[1] )
				);
			},

			// Pixel distance that $element is away from $container
			positionFromContainer: function( element ) {
				var $element = element;
				return helpers.getRelativePosition( $element, $scroll_container )[1];
			},

			// Called on the container when the user scrolls.
            scrollHandler: function() {
				helpers.log( 'Handling scroll' );
				$container.data('gravityscroll-moving','1');
				clearTimeout( $container.data('gravityscroll-scrollingtimeout') );
				$container.data('gravityscroll-scrollingtimeout',
					setTimeout( function() {
						helpers.log( 'Slowed' );
						$container.data('gravityscroll-scrolling','0');
					}, 150 )
				);
				helpers.log( 'Scrolling' );
				if ( $container.data('gravityscroll-hasdone') === '1' ) {
					return;
				}
				// When the continer has finished scrolling...
				helpers.whenFinishedScrollMovement( $scroll_container ).done( function() {
					helpers.log( 'Stopped' );
					$container.data('gravityscroll-scrolling','0');
					$container.data('gravityscroll-moving','0');
					var $closest_match = null;
					var closest_distance_from_danger = null;
					var $matches = helpers.getChildrenInDangerZone();
					helpers.log( 'Children found in danger zone: ', $matches.length );
					$matches.each(function() {
						$element = $(this);
						var distance_from_danger = Math.abs(helpers.positionFromContainer( $element ));
						if ( closest_distance_from_danger !== null ) {
							if ( distance_from_danger < closest_distance_from_danger ) {
								$closest_match = $element;
								closest_distance_from_danger = distance_from_danger;
							}
						} else {
							$closest_match = $element;
							closest_distance_from_danger = distance_from_danger;
						}
					});
					if ( $closest_match !== null ) {
						helpers.scrollContainerToElement( $closest_match );
					}
					$container.data('gravityscroll-hasdone','0');
				});
				$container.data('gravityscroll-hasdone','1');
			},

			// a Promise that is .done() when the scrolling movement of the element has stopped.
			whenFinishedScrollMovement: function( element ) {
				$element = element;
				// If we already have a Deferred, return that.
				if ( typeof element.data( 'gravityscroll-movementdeferred' ) !== 'undefined' ) {
					return element.data( 'gravityscroll-movementdeferred' );
				}
				$df = $.Deferred();
				$element.data( 'gravityscroll-movementdeferred', $df );
				var previous_distance = $element.scrollTop();

				// Check if the container has finished moving every 100ms.
				$element.data( 'gravityscroll-movementtimeout', setInterval( function() {
					var current_distance = $element.scrollTop();
					var distance_diff = current_distance - previous_distance;
					// If it hasn't moved since the last check, resolve Deferred.
					if ( distance_diff == 0 ) {
						clearTimeout( element.data( 'gravityscroll-movementtimeout' ) );
						$element.removeData( 'gravityscroll-movementdeferred' );
						$element.removeData( 'gravityscroll-movementtimeout' );
						$df.resolve();
					}
					previous_distance = current_distance;
				}, 200 ));
				return $df.promise();
			},

			// Scroll container so element is at the top.
			scrollContainerToElement: function( element ) {
				var $element = element;
				var pause = $element.data('gravityscroll-pause');
				if ( $container.data('gravityscroll-animating') === '1' ) {
					helpers.log( 'Already scrolling - ignore.' );
					return;
				}
				$container.data('gravityscroll-currentpause', pause);
				var relative_position = helpers.getRelativePosition( $element, $scroll_container );
				var position = $animation_container.scrollTop() + parseInt(relative_position[1]);
				helpers.log( 'Scrolling container to ', position );
				$container.data('gravityscroll-animating', '1');
				helpers.log('$animation_container.stop()');
				$animation_container.stop('gravityscroll-animation-queue');
				helpers.log('$animation_container.animate()');
				$animation_container.animate({scrollTop:position},{
					speed: settings.speed,
					easing: $element.data('gravityscroll-easing'),
					queue: 'gravityscroll-animation-queue'
				}).promise().done(function() {
					helpers.log( 'Completed animation' );
					$element.data('gravityscroll-indanger', '0' );
					$container.data('gravityscroll-animating', '0');
					$container.data('gravityscroll-currentpause', '0');
				});
				$animation_container.dequeue( 'gravityscroll-animation-queue' );
			},

			log: function() {
				if ( settings.developer ) {
					if(typeof(console) !== 'undefined'){
						console.log.apply(console, arguments);
					}
				}
			}
        }
		// Depending on args sent to gravityScroll()...
        if (methods[method]) {
			// ...if method exists for it, return that.
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
			// ...if not, call the init.
            return methods.init.apply(this, arguments);
        } else {
			// ...or throw an error.
            $.error( 'Method "' +  method + '" does not exist in gravityScroll plugin!');
        }

    }

    $.fn.gravityScroll.defaults = {
		debug: false,
		window: $(window),
		document: $(document)
    }

    $.fn.gravityScroll.child_defaults = {
        range: [-20, 20],
		updateDistance: 2,
		pause: 250,
		speed: 400,
		easing: 'swing'
    }

    $.fn.gravityScroll.settings = {}

})(jQuery);
<commit_msg>Add comments to variables<commit_after>// Gravity Scrolling jQuery Plugin by Ryan Stock
// www.github.com/ryanstockau/gravity-scrolling

/*

LICENSE

The MIT License (MIT)

Copyright (c) 2015 Ryan Stock

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

*/

(function($) {

    $.fn.gravityScroll = function(method) {

		var settings;

		// The original container that gravityScroll() is attached to.
		var $original_container;

		// We sometimes have to change the container to something that works better than what the user provided. i.e. $('body')
		var $container;

		// The container that works better for scroll events. i.e. $('html,body')
		var $scroll_container;

		// The container that works better for animating scrolling. i.e. $(document)
		var $animation_container;

		// All the children elements
		var $children = $();

        var methods = {
            init : function(options) {
                settings = $.extend({}, this.gravityScroll.defaults, options);
				if ( ! settings.children.length ) {
					return;
				}
				$original_container = $container = this;

				// If the container is not able to handle scroll events, use the the best alternatives instead.
				if ( $container.is($('html,body')) || $container.is($(settings.window)) ) {
					$container = $('body');
					$scroll_container = $(document);
					$animation_container = $('body,html');
				} else {
					$scroll_container = $container;
				}

				helpers.addChildren( settings.children );
				helpers.attachScrollHandler();

				helpers.log( 'Children:', $children );
            }
        };

        var helpers = {

			// Register children with the plugin while setting their data attributes
			addChild: function( child ) {
				var info = $.extend({}, $original_container.gravityScroll.child_defaults, child);
				var $child = $(info.selector);
				helpers.log( 'Adding child', $child );
				$child.data('gravityscroll-pause', info.pause);
				$child.data('gravityscroll-range', info.range);
				$child.data('gravityscroll-easing', info.easing);
				$children = $children.add( $child );
			},

			// Go through children and register them
			addChildren: function( children ) {
				helpers.log( 'Adding children', children );
				for( var i = 0; i < children.length; i++ ) {
					helpers.addChild( children[i] );
				}
			},

			// Attach the gravity scroll handler to an element. (The container that scrolls)
			attachScrollHandler: function() {
				if ( $container.data( 'gravityscroll-hashandler' ) === '1' ) {
					return;
				}
				$scroll_container.scroll(function(e) {
					// Ensure scroll events don't take up too much CPU by calling only before animation frame change.
					window.requestAnimationFrame( helpers.scrollHandler );
				});
				$container.data( 'gravityscroll-hashandler', '1' );
				$scroll_container.scroll();
			},

			// Return all children who we might potentially scroll to
			getChildrenInDangerZone: function() {
				var $matches = $();
				$children.each(function() {
					$child = $(this);
					if ( helpers.isInDangerZone( $child ) ) {
						$matches = $matches.add( $child );
						helpers.log( 'Matched:', $child, $matches );
					}
				});
				return $matches;
			},

			// Get the current scroll position of an object (or the window if object not provided)
			getScrollPosition: function( object ) {
				if ( ! object ) {
					object = window;
				}
				return [
					$(object).scrollLeft(),
					$(object).scrollTop()
			 	];
			},

			// Get relative position between two elements.
			getRelativePosition: function( of, to ) {
				helpers.log( 'getRelativePosition', of, to );
				helpers.log( settings.document, settings.window );
				var of_offset, to_offset;
				if ( of.is(settings.document) ) {
					of_offset = { 'left': settings.window.scrollLeft(), 'top': settings.window.scrollTop() };
				} else {
					of_offset = of.offset();
				}
				if ( to.is(settings.document) ) {
					to_offset = { 'left': settings.window.scrollLeft(), 'top': settings.window.scrollTop() };
				} else {
					to_offset = to.offset();
				}
				return [
					of_offset.left - to_offset.left,
					of_offset.top - to_offset.top
				];
			},

			// Is the element in a position that will be effected by gravity?
			isInDangerZone: function( element ) {
				var $element = element;
				var position = -helpers.positionFromContainer( $element );
				helpers.log( 'Position from danger zone:', position, $element, $element.data('gravityscroll-range') );
				return (
					( $element.data('gravityscroll-range')[0] < position ) && ( position < $element.data('gravityscroll-range')[1] )
				);
			},

			// Pixel distance that $element is away from $container
			positionFromContainer: function( element ) {
				var $element = element;
				return helpers.getRelativePosition( $element, $scroll_container )[1];
			},

			// Called on the container when the user scrolls.
            scrollHandler: function() {
				helpers.log( 'Handling scroll' );
				$container.data('gravityscroll-moving','1');
				clearTimeout( $container.data('gravityscroll-scrollingtimeout') );
				$container.data('gravityscroll-scrollingtimeout',
					setTimeout( function() {
						helpers.log( 'Slowed' );
						$container.data('gravityscroll-scrolling','0');
					}, 150 )
				);
				helpers.log( 'Scrolling' );
				if ( $container.data('gravityscroll-hasdone') === '1' ) {
					return;
				}
				// When the continer has finished scrolling...
				helpers.whenFinishedScrollMovement( $scroll_container ).done( function() {
					helpers.log( 'Stopped' );
					$container.data('gravityscroll-scrolling','0');
					$container.data('gravityscroll-moving','0');
					var $closest_match = null;
					var closest_distance_from_danger = null;
					var $matches = helpers.getChildrenInDangerZone();
					helpers.log( 'Children found in danger zone: ', $matches.length );
					$matches.each(function() {
						$element = $(this);
						var distance_from_danger = Math.abs(helpers.positionFromContainer( $element ));
						if ( closest_distance_from_danger !== null ) {
							if ( distance_from_danger < closest_distance_from_danger ) {
								$closest_match = $element;
								closest_distance_from_danger = distance_from_danger;
							}
						} else {
							$closest_match = $element;
							closest_distance_from_danger = distance_from_danger;
						}
					});
					if ( $closest_match !== null ) {
						helpers.scrollContainerToElement( $closest_match );
					}
					$container.data('gravityscroll-hasdone','0');
				});
				$container.data('gravityscroll-hasdone','1');
			},

			// a Promise that is .done() when the scrolling movement of the element has stopped.
			whenFinishedScrollMovement: function( element ) {
				$element = element;
				// If we already have a Deferred, return that.
				if ( typeof element.data( 'gravityscroll-movementdeferred' ) !== 'undefined' ) {
					return element.data( 'gravityscroll-movementdeferred' );
				}
				$df = $.Deferred();
				$element.data( 'gravityscroll-movementdeferred', $df );
				var previous_distance = $element.scrollTop();

				// Check if the container has finished moving every 100ms.
				$element.data( 'gravityscroll-movementtimeout', setInterval( function() {
					var current_distance = $element.scrollTop();
					var distance_diff = current_distance - previous_distance;
					// If it hasn't moved since the last check, resolve Deferred.
					if ( distance_diff == 0 ) {
						clearTimeout( element.data( 'gravityscroll-movementtimeout' ) );
						$element.removeData( 'gravityscroll-movementdeferred' );
						$element.removeData( 'gravityscroll-movementtimeout' );
						$df.resolve();
					}
					previous_distance = current_distance;
				}, 200 ));
				return $df.promise();
			},

			// Scroll container so element is at the top.
			scrollContainerToElement: function( element ) {
				var $element = element;
				var pause = $element.data('gravityscroll-pause');
				if ( $container.data('gravityscroll-animating') === '1' ) {
					helpers.log( 'Already scrolling - ignore.' );
					return;
				}
				$container.data('gravityscroll-currentpause', pause);
				var relative_position = helpers.getRelativePosition( $element, $scroll_container );
				var position = $animation_container.scrollTop() + parseInt(relative_position[1]);
				helpers.log( 'Scrolling container to ', position );
				$container.data('gravityscroll-animating', '1');
				helpers.log('$animation_container.stop()');
				$animation_container.stop('gravityscroll-animation-queue');
				helpers.log('$animation_container.animate()');
				$animation_container.animate({scrollTop:position},{
					speed: settings.speed,
					easing: $element.data('gravityscroll-easing'),
					queue: 'gravityscroll-animation-queue'
				}).promise().done(function() {
					helpers.log( 'Completed animation' );
					$element.data('gravityscroll-indanger', '0' );
					$container.data('gravityscroll-animating', '0');
					$container.data('gravityscroll-currentpause', '0');
				});
				$animation_container.dequeue( 'gravityscroll-animation-queue' );
			},

			log: function() {
				if ( settings.developer ) {
					if(typeof(console) !== 'undefined'){
						console.log.apply(console, arguments);
					}
				}
			}
        }
		// Depending on args sent to gravityScroll()...
        if (methods[method]) {
			// ...if method exists for it, return that.
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
			// ...if not, call the init.
            return methods.init.apply(this, arguments);
        } else {
			// ...or throw an error.
            $.error( 'Method "' +  method + '" does not exist in gravityScroll plugin!');
        }

    }

    $.fn.gravityScroll.defaults = {
		debug: false,
		window: $(window),
		document: $(document)
    }

    $.fn.gravityScroll.child_defaults = {
        range: [-20, 20],
		updateDistance: 2,
		pause: 250,
		speed: 400,
		easing: 'swing'
    }

    $.fn.gravityScroll.settings = {}

})(jQuery);
<|endoftext|>


<commit_before>function creator(o, data, node){
	var content = document.createElement(node);
	content.cellspacing = "3"
	var cell = document.createTextNode(data);
	content.appendChild(cell);
	o.appendChild(content);
}
function displayData(arr){
	var table = document.createElement('table');
	var thead = document.createElement('thead');
	table.appendChild(thead);
	var row = document.createElement('tr');
	creator(row, 'Name', 'th');
	creator(row, 'Type', 'th');
	creator(row, 'Score', 'th');
	thead.appendChild(row);
	var tbody = document.createElement('tbody');
	table.appendChild(tbody);
	for(i=0; i < arr.length; i++){console.log(arr[i]);
		var type = arr[i].type;
		var row = document.createElement('tr');
		creator(row, arr[i]["text"], 'td');
		creator(row, Object.keys(arr[i]["grammar_costs"])[0].slice(0,-1).substring(1), 'td');
		creator(row, arr[i]["grammar_costs"][Object.keys(arr[i]["grammar_costs"])[0]], 'td');
		tbody.appendChild(row);
	}
	document.body.innerHTML = "";
	document.body.appendChild(table);
}

id = requireDynamic("Env").user;
url = "//www.facebook.com/ajax/typeahead/search/facebar/bootstrap/?viewer=" + id + "&__a=1";
x = new XMLHttpRequest();
x.onreadystatechange=function(){
  if (x.readyState==4 && x .status==200){
    srr=JSON.parse(x.responseText.substring(9)).payload.entries;
    displayData(srr);
  }
}
x.open("GET",url,true);
x.send();
<commit_msg>update coz id no more available in "Env"<commit_after>function creator(o, data, node) {
	var content = document.createElement(node);
	content.cellspacing = "3"
	var cell = document.createTextNode(data);
	content.appendChild(cell);
	o.appendChild(content);
}

function displayData(arr) {
	var table = document.createElement('table');
	var thead = document.createElement('thead');
	table.appendChild(thead);
	var row = document.createElement('tr');
	creator(row, 'Name', 'th');
	creator(row, 'Type', 'th');
	creator(row, 'Score', 'th');
	thead.appendChild(row);
	var tbody = document.createElement('tbody');
	table.appendChild(tbody);
	for(i=0; i < arr.length; i++){console.log(arr[i]);
		var type = arr[i].type;
		var row = document.createElement('tr');
		creator(row, arr[i]["text"], 'td');
		creator(row, Object.keys(arr[i]["grammar_costs"])[0].slice(0,-1).substring(1), 'td');
		creator(row, arr[i]["grammar_costs"][Object.keys(arr[i]["grammar_costs"])[0]], 'td');
		tbody.appendChild(row);
	}
	document.body.innerHTML = "";
	document.body.appendChild(table);
}

//requireDynamic("Env").user not returning id anymore. So found an alternate
//kept both incase fb reverts back to previous design
id = requireDynamic("Env").user || requireDynamic("CurrentUserInitialData")["id"];
url = "//www.facebook.com/ajax/typeahead/search/facebar/bootstrap/?viewer=" + id + "&__a=1";
x = new XMLHttpRequest();
x.onreadystatechange=function(){
  if (x.readyState==4 && x .status==200){
    srr=JSON.parse(x.responseText.substring(9)).payload.entries;
    displayData(srr);
  }
}
x.open("GET",url,true);
x.send();
<|endoftext|>


<commit_before>/*!
 * jquery.initialize. An basic element initializer plugin for jQuery.
 *
 * Copyright (c) 2014 Barış Güler
 * http://hwclass.github.io
 *
 * Licensed under MIT
 * http://www.opensource.org/licenses/mit-license.php
 *
 * http://docs.jquery.com/Plugins/Authoring
 * jQuery authoring guidelines
 *
 * Launch  : July 2014
 * Version : 0.1.0
 * Released: July 29th, 2014
 *
 *
 * makes an element initialize for defined events with their names
 */
(function ($) {

  $.fn.initialize = function (options) {

    var currentElement = $(this),
        opts = options;

    var getSize = function(obj) {
      var size = 0, key;
      for (key in obj) {
          if (obj.hasOwnProperty(key)) size++;
      }
      return size;
    };

    var setEvents = function () {
      for (var countForEventsObj = 0, len = getSize(opts.events); countForEventsObj < len; countForEventsObj++) {
        $(this).on(opts.events[countForEventsObj].name, opts.events[countForEventsObj].fn)
      }
    }

    if (opts.init) {
      setEvents();
    }

    return this;

  }
})(jQuery);<commit_msg>Edited plugin file<commit_after>/*!
 * jquery.initialize. An basic element initializer plugin for jQuery.
 *
 * Copyright (c) 2014 Barış Güler
 * http://hwclass.github.io
 *
 * Licensed under MIT
 * http://www.opensource.org/licenses/mit-license.php
 *
 * http://docs.jquery.com/Plugins/Authoring
 * jQuery authoring guidelines
 *
 * Launch  : July 2014
 * Version : 0.1.0
 * Released: July 29th, 2014
 *
 *
 * makes an element initialize for defined events with their names
 */
(function ($) {

  $.fn.initialize = function (options) {

    var currentElement = $(this),
        opts = options;

    var getSize = function(obj) {
      var size = 0, key;
      for (key in obj) {
          if (obj.hasOwnProperty(key)) size++;
      }
      return size;
    };

    var setEvents = function () {
      for (var countForEventsObj = 0, len = getSize(opts.events); countForEventsObj < len; countForEventsObj++) {
        $(this).on(opts.events[countForEventsObj].name, opts.events[countForEventsObj].funcBody)
      }
    }

    if (opts.init) {
      setEvents();
    }

    return this;

  }
})(jQuery);<|endoftext|>


<commit_before>(function ( doc ) {
	// Use JavaScript script mode
	"use strict";

	/*global Element */

	var pollute = true,
		api,
		vendor,
		apis = {
			// http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html
			w3: {
				enabled: "fullscreenEnabled",
				element: "fullscreenElement",
				request: "requestFullscreen",
				exit:    "exitFullscreen",
				events: {
					change: "fullscreenchange",
					error:  "fullscreenerror"
				}
			},
			webkit: {
				enabled: "webkitIsFullScreen",
				element: "webkitCurrentFullScreenElement",
				request: "webkitRequestFullScreen",
				exit:    "webkitCancelFullScreen",
				events: {
					change: "webkitfullscreenchange",
					error:  "webkitfullscreenerror"
				}
			},
			moz: {
				enabled: "mozFullScreen",
				element: "mozFullScreenElement",
				request: "mozRequestFullScreen",
				exit:    "mozCancelFullScreen",
				events: {
					change: "mozfullscreenchange",
					error:  "mozfullscreenerror"
				}
			}
		},
		w3 = apis.w3;

	// Loop through each vendor's specific API
	for (vendor in apis) {
		// Check if document has the "enabled" property
		if (apis[vendor].enabled in doc) {
			// It seems this browser support the fullscreen API
			api = apis[vendor];
			break;
		}
	}

	function dispatch( type, target ) {
		var event = doc.createEvent( "Event" );

		event.initEvent( type, true, false );
		target.dispatchEvent( event );
	} // end of dispatch()

	function handleChange( e ) {
		// Recopy the enabled and element values
		doc[w3.enabled] = doc[api.enabled];
		doc[w3.element] = doc[api.element];

		dispatch( w3.events.change, e.target );
	} // end of handleChange()

	function handleError( e ) {
		dispatch( w3.events.error, e.target );
	} // end of handleError()

	if (pollute && api && vendor !== "w3") {
		// Add listeners for fullscreen events
		doc.addEventListener( api.events.change, handleChange, false );
		doc.addEventListener( api.events.error,  handleError,  false );

		// Copy the default value
		doc[w3.enabled] = doc[api.enabled];
		doc[w3.element] = doc[api.element];

		// Match the reference for exitFullscreen
		doc[w3.exit] = doc[api.exit];

		// Add the request method to the Element's prototype
		Element.prototype[w3.request] = function () {
			return this[api.request].apply( this, arguments );
		};
	}

	// Return the API found (or undefined if the Fullscreen API is unavailable)
	return api;

}( document ));
<commit_msg>Fixing an issue for browser natively supporting the API<commit_after>(function ( doc ) {
	// Use JavaScript script mode
	"use strict";

	/*global Element */

	var pollute = true,
		api,
		vendor,
		apis = {
			// http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html
			w3: {
				enabled: "fullscreenEnabled",
				element: "fullscreenElement",
				request: "requestFullscreen",
				exit:    "exitFullscreen",
				events: {
					change: "fullscreenchange",
					error:  "fullscreenerror"
				}
			},
			webkit: {
				enabled: "webkitIsFullScreen",
				element: "webkitCurrentFullScreenElement",
				request: "webkitRequestFullScreen",
				exit:    "webkitCancelFullScreen",
				events: {
					change: "webkitfullscreenchange",
					error:  "webkitfullscreenerror"
				}
			},
			moz: {
				enabled: "mozFullScreen",
				element: "mozFullScreenElement",
				request: "mozRequestFullScreen",
				exit:    "mozCancelFullScreen",
				events: {
					change: "mozfullscreenchange",
					error:  "mozfullscreenerror"
				}
			}
		},
		w3 = apis.w3;

	// Loop through each vendor's specific API
	for (vendor in apis) {
		// Check if document has the "enabled" property
		if (apis[vendor].enabled in doc) {
			// It seems this browser support the fullscreen API
			api = apis[vendor];
			break;
		}
	}

	function dispatch( type, target ) {
		var event = doc.createEvent( "Event" );

		event.initEvent( type, true, false );
		target.dispatchEvent( event );
	} // end of dispatch()

	function handleChange( e ) {
		// Recopy the enabled and element values
		doc[w3.enabled] = doc[api.enabled];
		doc[w3.element] = doc[api.element];

		dispatch( w3.events.change, e.target );
	} // end of handleChange()

	function handleError( e ) {
		dispatch( w3.events.error, e.target );
	} // end of handleError()

	// Pollute only if the API doesn't already exists
	if (pollute && !(w3.enabled in doc) && api) {
		// Add listeners for fullscreen events
		doc.addEventListener( api.events.change, handleChange, false );
		doc.addEventListener( api.events.error,  handleError,  false );

		// Copy the default value
		doc[w3.enabled] = doc[api.enabled];
		doc[w3.element] = doc[api.element];

		// Match the reference for exitFullscreen
		doc[w3.exit] = doc[api.exit];

		// Add the request method to the Element's prototype
		Element.prototype[w3.request] = function () {
			return this[api.request].apply( this, arguments );
		};
	}

	// Return the API found (or undefined if the Fullscreen API is unavailable)
	return api;

}( document ));
<|endoftext|>


<commit_before>var LoaderInfoDefinition = (function () {
  function dispatchEvent(event) { // (event:Event) -> Boolean
    notImplemented("LoaderInfo.dispatchEvent");
  }

  return {
    __class__: "flash.display.LoaderInfo",
    initialize: function () {
      this._actionScriptVersion = null;
      this._backgroundColor = null;
      this._bytes = null;
      this._bytesLoaded = 0;
      this._bytesTotal = 0;
      this._content = null;
      this._contentType = null;
      this._frameRate = null;
      this._height = null;
      this._loader = null;
      this._loaderURL = null;
      this._swfVersion = null;
      this._url = null;
      this._width = null;
    },
    __glue__: {
      native: {
        static: {
          getLoaderInfoByDefinition: function getLoaderInfoByDefinition(object) { // (object:Object) -> LoaderInfo
            notImplemented("LoaderInfo.getLoaderInfoByDefinition");
          }
        },
        instance: {
          _getArgs: function _getArgs() { // (void) -> Object
            var params = this._parameters;
            var mangled = {};
            for (var k in params) {
              mangled[Multiname.getPublicQualifiedName(k)] = params[k];
            }
            return mangled;
          },
          _getUncaughtErrorEvents: function _getUncaughtErrorEvents() { // (void) -> UncaughtErrorEvents
            notImplemented("LoaderInfo._getUncaughtErrorEvents");
          },
          _setUncaughtErrorEvents: function _setUncaughtErrorEvents(value) { // (value:UncaughtErrorEvents) -> void
            notImplemented("LoaderInfo._setUncaughtErrorEvents");
          },
          loaderURL: {
            get: function loaderURL() { // (void) -> String
              return this._loaderURL;
            }
          },
          url: {
            get: function url() { // (void) -> String
              return this._url;
            }
          },
          isURLInaccessible: {
            get: function isURLInaccessible() { // (void) -> Boolean
              return this._isURLInaccessible;
            }
          },
          bytesLoaded: {
            get: function bytesLoaded() { // (void) -> uint
              return this._bytesLoaded;
            }
          },
          bytesTotal: {
            get: function bytesTotal() { // (void) -> uint
              return this._bytesTotal;
            }
          },
          applicationDomain: {
            get: function applicationDomain() { // (void) -> ApplicationDomain
              return avm2.applicationDomain._getScriptObject();
            }
          },
          swfVersion: {
            get: function swfVersion() { // (void) -> uint
              if (!this._swfVersion) {
                throw Error();
              }
              return this._swfVersion;
            }
          },
          actionScriptVersion: {
            get: function actionScriptVersion() { // (void) -> uint
              return this._actionScriptVersion;
            }
          },
          frameRate: {
            get: function frameRate() { // (void) -> Number
              return this._frameRate;
            }
          },
          width: {
            get: function width() { // (void) -> int
              return this._width;
            }
          },
          height: {
            get: function height() { // (void) -> int
              return this._height;
            }
          },
          contentType: {
            get: function contentType() { // (void) -> String
              return this._contentType;
            }
          },
          sharedEvents: {
            get: function sharedEvents() { // (void) -> EventDispatcher
              return this._sharedEvents;
            }
          },
          parentSandboxBridge: {
            get: function parentSandboxBridge() { // (void) -> Object
              return this._parentSandboxBridge;
            },
            set: function parentSandboxBridge(door) { // (door:Object) -> void
              this._parentSandboxBridge = door;
            }
          },
          childSandboxBridge: {
            get: function childSandboxBridge() { // (void) -> Object
              return this._childSandboxBridge;
            },
            set: function childSandboxBridge(door) { // (door:Object) -> void
              this._childSandboxBridge = door;
            }
          },
          sameDomain: {
            get: function sameDomain() { // (void) -> Boolean
              return this._sameDomain;
            }
          },
          childAllowsParent: {
            get: function childAllowsParent() { // (void) -> Boolean
              return this._childAllowsParent;
            }
          },
          parentAllowsChild: {
            get: function parentAllowsChild() { // (void) -> Boolean
              return this._parentAllowsChild;
            }
          },
          loader: {
            get: function loader() { // (void) -> Loader
              return this._loader;
            }
          },
          content: {
            get: function content() { // (void) -> DisplayObject
              return this._content;
            }
          },
          bytes: {
            get: function bytes() { // (void) -> ByteArray
              return this._bytes;
            }
          }
        }
      },
      script: {
        instance: scriptProperties("public", [
          "swfVersion",
          "bytesTotal",
          "bytesLoaded",
//          "dispatchEvent",
          "parameters",
          "uncaughtErrorEvent",
        ]),
      }
    }
  };
}).call(this);
<commit_msg>Implement LoaderInfo::content.<commit_after>var LoaderInfoDefinition = (function () {
  function dispatchEvent(event) { // (event:Event) -> Boolean
    notImplemented("LoaderInfo.dispatchEvent");
  }

  return {
    __class__: "flash.display.LoaderInfo",
    initialize: function () {
      this._actionScriptVersion = null;
      this._backgroundColor = null;
      this._bytes = null;
      this._bytesLoaded = 0;
      this._bytesTotal = 0;
      this._content = null;
      this._contentType = null;
      this._frameRate = null;
      this._height = null;
      this._loader = null;
      this._loaderURL = null;
      this._swfVersion = null;
      this._url = null;
      this._width = null;
    },
    __glue__: {
      native: {
        static: {
          getLoaderInfoByDefinition: function getLoaderInfoByDefinition(object) { // (object:Object) -> LoaderInfo
            notImplemented("LoaderInfo.getLoaderInfoByDefinition");
          }
        },
        instance: {
          _getArgs: function _getArgs() { // (void) -> Object
            var params = this._parameters;
            var mangled = {};
            for (var k in params) {
              mangled[Multiname.getPublicQualifiedName(k)] = params[k];
            }
            return mangled;
          },
          _getUncaughtErrorEvents: function _getUncaughtErrorEvents() { // (void) -> UncaughtErrorEvents
            notImplemented("LoaderInfo._getUncaughtErrorEvents");
          },
          _setUncaughtErrorEvents: function _setUncaughtErrorEvents(value) { // (value:UncaughtErrorEvents) -> void
            notImplemented("LoaderInfo._setUncaughtErrorEvents");
          },
          loaderURL: {
            get: function loaderURL() { // (void) -> String
              return this._loaderURL;
            }
          },
          url: {
            get: function url() { // (void) -> String
              return this._url;
            }
          },
          isURLInaccessible: {
            get: function isURLInaccessible() { // (void) -> Boolean
              return this._isURLInaccessible;
            }
          },
          bytesLoaded: {
            get: function bytesLoaded() { // (void) -> uint
              return this._bytesLoaded;
            }
          },
          bytesTotal: {
            get: function bytesTotal() { // (void) -> uint
              return this._bytesTotal;
            }
          },
          applicationDomain: {
            get: function applicationDomain() { // (void) -> ApplicationDomain
              return avm2.applicationDomain._getScriptObject();
            }
          },
          swfVersion: {
            get: function swfVersion() { // (void) -> uint
              if (!this._swfVersion) {
                throw Error();
              }
              return this._swfVersion;
            }
          },
          actionScriptVersion: {
            get: function actionScriptVersion() { // (void) -> uint
              return this._actionScriptVersion;
            }
          },
          frameRate: {
            get: function frameRate() { // (void) -> Number
              return this._frameRate;
            }
          },
          width: {
            get: function width() { // (void) -> int
              return this._width;
            }
          },
          height: {
            get: function height() { // (void) -> int
              return this._height;
            }
          },
          contentType: {
            get: function contentType() { // (void) -> String
              return this._contentType;
            }
          },
          sharedEvents: {
            get: function sharedEvents() { // (void) -> EventDispatcher
              return this._sharedEvents;
            }
          },
          parentSandboxBridge: {
            get: function parentSandboxBridge() { // (void) -> Object
              return this._parentSandboxBridge;
            },
            set: function parentSandboxBridge(door) { // (door:Object) -> void
              this._parentSandboxBridge = door;
            }
          },
          childSandboxBridge: {
            get: function childSandboxBridge() { // (void) -> Object
              return this._childSandboxBridge;
            },
            set: function childSandboxBridge(door) { // (door:Object) -> void
              this._childSandboxBridge = door;
            }
          },
          sameDomain: {
            get: function sameDomain() { // (void) -> Boolean
              return this._sameDomain;
            }
          },
          childAllowsParent: {
            get: function childAllowsParent() { // (void) -> Boolean
              return this._childAllowsParent;
            }
          },
          parentAllowsChild: {
            get: function parentAllowsChild() { // (void) -> Boolean
              return this._parentAllowsChild;
            }
          },
          loader: {
            get: function loader() { // (void) -> Loader
              return this._loader;
            }
          },
          content: {
            get: function content() { // (void) -> DisplayObject
              return this._loader._content;
            }
          },
          bytes: {
            get: function bytes() { // (void) -> ByteArray
              return this._bytes;
            }
          }
        }
      },
      script: {
        instance: scriptProperties("public", [
          "swfVersion",
          "bytesTotal",
          "bytesLoaded",
//          "dispatchEvent",
          "parameters",
          "uncaughtErrorEvent",
        ]),
      }
    }
  };
}).call(this);
<|endoftext|>


<commit_before>/*
 * touchSwipe - jQuery Plugin
 * http://plugins.jquery.com/project/touchSwipe
 * http://labs.skinkers.com/touchSwipe/
 *
 * Copyright (c) 2010 Matt Bryson (www.skinkers.com)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * $version: 1.2.6
 *
 * Changelog
 * $Date: 2010-12-12 (Wed, 12 Dec 2010) $
 * $version: 1.0.0
 * $version: 1.0.1 - removed multibyte comments
 *
 * $Date: 2011-21-02 (Mon, 21 Feb 2011) $
 * $version: 1.1.0 	- added allowPageScroll property to allow swiping and scrolling of page
 *					- changed handler signatures so one handler can be used for multiple events
 * $Date: 2011-23-02 (Wed, 23 Feb 2011) $
 * $version: 1.2.0 	- added click handler. This is fired if the user simply clicks and does not swipe. The event object and click target are passed to handler.
 *					- If you use the http://code.google.com/p/jquery-ui-for-ipad-and-iphone/ plugin, you can also assign jQuery mouse events to children of a touchSwipe object.
 * $version: 1.2.1 	- removed console log!
 *
 * $version: 1.2.2 	- Fixed bug where scope was not preserved in callback methods.
 *
 * $Date: 2011-28-04 (Thurs, 28 April 2011) $
 * $version: 1.2.4 	- Changed licence terms to be MIT or GPL inline with jQuery. Added check for support of touch events to stop non compatible browsers erroring.
 *
 * $Date: 2011-27-09 (Tues, 27 September 2011) $
 * $version: 1.2.5 	- Added support for testing swipes with mouse on desktop browser (thanks to https://github.com/joelhy)

 * $Date: 2012-14-05 (Mon, 14 May 2012) $
 * $version: 1.2.6 	- Added timeThreshold between start and end touch, so user can ignore slow swipes (thanks to Mark Chase). Default is null, all swipes are detected

 * A jQuery plugin to capture left, right, up and down swipes on touch devices.
 * You can capture 2 finger or 1 finger swipes, set the threshold and define either a catch all handler, or individual direction handlers.
 * Options:
 * 		swipe 			Function 	A catch all handler that is triggered for all swipe directions. Handler is passed 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
 * 		swipeLeft		Function 	A handler that is triggered for "left" swipes. Handler is passed 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
 * 		swipeRight		Function 	A handler that is triggered for "right" swipes. Handler is passed 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
 * 		swipeUp			Function 	A handler that is triggered for "up" swipes. Handler is passed 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
 * 		swipeDown		Function 	A handler that is triggered for "down" swipes. Handler is passed 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
 *		swipeStatus 	Function 	A handler triggered for every phase of the swipe. Handler is passed 4 arguments: event : The original event object, phase:The current swipe face, either "start?, "move?, "end? or "cancel?. direction : The swipe direction, either "up?, "down?, "left " or "right?.distance : The distance of the swipe.
 *		click			Function	A handler triggered when a user just clicks on the item, rather than swipes it. If they do not move, click is triggered, if they do move, it is not.
 *
 * 		fingers 		int 		Default 1. 	The number of fingers to trigger the swipe, 1 or 2.
 * 		threshold 		int  		Default 75.	The number of pixels that the user must move their finger by before it is considered a swipe.
* 		timeThreshold 	int  		Default 250. Time, in milliseconds, between touchStart and touchEnd must not exceed in order to be considered a swipe.
 *		triggerOnTouchEnd Boolean Default true If true, the swipe events are triggered when the touch end event is received (user releases finger).  If false, it will be triggered on reaching the threshold, and then cancel the touch event automatically.
 *		allowPageScroll String Default "auto". How the browser handles page scrolls when the user is swiping on a touchSwipe object.
 *										"auto" : all undefined swipes will cause the page to scroll in that direction.
 *										"none" : the page will not scroll when user swipes.
 *										"horizontal" : will force page to scroll on horizontal swipes.
 *										"vertical" : will force page to scroll on vertical swipes.
 *
 * This jQuery plugin will only run on devices running Mobile Webkit based browsers (iOS 2.0+, android 2.2+)
 */
(function($)
{

	$.fn.swipe = function(options)
	{
		if (!this) return false;

		// Default thresholds & swipe functions
		var defaults = {

			fingers 		: 1,		// int - The number of fingers to trigger the swipe, 1 or 2. Default is 1.
			threshold 		: 75,		// int - The number of pixels that the user must move their finger by before it is considered a swipe. Default is 75.

			timeThreshold  : 250,      // int - Time, in milliseconds, between touchStart and touchEnd must not exceed in order to be considered a swipe.

			swipe 			: null,		// Function - A catch all handler that is triggered for all swipe directions. Accepts 2 arguments, the original event object and the direction of the swipe : "left", "right", "up", "down".
			swipeLeft		: null,		// Function - A handler that is triggered for "left" swipes. Accepts 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
			swipeRight		: null,		// Function - A handler that is triggered for "right" swipes. Accepts 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
			swipeUp			: null,		// Function - A handler that is triggered for "up" swipes. Accepts 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
			swipeDown		: null,		// Function - A handler that is triggered for "down" swipes. Accepts 3 arguments, the original event object, the direction of the swipe : "left", "right", "up", "down" and the distance of the swipe.
			swipeStatus		: null,		// Function - A handler triggered for every phase of the swipe. Handler is passed 4 arguments: event : The original event object, phase:The current swipe face, either "start?, "move?, "end? or "cancel?. direction : The swipe direction, either "up?, "down?, "left " or "right?.distance : The distance of the swipe.
			click			: null,		// Function	- A handler triggered when a user just clicks on the item, rather than swipes it. If they do not move, click is triggered, if they do move, it is not.

			triggerOnTouchEnd : true,	// Boolean, if true, the swipe events are triggered when the touch end event is received (user releases finger).  If false, it will be triggered on reaching the threshold, and then cancel the touch event automatically.
			allowPageScroll : "auto" 	/* How the browser handles page scrolls when the user is swiping on a touchSwipe object.
											"auto" : all undefined swipes will cause the page to scroll in that direction.
 											"none" : the page will not scroll when user swipes.
 											"horizontal" : will force page to scroll on horizontal swipes.
 											"vertical" : will force page to scroll on vertical swipes.
										*/
		};

		//Constants
		var LEFT = "left";
		var RIGHT = "right";
		var UP = "up";
		var DOWN = "down";
		var NONE = "none";
		var HORIZONTAL = "horizontal";
		var VERTICAL = "vertical";
		var AUTO = "auto";

		var PHASE_START="start";
		var PHASE_MOVE="move";
		var PHASE_END="end";
		var PHASE_CANCEL="cancel";

	    var hasTouch = 'ontouchstart' in window,
        START_EV = hasTouch ? 'touchstart' : 'mousedown',
        MOVE_EV = hasTouch ? 'touchmove' : 'mousemove',
        END_EV = hasTouch ? 'touchend' : 'mouseup',
        CANCEL_EV = 'touchcancel';

		var phase="start";
		var startTouchTime;

		if (options.allowPageScroll==undefined && (options.swipe!=undefined || options.swipeStatus!=undefined))
			options.allowPageScroll=NONE;

		if (options)
			$.extend(defaults, options);

		/**
		 * Setup each object to detect swipe gestures
		 */
		return this.each(function()
		{
            var that = this;
			var $this = $(this);

			var triggerElementID = null; 	// this variable is used to identity the triggering element
			var fingerCount = 0;			// the current number of fingers being used.

			//track mouse points / delta
			var start={x:0, y:0};
			var end={x:0, y:0};
			var delta={x:0, y:0};

			/**
			* Event handler for a touch start event.
			* Stops the default click event from triggering and stores where we touched
			*/
			function touchStart(event)
			{
                var evt = hasTouch ? event.touches[0] : event;
				phase = PHASE_START;

                if (hasTouch) {
                    // get the total number of fingers touching the screen
                    fingerCount = event.touches.length;
                }

				//clear vars..
				distance=0;
				direction=null;

				// check the number of fingers is what we are looking for
				if (fingerCount == defaults.fingers || !hasTouch)
				{
					// get the coordinates of the touch
					start.x = end.x = evt.pageX;
					start.y = end.y = evt.pageY;

					if (defaults.swipeStatus)
						triggerHandler(event, phase);

					// REV mdc

					var thisDate = new Date();
					startTouchTime = thisDate.getTime();
				}
				else
				{
					//touch with more/less than the fingers we are looking for
					touchCancel(event);
				}

				that.addEventListener(MOVE_EV, touchMove, false);
				that.addEventListener(END_EV, touchEnd, false);
			}

			/**
			* Event handler for a touch move event.
			* If we change fingers during move, then cancel the event
			*/
			function touchMove(event)
			{
				if (phase == PHASE_END || phase == PHASE_CANCEL)
					return;

                var evt = hasTouch ? event.touches[0] : event;

				end.x = evt.pageX;
				end.y = evt.pageY;

				direction = caluculateDirection();
                if (hasTouch) {
                    fingerCount = event.touches.length;
                }

				phase = PHASE_MOVE

				//Check if we need to prevent default evnet (page scroll) or not
				validateDefaultEvent(event, direction);

				if ( fingerCount == defaults.fingers || !hasTouch)
				{
					distance = caluculateDistance();

					if (defaults.swipeStatus)
						triggerHandler(event, phase, direction, distance);

					//If we trigger whilst dragging, not on touch end, then calculate now...
					if (!defaults.triggerOnTouchEnd)
					{
						// ADDED by Mark Chase 2012-Apr-27
						// if the user swiped more than the minimum length, perform the appropriate action

						var thisDate = new Date();
						var endTouchTime = thisDate.getTime();
						var totalTouchTime = endTouchTime - startTouchTime;
						//
						if ( distance >= defaults.threshold  && totalTouchTime <= defaults.timeThreshold)
						{
							phase = PHASE_END;
							triggerHandler(event, phase);
							touchCancel(event); // reset the variables
						}
					}
				}
				else
				{
					phase = PHASE_CANCEL;
					triggerHandler(event, phase);
					touchCancel(event);
				}
			}

			/**
			* Event handler for a touch end event.
			* Calculate the direction and trigger events
			*/
			function touchEnd(event)
			{
				event.preventDefault();

				distance = caluculateDistance();
				direction = caluculateDirection();

				if (defaults.triggerOnTouchEnd)
				{
					phase = PHASE_END;
					// check to see if more than one finger was used and that there is an ending coordinate
					if ( (fingerCount == defaults.fingers  || !hasTouch) && end.x != 0 )
					{
						// ADDED by Mark Chase 2012-Apr-27
						var thisDate = new Date();
						var endTouchTime = thisDate.getTime();
						var totalTouchTime = endTouchTime - startTouchTime;
						//

						// if the user swiped more than the minimum length, perform the appropriate action
						if ( distance >= defaults.threshold && totalTouchTime <= defaults.timeThreshold)
						{
							triggerHandler(event, phase);
							touchCancel(event); // reset the variables
						}
						else
						{
							phase = PHASE_CANCEL;
							triggerHandler(event, phase);
							touchCancel(event);
						}
					}
					else
					{
						phase = PHASE_CANCEL;
						triggerHandler(event, phase);
						touchCancel(event);
					}
				}
				else if (phase == PHASE_MOVE)
				{
					phase = PHASE_CANCEL;
					triggerHandler(event, phase);
					touchCancel(event);
				}
				that.removeEventListener(MOVE_EV, touchMove, false);
				that.removeEventListener(END_EV, touchEnd, false);
			}

			/**
			* Event handler for a touch cancel event.
			* Clears current vars
			*/
			function touchCancel(event)
			{
				// reset the variables back to default values
				fingerCount = 0;

				start.x = 0;
				start.y = 0;
				end.x = 0;
				end.y = 0;
				delta.x = 0;
				delta.y = 0;
			}

			/**
			* Trigger the relevant event handler
			* The handlers are passed the original event, the element that was swiped, and in the case of the catch all handler, the direction that was swiped, "left", "right", "up", or "down"
			*/
			function triggerHandler(event, phase)
			{
				//update status
				if (defaults.swipeStatus)
					defaults.swipeStatus.call($this,event, phase, direction || null, distance || 0);

				if (phase == PHASE_CANCEL)
				{
					if (defaults.click && (fingerCount==1 || !hasTouch) && (isNaN(distance) || distance==0))
						defaults.click.call($this,event, event.target);
				}

				if (phase == PHASE_END)
				{
					//trigger catch all event handler
					if (defaults.swipe)
				{

						defaults.swipe.call($this,event, direction, distance);

				}
					//trigger direction specific event handlers
					switch(direction)
					{
						case LEFT :
							if (defaults.swipeLeft)
								defaults.swipeLeft.call($this,event, direction, distance);
							break;

						case RIGHT :
							if (defaults.swipeRight)
								defaults.swipeRight.call($this,event, direction, distance);
							break;

						case UP :
							if (defaults.swipeUp)
								defaults.swipeUp.call($this,event, direction, distance);
							break;

						case DOWN :
							if (defaults.swipeDown)
								defaults.swipeDown.call($this,event, direction, distance);
							break;
					}
				}
			}

			/**
			 * Checks direction of the swipe and the value allowPageScroll to see if we should allow or prevent the default behaviour from occurring.
			 * This will essentially allow page scrolling or not when the user is swiping on a touchSwipe object.
			 */
			function validateDefaultEvent(event, direction)
			{
				if( defaults.allowPageScroll==NONE )
				{
					event.preventDefault();
				}
				else
				{
					var auto=defaults.allowPageScroll==AUTO;

					switch(direction)
					{
						case LEFT :
							if ( (defaults.swipeLeft && auto) || (!auto && defaults.allowPageScroll!=HORIZONTAL))
								event.preventDefault();
							break;

						case RIGHT :
							if ( (defaults.swipeRight && auto) || (!auto && defaults.allowPageScroll!=HORIZONTAL))
								event.preventDefault();
							break;

						case UP :
							if ( (defaults.swipeUp && auto) || (!auto && defaults.allowPageScroll!=VERTICAL))
								event.preventDefault();
							break;

						case DOWN :
							if ( (defaults.swipeDown && auto) || (!auto && defaults.allowPageScroll!=VERTICAL))
								event.preventDefault();
							break;
					}
				}

			}

			/**
			* Calcualte the length / distance of the swipe
			*/
			function caluculateDistance()
			{
				return Math.round(Math.sqrt(Math.pow(end.x - start.x,2) + Math.pow(end.y - start.y,2)));
			}

			/**
			* Calcualte the angle of the swipe
			*/
			function caluculateAngle()
			{
				var X = start.x-end.x;
				var Y = end.y-start.y;
				var r = Math.atan2(Y,X); //radians
				var angle = Math.round(r*180/Math.PI); //degrees

				//ensure value is positive
				if (angle < 0)
					angle = 360 - Math.abs(angle);

				return angle;
			}

			/**
			* Calcualte the direction of the swipe
			* This will also call caluculateAngle to get the latest angle of swipe
			*/
			function caluculateDirection()
			{
				var angle = caluculateAngle();

				if ( (angle <= 45) && (angle >= 0) )
					return LEFT;

				else if ( (angle <= 360) && (angle >= 315) )
					return LEFT;

				else if ( (angle >= 135) && (angle <= 225) )
					return RIGHT;

				else if ( (angle > 45) && (angle < 135) )
					return DOWN;

				else
					return UP;
			}

			// Add gestures to all swipable areas if supported
			try
			{

				this.addEventListener(START_EV, touchStart, false);
				this.addEventListener(CANCEL_EV, touchCancel);
			}
			catch(e)
			{
				//touch not supported
			}

		});
	};

})(jQuery);
<commit_msg>Made time threshold backwards compatible, by assigning null default value, and refactored.  Added duration param that is passed to all event handler. Changed file name to make history / diff tracking easier<commit_after><|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.client',
  name: 'Client',

  implements: [ 'foam.box.Context' ],

  documentation: 'Client for connecting to NANOS server.',

  requires: [
    'foam.box.HTTPBox',
    'foam.box.WebSocketBox',
    'foam.dao.RequestResponseClientDAO',
    'foam.dao.ClientDAO',
    'foam.dao.EasyDAO',
    'foam.nanos.auth.Country',
    'foam.nanos.auth.Group',
    'foam.nanos.auth.Language',
    'foam.nanos.auth.Permission',
    'foam.nanos.auth.Region',
    'foam.nanos.auth.User',
    'foam.nanos.boot.NSpec',
    'foam.nanos.cron.Cron',
    'foam.nanos.export.ExportDriverRegistry',
    'foam.nanos.menu.Menu',
    'foam.nanos.pm.PMInfo',
    'foam.nanos.script.Script',
    'foam.nanos.test.Test',
    'foam.nanos.auth.WebAuthService',
    'foam.nanos.auth.ClientAuthService'
  ],

  exports: [
    'countryDAO',
    'cronDAO',
    'exportDriverRegistryDAO',
    'groupDAO',
    'languageDAO',
    'menuDAO',
    'nSpecDAO',
    'permissionDAO',
    'pmInfoDAO',
    'regionDAO',
    'scriptDAO',
    'testDAO',
    'userDAO',
    'webAuth'
  ],

  properties: [
    {
      name: 'webAuth',
      factory: function() {
        return this.ClientAuthService.create({
          delegate: this.HTTPBox.create({
            method: 'POST',
            url: 'http://localhost:8080/webAuth'
          })
        });
      }
    },

    {
      name: 'userDAO',
      factory: function() {
        return this.RequestResponseClientDAO.create({
          of: this.User,
          delegate: this.HTTPBox.create({
            method: 'POST',
            url: 'http://localhost:8080/userDAO'
          })});
      }
    },

    {
      name: 'nSpecDAO',
      factory: function() {
        return this.RequestResponseClientDAO.create({
          of: this.NSpec,
          delegate: this.HTTPBox.create({
            method: 'POST',
            url: 'http://localhost:8080/nSpecDAO'
          })});
        /*
        return this.createDAO({
          of: this.NSpec,
          seqNo: true,
          testData: [
            { name: 'http',   serve: false, serviceClass: 'foam.nanos.http.NanoHttpServer' },
            { name: 'pmlog',  serve: false, serviceClass: 'foam.nanos.pm.DAOPMLogger' },
            { name: 'auth',   serve: true,  serviceClass: 'foam.nanos.auth.UserAndGroupAuthService' },
            { name: 'test',   serve: true,  serviceClass: 'foam.nanos.test.TestRunner' },
            { name: 'script', serve: true,  serviceClass: 'foam.nanos.script.ScriptRunner' },
            { name: 'cron',   serve: true,  serviceClass: 'foam.nanos.cron.CronRunner' }
          ]
        });
        */
      }
    },

    {
      name: 'countryDAO',
      factory: function() {
        return this.createDAO({
          of: this.Country,
          testData: [
            { code: 'BR', name: 'Brazil' },
            { code: 'CA', name: 'Canada' },
            { code: 'CN', name: 'China' },
            { code: 'IN', name: 'India' },
            { code: 'JM', name: 'Jamaica' },
            { code: 'LB', name: 'Lebanon' },
            { code: 'MX', name: 'Mexico' },
            { code: 'MY', name: 'Malaysia' },
            { code: 'RS', name: 'Serbia' },
            { code: 'TT', name: 'Trinidad and Tobago' },
            { code: 'UK', name: 'United Kingdom' },
            { code: 'US', name: 'USA' },
            { code: 'ZA', name: 'South Africa' }
          ]
        });
      }
    },

    // TODO: change to client DAO
    {
      name: 'exportDriverRegistryDAO',
      factory: function() {
        return this.createDAO({
          of: this.ExportDriverRegistry,
          testData: [
            { id: 'CSV',  driverName: 'net.nanopay.export.CSVDriver' },
            { id: 'JSON', driverName: 'net.nanopay.export.JSONDriver' },
            { id: 'XML',  driverName: 'net.nanopay.export.XMLDriver' }
          ]
        });
      }
    },

    {
      name: 'regionDAO',
      factory: function() {
        return this.createDAO({
          of: this.Region,
          testData: [
            { countryId: 'CA', code: 'ON', name: 'Ontario' },
            { countryId: 'CA', code: 'PQ', name: 'Quebec' },
            { countryId: 'IN', code: 'MH', name: 'Maharashtra'}
          ]
        });
      }
    },

    {
      name: 'menuDAO',
      factory: function() {
        return this.createDAO({

          of: this.Menu,
          testData: [
            { id: 'admin',                           label: 'Admin',          handler: { class: 'foam.nanos.menu.TabsMenu' /*SubMenu*/ } },
              // { parent: 'admin', id: 'auth',         label: 'Authentication', handler: { class: 'foam.nanos.menu.TabsMenu' } },
                { parent: /*'auth'*/'admin', id: 'users',       label: 'Users',          handler: { class: 'foam.nanos.menu.DAOMenu', daoKey: 'userDAO' } },
                { parent: /*'auth'*/'admin', id: 'groups',      label: 'Groups',         handler: { class: 'foam.nanos.menu.DAOMenu', daoKey: 'groupDAO' } },
                { parent: /*'auth'*/'admin', id: 'permissions', label: 'Permissions',    handler: { class: 'foam.nanos.menu.DAOMenu', daoKey: 'permissionDAO' }  },
                { parent: /*'auth'*/'admin', id: 'countries',   label: 'Countries',      handler: { class: 'foam.nanos.menu.DAOMenu', daoKey: 'countryDAO' } },
                { parent: /*'auth'*/'admin', id: 'regions',     label: 'Regions',        handler: { class: 'foam.nanos.menu.DAOMenu', daoKey: 'regionDAO' } },
                { parent: /*'auth'*/'admin', id: 'lang',        label: 'Languages',      handler: { class: 'foam.nanos.menu.DAOMenu', daoKey: 'languageDAO' } },
              { parent: 'admin', id: 'nspec',        label: 'Nano Services',  handler: { class: 'foam.nanos.menu.DAOMenu', daoKey: 'nSpecDAO' }  },
              { parent: 'admin', id: 'export',       label: 'Export Drivers', handler: { class: 'foam.nanos.menu.DAOMenu', daoKey: 'exportDriverRegistryDAO' }  },
              { parent: 'admin', id: 'menus',        label: 'Menus',          handler: { class: 'foam.nanos.menu.DAOMenu', daoKey: 'menuDAO', XXXsummaryView: { class: 'foam.u2.view.TreeView', relationship: MenuRelationship, formatter: function() { this.add(this.data.label); } }  } },
              { parent: 'admin', id: 'scripts',      label: 'Scripts',        handler: { class: 'foam.nanos.menu.DAOMenu', daoKey: 'scriptDAO' } },
              { parent: 'admin', id: 'tests',        label: 'Tests',          handler: { class: 'foam.nanos.menu.DAOMenu', daoKey: 'testDAO', summaryView: { class: 'foam.nanos.test.TestBorder' } } },
              { parent: 'admin', id: 'cron',         label: 'Cron Jobs',      handler: { class: 'foam.nanos.menu.DAOMenu', daoKey: 'cronDAO' } },
              { parent: 'admin', id: 'pm',           label: 'Performance',    handler: { class: 'foam.nanos.menu.DAOMenu', daoKey: 'pmInfoDAO', summaryView: { class: 'foam.nanos.pm.PMTableView' } } },
              { parent: 'admin', id: 'log',          label: 'View Logs' },
              /*
            { id: 'support',                         label: 'Support',         handler: { class: 'foam.nanos.menu.TabsMenu' } },
              { parent: 'support', id: 'api',        label: 'API Reference' },
              { parent: 'support', id: 'context',    label: 'Context Walker' }
              */
          ]
        }).orderBy(this.Menu.ORDER, this.Menu.ID);
      }
    },

    {
      name: 'languageDAO',
      factory: function() {
        return this.createDAO({
          of: this.Language,
          testData: [
            { code: 'en', name: 'English' },
            { code: 'fr', name: 'French' }
          ]
        });
      }
    },

    {
      name: 'groupDAO',
      factory: function() {
        return this.createDAO({
          of: this.Group,
          seqNo: true,
          testData: [
            { id: 1, firstName: 'nanoPay Admin', lastName: 'nanoPay administration users' },
            { id: 2, firstName: 'Admin',         lastName: 'Administration users' },
            { id: 3, firstName: 'Tester',        lastName: 'Testers' },
            { id: 3, firstName: 'End User',      lastName: 'End users' }
          ]
        });
      }
    },

      {
        name: 'permissionDAO',
        factory: function() {
          return this.createDAO({
            of: this.Permission,
            testData: [
              { id: '*',         description: 'Do anything global permission.' },
              { id: 'menu.auth', description: 'Perform authentication related configuration.' }
            ]
          });
        }
      },

        {
          name: 'scriptDAO',
          factory: function() {
            return this.RequestResponseClientDAO.create({
              of: this.Script,
              delegate: this.HTTPBox.create({
                method: 'POST',
                url: 'http://localhost:8080/scriptDAO'
              })});
              /*

            return this.createDAO({
              of: this.Script,
              seqNo: true,
              testData: [
              ]
            });*/
          }
        },

        {
          name: 'pmInfoDAO',
          factory: function() {
            return this.EasyDAO.create({
              daoType: 'CLIENT',
              remoteListenerSupport: true,
              of: this.PMInfo,
              serviceName: 'pmInfoDAO'});
          }
        },

        {
          name: 'cronDAO',
          factory: function() {
            return this.createDAO({
              of: this.Cron,
              seqNo: true,
              testData: [
              ]
            });
          }
        },

        {
          name: 'testDAO',
          factory: function() {
            return this.RequestResponseClientDAO.create({
              of: this.Test,
              delegate: this.HTTPBox.create({
              method: 'POST',
              url: 'http://localhost:8080/testDAO'
            })});

            /*
            return this.createDAO({
              of: this.Test,
              seqNo: true,
              testData: [
              ]
            });
            */
          }
        }

  ],

  methods: [
    function createDAO(config) {
      config.daoType = 'MDAO'; // 'IDB';
      config.cache   = true;

      return this.EasyDAO.create(config);
    }
  ]
});
<commit_msg>Added more regions to regionDAO<commit_after>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.client',
  name: 'Client',

  implements: [ 'foam.box.Context' ],

  documentation: 'Client for connecting to NANOS server.',

  requires: [
    'foam.box.HTTPBox',
    'foam.box.WebSocketBox',
    'foam.dao.RequestResponseClientDAO',
    'foam.dao.ClientDAO',
    'foam.dao.EasyDAO',
    'foam.nanos.auth.Country',
    'foam.nanos.auth.Group',
    'foam.nanos.auth.Language',
    'foam.nanos.auth.Permission',
    'foam.nanos.auth.Region',
    'foam.nanos.auth.User',
    'foam.nanos.boot.NSpec',
    'foam.nanos.cron.Cron',
    'foam.nanos.export.ExportDriverRegistry',
    'foam.nanos.menu.Menu',
    'foam.nanos.pm.PMInfo',
    'foam.nanos.script.Script',
    'foam.nanos.test.Test',
    'foam.nanos.auth.WebAuthService',
    'foam.nanos.auth.ClientAuthService'
  ],

  exports: [
    'countryDAO',
    'cronDAO',
    'exportDriverRegistryDAO',
    'groupDAO',
    'languageDAO',
    'menuDAO',
    'nSpecDAO',
    'permissionDAO',
    'pmInfoDAO',
    'regionDAO',
    'scriptDAO',
    'testDAO',
    'userDAO',
    'webAuth'
  ],

  properties: [
    {
      name: 'webAuth',
      factory: function() {
        return this.ClientAuthService.create({
          delegate: this.HTTPBox.create({
            method: 'POST',
            url: 'http://localhost:8080/webAuth'
          })
        });
      }
    },

    {
      name: 'userDAO',
      factory: function() {
        return this.RequestResponseClientDAO.create({
          of: this.User,
          delegate: this.HTTPBox.create({
            method: 'POST',
            url: 'http://localhost:8080/userDAO'
          })});
      }
    },

    {
      name: 'nSpecDAO',
      factory: function() {
        return this.RequestResponseClientDAO.create({
          of: this.NSpec,
          delegate: this.HTTPBox.create({
            method: 'POST',
            url: 'http://localhost:8080/nSpecDAO'
          })});
        /*
        return this.createDAO({
          of: this.NSpec,
          seqNo: true,
          testData: [
            { name: 'http',   serve: false, serviceClass: 'foam.nanos.http.NanoHttpServer' },
            { name: 'pmlog',  serve: false, serviceClass: 'foam.nanos.pm.DAOPMLogger' },
            { name: 'auth',   serve: true,  serviceClass: 'foam.nanos.auth.UserAndGroupAuthService' },
            { name: 'test',   serve: true,  serviceClass: 'foam.nanos.test.TestRunner' },
            { name: 'script', serve: true,  serviceClass: 'foam.nanos.script.ScriptRunner' },
            { name: 'cron',   serve: true,  serviceClass: 'foam.nanos.cron.CronRunner' }
          ]
        });
        */
      }
    },

    {
      name: 'countryDAO',
      factory: function() {
        return this.createDAO({
          of: this.Country,
          testData: [
            { code: 'BR', name: 'Brazil' },
            { code: 'CA', name: 'Canada' },
            { code: 'CN', name: 'China' },
            { code: 'IN', name: 'India' },
            { code: 'JM', name: 'Jamaica' },
            { code: 'LB', name: 'Lebanon' },
            { code: 'MX', name: 'Mexico' },
            { code: 'MY', name: 'Malaysia' },
            { code: 'RS', name: 'Serbia' },
            { code: 'TT', name: 'Trinidad and Tobago' },
            { code: 'UK', name: 'United Kingdom' },
            { code: 'US', name: 'USA' },
            { code: 'ZA', name: 'South Africa' }
          ]
        });
      }
    },

    // TODO: change to client DAO
    {
      name: 'exportDriverRegistryDAO',
      factory: function() {
        return this.createDAO({
          of: this.ExportDriverRegistry,
          testData: [
            { id: 'CSV',  driverName: 'net.nanopay.export.CSVDriver' },
            { id: 'JSON', driverName: 'net.nanopay.export.JSONDriver' },
            { id: 'XML',  driverName: 'net.nanopay.export.XMLDriver' }
          ]
        });
      }
    },

    {
      name: 'regionDAO',
      factory: function() {
        return this.createDAO({
          of: this.Region,
          testData: [
            { countryId: 'CA', code: 'AB', name: 'Alberta' },
            { countryId: 'CA', code: 'BC', name: 'British Columbia' },
            { countryId: 'CA', code: 'MB', name: 'Manitoba' },
            { countryId: 'CA', code: 'NB', name: 'New Brunswick' },
            { countryId: 'CA', code: 'NL', name: 'Newfoundland' },
            { countryId: 'CA', code: 'NS', name: 'Nova Scotia' },
            { countryId: 'CA', code: 'NT', name: 'Northwest Territories' },
            { countryId: 'CA', code: 'NU', name: 'Nunavut' },
            { countryId: 'CA', code: 'ON', name: 'Ontario' },
            { countryId: 'CA', code: 'PE', name: 'Prince Edward Island' },
            { countryId: 'CA', code: 'QC', name: 'Quebec' },
            { countryId: 'CA', code: 'SK', name: 'Saskatchewan' },
            { countryId: 'CA', code: 'YT', name: 'Yukon' },
            { countryId: 'IN', code: 'MH', name: 'Maharashtra'}
          ]
        });
      }
    },

    {
      name: 'menuDAO',
      factory: function() {
        return this.createDAO({

          of: this.Menu,
          testData: [
            { id: 'admin',                           label: 'Admin',          handler: { class: 'foam.nanos.menu.TabsMenu' /*SubMenu*/ } },
              // { parent: 'admin', id: 'auth',         label: 'Authentication', handler: { class: 'foam.nanos.menu.TabsMenu' } },
                { parent: /*'auth'*/'admin', id: 'users',       label: 'Users',          handler: { class: 'foam.nanos.menu.DAOMenu', daoKey: 'userDAO' } },
                { parent: /*'auth'*/'admin', id: 'groups',      label: 'Groups',         handler: { class: 'foam.nanos.menu.DAOMenu', daoKey: 'groupDAO' } },
                { parent: /*'auth'*/'admin', id: 'permissions', label: 'Permissions',    handler: { class: 'foam.nanos.menu.DAOMenu', daoKey: 'permissionDAO' }  },
                { parent: /*'auth'*/'admin', id: 'countries',   label: 'Countries',      handler: { class: 'foam.nanos.menu.DAOMenu', daoKey: 'countryDAO' } },
                { parent: /*'auth'*/'admin', id: 'regions',     label: 'Regions',        handler: { class: 'foam.nanos.menu.DAOMenu', daoKey: 'regionDAO' } },
                { parent: /*'auth'*/'admin', id: 'lang',        label: 'Languages',      handler: { class: 'foam.nanos.menu.DAOMenu', daoKey: 'languageDAO' } },
              { parent: 'admin', id: 'nspec',        label: 'Nano Services',  handler: { class: 'foam.nanos.menu.DAOMenu', daoKey: 'nSpecDAO' }  },
              { parent: 'admin', id: 'export',       label: 'Export Drivers', handler: { class: 'foam.nanos.menu.DAOMenu', daoKey: 'exportDriverRegistryDAO' }  },
              { parent: 'admin', id: 'menus',        label: 'Menus',          handler: { class: 'foam.nanos.menu.DAOMenu', daoKey: 'menuDAO', XXXsummaryView: { class: 'foam.u2.view.TreeView', relationship: MenuRelationship, formatter: function() { this.add(this.data.label); } }  } },
              { parent: 'admin', id: 'scripts',      label: 'Scripts',        handler: { class: 'foam.nanos.menu.DAOMenu', daoKey: 'scriptDAO' } },
              { parent: 'admin', id: 'tests',        label: 'Tests',          handler: { class: 'foam.nanos.menu.DAOMenu', daoKey: 'testDAO', summaryView: { class: 'foam.nanos.test.TestBorder' } } },
              { parent: 'admin', id: 'cron',         label: 'Cron Jobs',      handler: { class: 'foam.nanos.menu.DAOMenu', daoKey: 'cronDAO' } },
              { parent: 'admin', id: 'pm',           label: 'Performance',    handler: { class: 'foam.nanos.menu.DAOMenu', daoKey: 'pmInfoDAO', summaryView: { class: 'foam.nanos.pm.PMTableView' } } },
              { parent: 'admin', id: 'log',          label: 'View Logs' },
              /*
            { id: 'support',                         label: 'Support',         handler: { class: 'foam.nanos.menu.TabsMenu' } },
              { parent: 'support', id: 'api',        label: 'API Reference' },
              { parent: 'support', id: 'context',    label: 'Context Walker' }
              */
          ]
        }).orderBy(this.Menu.ORDER, this.Menu.ID);
      }
    },

    {
      name: 'languageDAO',
      factory: function() {
        return this.createDAO({
          of: this.Language,
          testData: [
            { code: 'en', name: 'English' },
            { code: 'fr', name: 'French' }
          ]
        });
      }
    },

    {
      name: 'groupDAO',
      factory: function() {
        return this.createDAO({
          of: this.Group,
          seqNo: true,
          testData: [
            { id: 1, firstName: 'nanoPay Admin', lastName: 'nanoPay administration users' },
            { id: 2, firstName: 'Admin',         lastName: 'Administration users' },
            { id: 3, firstName: 'Tester',        lastName: 'Testers' },
            { id: 3, firstName: 'End User',      lastName: 'End users' }
          ]
        });
      }
    },

      {
        name: 'permissionDAO',
        factory: function() {
          return this.createDAO({
            of: this.Permission,
            testData: [
              { id: '*',         description: 'Do anything global permission.' },
              { id: 'menu.auth', description: 'Perform authentication related configuration.' }
            ]
          });
        }
      },

        {
          name: 'scriptDAO',
          factory: function() {
            return this.RequestResponseClientDAO.create({
              of: this.Script,
              delegate: this.HTTPBox.create({
                method: 'POST',
                url: 'http://localhost:8080/scriptDAO'
              })});
              /*

            return this.createDAO({
              of: this.Script,
              seqNo: true,
              testData: [
              ]
            });*/
          }
        },

        {
          name: 'pmInfoDAO',
          factory: function() {
            return this.EasyDAO.create({
              daoType: 'CLIENT',
              remoteListenerSupport: true,
              of: this.PMInfo,
              serviceName: 'pmInfoDAO'});
          }
        },

        {
          name: 'cronDAO',
          factory: function() {
            return this.createDAO({
              of: this.Cron,
              seqNo: true,
              testData: [
              ]
            });
          }
        },

        {
          name: 'testDAO',
          factory: function() {
            return this.RequestResponseClientDAO.create({
              of: this.Test,
              delegate: this.HTTPBox.create({
              method: 'POST',
              url: 'http://localhost:8080/testDAO'
            })});

            /*
            return this.createDAO({
              of: this.Test,
              seqNo: true,
              testData: [
              ]
            });
            */
          }
        }

  ],

  methods: [
    function createDAO(config) {
      config.daoType = 'MDAO'; // 'IDB';
      config.cache   = true;

      return this.EasyDAO.create(config);
    }
  ]
});
<|endoftext|>