<commit_before>const config = require('./config.js');
const sortingOption = {
  order: [
    'custom-properties',
    'dollar-variables',
    'declarations',
    'at-rules',
    {
      type: 'at-rule',
      name: 'include',
    },
    {
      type: 'at-rule',
      name: 'include',
      parameter: 'icon',
    },
    'rules',
  ],
  'properties-order': [
    {
      emptyLineBefore: true,
      properties: [
        'margin',
        'padding',
      ],
    },
    {
      emptyLineBefore: true,
      properties: [
        'border',
        'background',
      ],
    },
  ],
  'unspecified-properties-position': 'bottom',
};

module.exports = {
  plugins: [
    require('postcss-smart-import'),
    require('postcss-zindex'),
    require('postcss-will-change'),
    require('postcss-merge-longhand'),
    require('css-mqpacker')({
      sort: true,
    }),
    require('cssnano')({
      options: {
        autoprefixer: false,
        colormin: true,
        convertValues: true,
        discardComments: { removeAll: true },
        discardDuplicates: true,
        discardEmpty: true,
        discardOverridden: true,
        mergeLonghand: true,
        mergeRules: true,
        minifyFontValues: true,
        minifySelectors: true,
        uniqueSelectors: true,
      },
    }),
    require('postcss-sorting')(sortingOption),
    require('postcss-cssnext')({
      browsers: config.browsers,
    }),
  ],
  options: {
    output: { path: config.paths.dist },
    context: config.paths.assets,
    sourceMap: 'inline',
  },
};
<commit_msg>remove: properties-order option<commit_after>const config = require('./config.js');
const sortingOption = {
  order: [
    'custom-properties',
    'dollar-variables',
    'declarations',
    'at-rules',
    {
      type: 'at-rule',
      name: 'include',
    },
    {
      type: 'at-rule',
      name: 'include',
      parameter: 'icon',
    },
    'rules',
  ],
  'unspecified-properties-position': 'bottom',
};

module.exports = {
  plugins: [
    require('postcss-smart-import'),
    require('postcss-zindex'),
    require('postcss-will-change'),
    require('postcss-merge-longhand'),
    require('css-mqpacker')({
      sort: true,
    }),
    require('cssnano')({
      options: {
        autoprefixer: false,
        colormin: true,
        convertValues: true,
        discardComments: { removeAll: true },
        discardDuplicates: true,
        discardEmpty: true,
        discardOverridden: true,
        mergeLonghand: true,
        mergeRules: true,
        minifyFontValues: true,
        minifySelectors: true,
        uniqueSelectors: true,
      },
    }),
    require('postcss-sorting')(sortingOption),
    require('postcss-cssnext')({
      browsers: config.browsers,
    }),
  ],
  options: {
    output: { path: config.paths.dist },
    context: config.paths.assets,
    sourceMap: 'inline',
  },
};
<|endoftext|>


<commit_before>/**
 * van11y-accessible-hide-show-aria - ES2015 accessible hide-show system (collapsible regions), using ARIA
 * @version v1.0.0
 * @link https://van11y.net/accessible-hide-show/
 * @license MIT : https://github.com/nico3333fr/van11y-accessible-hide-show-aria/blob/master/LICENSE
 */
"use strict";function _defineProperty(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}!function(e){var t="js-expandmore",n="js-expandmore-button",i="expandmore__button",r="label_expand_",a="data-hideshow-prefix-class",o="expand_",c="expandmore__to_expand",s="data-controls",d="aria-expanded",u="data-labelledby",l="data-hidden",f="is-opened",b="js-first_load",p="1500",m=function(t){return e.getElementById(t)},v=function(e,t){e.classList?e.classList.add(t):e.className+=" "+t},y=function(e,t){e.classList?e.classList.remove(t):e.className=e.className.replace(new RegExp("(^|\\b)"+t.split(" ").join("|")+"(\\b|$)","gi")," ")},E=function(e,t){return e.classList?e.classList.contains(t):new RegExp("(^| )"+t+"( |$)","gi").test(e.className)},_=function(e,t){Object.keys(t).forEach(function(n){e.setAttribute(n,t[n])})},g=function(e,t){if(e.fireEvent)e.fireEvent("on"+t);else{var n=document.createEvent("Events");n.initEvent(t,!0,!1),e.dispatchEvent(n)}},L=function(){return[].slice.call(e.querySelectorAll("."+t))},x=function A(){L().forEach(function(t,m){var g,L,x=m+1,A=t.hasAttribute(a)===!0?t.getAttribute(a)+"-":"",k=t.nextElementSibling,h=t.innerHTML,P=e.createElement("BUTTON");t.innerHTML="",v(P,A+i),v(P,n),_(P,(g={},_defineProperty(g,s,o+x),_defineProperty(g,d,"false"),_defineProperty(g,"id",r+x),g)),P.innerHTML=h,t.appendChild(P),_(k,(L={},_defineProperty(L,u,r+x),_defineProperty(L,l,"true"),_defineProperty(L,"id",o+x),L)),v(k,A+c),E(k,b)===!0&&setTimeout(function(){y(k,b)},p),E(k,f)===!0&&(v(P,f),P.setAttribute(d,"true"),y(k,f),k.removeAttribute(l))}),["click","keydown"].forEach(function(i){e.body.addEventListener(i,function(e){if(E(e.target,n)===!0&&"click"===i){var r=e.target,a=m(r.getAttribute(s)),o=r.getAttribute(d);"false"===o?(r.setAttribute(d,!0),v(r,f),a.removeAttribute(l)):(r.setAttribute(d,!1),y(r,f),a.setAttribute(l,!0))}if(E(e.target,t)===!0){var c=e.target,u=c.querySelector("."+n);if(c!=u){if("click"===i)return g(u,"click"),!1;if("keydown"===i&&(13===e.keyCode||32===e.keyCode))return g(u,"click"),!1}}},!0)}),document.removeEventListener("DOMContentLoaded",A)};document.addEventListener("DOMContentLoaded",x)}(document);<commit_msg>Update version number<commit_after>/**
 * van11y-accessible-hide-show-aria - ES2015 accessible hide-show system (collapsible regions), using ARIA
 * @version v1.0.2
 * @link https://van11y.net/accessible-hide-show/
 * @license MIT : https://github.com/nico3333fr/van11y-accessible-hide-show-aria/blob/master/LICENSE
 */
"use strict";function _defineProperty(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}!function(e){var t="js-expandmore",n="js-expandmore-button",i="expandmore__button",r="label_expand_",a="data-hideshow-prefix-class",o="expand_",c="expandmore__to_expand",s="data-controls",d="aria-expanded",u="data-labelledby",l="data-hidden",f="is-opened",b="js-first_load",p="1500",m=function(t){return e.getElementById(t)},v=function(e,t){e.classList?e.classList.add(t):e.className+=" "+t},y=function(e,t){e.classList?e.classList.remove(t):e.className=e.className.replace(new RegExp("(^|\\b)"+t.split(" ").join("|")+"(\\b|$)","gi")," ")},E=function(e,t){return e.classList?e.classList.contains(t):new RegExp("(^| )"+t+"( |$)","gi").test(e.className)},_=function(e,t){Object.keys(t).forEach(function(n){e.setAttribute(n,t[n])})},g=function(e,t){if(e.fireEvent)e.fireEvent("on"+t);else{var n=document.createEvent("Events");n.initEvent(t,!0,!1),e.dispatchEvent(n)}},L=function(){return[].slice.call(e.querySelectorAll("."+t))},x=function A(){L().forEach(function(t,m){var g,L,x=m+1,A=t.hasAttribute(a)===!0?t.getAttribute(a)+"-":"",k=t.nextElementSibling,h=t.innerHTML,P=e.createElement("BUTTON");t.innerHTML="",v(P,A+i),v(P,n),_(P,(g={},_defineProperty(g,s,o+x),_defineProperty(g,d,"false"),_defineProperty(g,"id",r+x),g)),P.innerHTML=h,t.appendChild(P),_(k,(L={},_defineProperty(L,u,r+x),_defineProperty(L,l,"true"),_defineProperty(L,"id",o+x),L)),v(k,A+c),E(k,b)===!0&&setTimeout(function(){y(k,b)},p),E(k,f)===!0&&(v(P,f),P.setAttribute(d,"true"),y(k,f),k.removeAttribute(l))}),["click","keydown"].forEach(function(i){e.body.addEventListener(i,function(e){if(E(e.target,n)===!0&&"click"===i){var r=e.target,a=m(r.getAttribute(s)),o=r.getAttribute(d);"false"===o?(r.setAttribute(d,!0),v(r,f),a.removeAttribute(l)):(r.setAttribute(d,!1),y(r,f),a.setAttribute(l,!0))}if(E(e.target,t)===!0){var c=e.target,u=c.querySelector("."+n);if(c!=u){if("click"===i)return g(u,"click"),!1;if("keydown"===i&&(13===e.keyCode||32===e.keyCode))return g(u,"click"),!1}}},!0)}),document.removeEventListener("DOMContentLoaded",A)};document.addEventListener("DOMContentLoaded",x)}(document);
<|endoftext|>


<commit_before>(function($){
	 //focusing on box first will do sphere later

	var threeDJson = new Object();

 	$.threeDLoad = function(obj){
 		//Load a JS object or JSON String to begin.
		if(typeof obj === 'object'){
			threeDJson = obj;
		}else{
			try {
     			var jsonObject = jQuery.parseJSON(obj);
			} catch (e) {
    			return false;
			}
		  	threeDJson = jsonObject;
		  	return true;
		}
 	}
 	$.threeDShow = function(remove){
 		//I show the whole JSON with & without Prefex.
	 	if(typeof remove === 'undefined' || remove === false){ return threeDJson; }
	 	if(remove === true){ return jQuery.threeDRemove(); }else{ return threeDJson;}
 	}

 	$.threeDSplit = function(string){
 		//interna function to split prefex if you passed a string instead of Array
 		var data = string.split('~');
    	return data[1];
 	}

 	$.threeDRemove = function(){
 		//goes through JSON and removes 3DJSON prefex EX."-190,0~element":"data" => "element":"data"
 		//needs more work to be usable on decimal numbers
 		return jQuery.parseJSON(JSON.stringify(threeDJson).replace(/["]-?[\d]{1,3}[\/,]-?[\d]{1,3}[\/~]/g ,'"'));
 	}

 	$.threeDStringToArray = function(string){
 		//  '90,0' => [90,0]
 	 	if(typeof string !== 'undefined'){
 			//assumes it a string of '90,0'
 			var data = string.split('~');
 			if(data.length !== 2 || !jQuery.isNumeric(data[0]) || !jQuery.isNumeric(data[1]) ){
 				return false;
 			}else{
 				return data;
 			}
 	    }
 	    return false;
 	}

 	$.threeDArrayToString = function(array1){
 	 	// [90,0] => '90,0'
 	 	if(typeof array1 !== 'undefined' && array1.length === 2 && jQuery.isNumeric(array1[0]) && jQuery.isNumeric(array1[1]) && jQuery.threeDCheckDegree(array1[0]) && jQuery.threeDCheckDegree(array1[1])){
 			var data = array1[0]+','+array1[1];
 			return data;
 	    }
 	    return false;
 	}

 	$.threeDCheckDegree = function(degree){
 		//check that its in the right range #NO number over 359 and under -359 please
 		if(degree > -360 && degree < 360){return true;}else{ return false;}
 	}

 	$.threeDAdd = function(face,element,value){
	var face_add = '0,0~'; // Front of box
	var obj = new Object();

	 	if(typeof face !== 'undefined'){
	 		// if you just pass a number as face
	 		if(jQuery.isNumeric(face) && face <= 6 && face >= 1){

	 			switch(face){
	 			case 2: //left of box
	 			face_add = '90,0~';
	 			break;
	 			case 3: //back of box
	 			face_add = '180,0~';
	 			break;
	 			case 4: //right of box
	 			face_add = '270,0~';
	 			break;
	 			case 5: //top of box
	 			face_add = '0,90~';
	 			break;
	 			case 6: //bottom of box
	 			face_add = '0,270~';
	 			break;
	 			default: //front of box
	 			//"0,0~data":"data"
	 			}

	 		}else{
			// Pass a string or Array as face
	 		//check if its array with two elements (Future)

	 			if(jQuery.isArray(face)){
	 				var array_to_string = $.threeDArrayToString(face);
	 				if(array_to_string){
	 					face_add =  array_to_string +'~';
	 				}
	 			}else{
	 				face_add = face+'~';
	 			}
	 		}
	 	}
	 threeDJson[face_add+element] = value;
	 return threeDJson;
 	}

 	$.threeDInside = function(noInside){
 		//paper documents have a back side. In 3dJson to denote its on back side or Inside the box or sphere use negative
 		// Ex."-90,0~data":"data"  => face 2, inside of box or sphere
 		// ZERO problem you can not have -0 or negative zero ...  Thinking about the best way to solve this.
 		// I want face 1 or "0,0~data":"data" to have a back side

 	}

}( jQuery ));
<commit_msg>Update threeDJson.jquery.js<commit_after>(function($){
	 //focusing on box first will do sphere later

	var threeDJson = new Object();

 	$.threeDLoad = function(obj){
 		//Load a JS object or JSON String to begin.
		if(typeof obj === 'object'){
			threeDJson = obj;
		}else{
			try {
     			var jsonObject = jQuery.parseJSON(obj);
			} catch (e) {
    			return false;
			}
		  	threeDJson = jsonObject;
		  	return true;
		}
 	}
 	$.threeDShow = function(remove){
 		//I show the whole JSON with & without Prefex.
	 	if(typeof remove === 'undefined' || remove === false){ return threeDJson; }
	 	if(remove === true){ return jQuery.threeDRemove(); }else{ return threeDJson;}
 	}

 	$.threeDSplit = function(string){
 		//interna function to split prefex if you passed a string instead of Array
 		var data = string.split('~');
    	return data[1];
 	}

 	$.threeDRemove = function(){
 		//goes through JSON and removes 3DJSON prefex EX."-190,0~element":"data" => "element":"data"
 		//You can add decimal numbers up to 4th point  EX. 1.1234
 		return jQuery.parseJSON(JSON.stringify(threeDJson).replace(/["]-?[\d+.]{1,8}[\/,][\d+.]{1,8}[\/~]/g ,'"'));
 	}

 	$.threeDStringToArray = function(string){
 		//  '90,0' => [90,0]
 	 	if(typeof string !== 'undefined'){
 			//assumes it a string of '90,0'
 			var data = string.split('~');
 			if(data.length !== 2 || !jQuery.isNumeric(data[0]) || !jQuery.isNumeric(data[1]) ){
 				return false;
 			}else{
 				return data;
 			}
 	    }
 	    return false;
 	}

 	$.threeDArrayToString = function(array1){
 	 	// [90,0] => '90,0'
 	 	if(typeof array1 !== 'undefined' && array1.length === 2 && jQuery.isNumeric(array1[0]) && jQuery.isNumeric(array1[1]) && jQuery.threeDCheckDegree(array1[0]) && jQuery.threeDCheckDegree(array1[1])){
 			var data = array1[0]+','+array1[1];
 			return data;
 	    }
 	    return false;
 	}

 	$.threeDCheckDegree = function(degree){
 		//check that its in the right range #NO number over 359 and under -359 please
 		if(degree > -360 && degree < 360){return true;}else{ return false;}
 	}

 	$.threeDAdd = function(face,element,value){
	var face_add = '0,0~'; // Front of box
	var obj = new Object();

	 	if(typeof face !== 'undefined'){
	 		// if you just pass a number as face
	 		if(jQuery.isNumeric(face) && face <= 6 && face >= 1){

	 			switch(face){
	 			case 2: //left of box
	 			face_add = '90,0~';
	 			break;
	 			case 3: //back of box
	 			face_add = '180,0~';
	 			break;
	 			case 4: //right of box
	 			face_add = '270,0~';
	 			break;
	 			case 5: //top of box
	 			face_add = '0,90~';
	 			break;
	 			case 6: //bottom of box
	 			face_add = '0,270~';
	 			break;
	 			default: //front of box
	 			//"0,0~data":"data"
	 			}

	 		}else{
			// Pass a string or Array as face
	 		//check if its array with two elements (Future)

	 			if(jQuery.isArray(face)){
	 				var array_to_string = $.threeDArrayToString(face);
	 				if(array_to_string){
	 					face_add =  array_to_string +'~';
	 				}
	 			}else{
	 				face_add = face+'~';
	 			}
	 		}
	 	}
	 threeDJson[face_add+element] = value;
	 return threeDJson;
 	}

 	$.threeDInside = function(noInside){
 		//paper documents have a back side. In 3dJson to denote its on back side or Inside the box or sphere use negative
 		// Ex."-90,0~data":"data"  => face 2, inside of box or sphere
 		// ZERO problem you can not have -0 or negative zero ...  Thinking about the best way to solve this.
 		// I want face 1 or "0,0~data":"data" to have a back side

 	}

}( jQuery ));
<|endoftext|>


<commit_before>import Request from './sessionSuperagent.js';
import Q from 'q';
import { dispatch } from 'redux';
import _ from 'lodash';
import { kGlobalConstants } from '../GlobalConstants.js';

export const loadActivity = () => {
	const deferred = Q.defer();

     Request.get(kGlobalConstants.API + 'list_submissions/?filter_by=agency')
            .send()
            .end((err, res) => {

                if (err) {
                    deferred.reject(err);
                }
                else {
                    deferred.resolve(res.body.recent);
                }
            });

    return deferred.promise;
}<commit_msg>Name of API response key changed<commit_after>import Request from './sessionSuperagent.js';
import Q from 'q';
import { dispatch } from 'redux';
import _ from 'lodash';
import { kGlobalConstants } from '../GlobalConstants.js';

export const loadActivity = () => {
	const deferred = Q.defer();

     Request.get(kGlobalConstants.API + 'list_submissions/?filter_by=agency')
            .send()
            .end((err, res) => {

                if (err) {
                    deferred.reject(err);
                }
                else {
                    deferred.resolve(res.body.submissions);
                }
            });

    return deferred.promise;
}<|endoftext|>


<commit_before>(function(W, Hooray) {
    "use strict";

    Hooray.defineClass('Billiard', '', 'Ball', {
        init: function(id, initX, initY, radius, mass) {
            Hooray.log('A new Billiard.Ball instance has been created with id "'+id+'"!');
            this.id     = id;
            this.initX  = initX;
            this.initY  = initY;
            this.radius = radius;
            this.mass   = mass;

            this.vX     = 3;
            this.vY     = 3;

            this.rotationHelper = Billiard.Helper.RotationHelper;

            this.coordsRotationHelper = Billiard.Helper.CoordsRotationHelper;

            /*this.collisionHelper = {
                ball0Center: new THREE.Vector2(0, 0),
                ball1Center: new THREE.Vector2(0, 0),
                v0: new THREE.Vector2(0, 0),
                v1: new THREE.Vector2(0, 0),
                n: new THREE.Vector2(0, 0),
                tmp: new THREE.Vector2(0, 0)

            };*/

            // !!! A Billiard.Ball object will be augmented with a mesh property during initialization !!!
        },

        translate: function() {
            this.mesh.position.x += this.vX;
            this.mesh.position.y += this.vY;
        },

        rotate: function() {
            this.rotationHelper.rotateAroundWorldAxisX(this.mesh, -this.vY / this.radius);
            this.rotationHelper.rotateAroundWorldAxisY(this.mesh, this.vX / this.radius);
        },

        handleCushionCollision: function(table) {
            var m = this.mesh,
                r = this.radius,
                halfWidth  = table.getPlayingFieldWidth()  / 2,
                halfHeight = table.getPlayingFieldHeight() / 2;

            if (m.position.x+r > halfWidth) {
                m.position.x = halfWidth - r;
                this.vX *= -1;
            }
            else if (m.position.x-r < -halfWidth) {
                m.position.x = -halfWidth + r;
                this.vX *= -1;
            }

            if (m.position.y+r > halfHeight) {
                m.position.y = halfHeight - r;
                this.vY *= -1;
            }
            else if (m.position.y-r < -halfHeight) {
                m.position.y = -halfHeight + r;
                this.vY *= -1;
            }
        },

        handleBallCollision: function(anotherBall) {
            var ball0 = this.mesh.position,
                ball1 = anotherBall.mesh.position;

            var dx = ball1.x - ball0.x,
                dy = ball1.y - ball0.y,
                dist = Math.sqrt(dx * dx + dy * dy);

            // check for collision based on radius
            if (dist < this.radius + anotherBall.radius) {

                /*

                THIS COLLISION HANDLING IS QUITE GOOD BUT BALLS BECOME STUCK!!!

                var angle = Math.atan2(dy, dx),
                    sin = Math.sin(angle),
                    cos = Math.cos(angle),
                    e = 1;

                // rotate velocity vectors
                var ball0vXr = this.vX * cos + this.vY * sin;
                var ball0vYr = -this.vX * sin + this.vY * cos;

                var ball1vXr = anotherBall.vX * cos + anotherBall.vY * sin;
                var ball1vYr = -anotherBall.vX * sin + anotherBall.vY * cos;

                // rotate orientation of line of action
                // and consider ball0 (pos0) as the reference
                var pos0 = {x: 0, y: 0};
                var pos1 = {
                    x: dx * cos + dy * sin,
                    y: -dx * sin + dy * cos
                };

                // apply conservation of momentum
                var tmp = 1 / (this.mass + anotherBall.mass);
                var newVxBall0 = (this.mass - e * anotherBall.mass) * ball0vXr * tmp
                                    + (1 + e) * anotherBall.mass * ball1vXr * tmp;

                var newVxBall1 = (1 + e) * this.mass * ball0vXr * tmp
                                    + (anotherBall.mass - e * this.mass) * ball1vXr * tmp;

                // update position to avoid objects becoming stuck together
                var absV = Math.abs(ball0vXr) + Math.abs(ball1vXr),
                    overlap = (this.radius + anotherBall.radius) - Math.abs(pos0.x - pos1.x);
                pos0.x += ball0vXr.x / absV * overlap;
                pos1.x += ball1vXr.x / absV * overlap;

                // rotate positions back
                var pos0F = {
                        x: pos0.x * cos - pos0.y * sin,
                        y: pos0.x * sin + pos0.y * cos
                    },
                    pos1F = {
                        x: pos1.x * cos - pos1.y * sin,
                        y: pos1.x * sin + pos1.y * cos
                    };

                // rotate velocity vectors back
                this.vX = newVxBall0 * cos - ball0vYr * sin;
                this.vY = newVxBall0 * sin + ball0vYr * cos;

                anotherBall.vX = newVxBall1 * cos - ball1vYr * sin;
                anotherBall.vY = newVxBall1 * sin + ball1vYr * cos;
                */

                var crh = this.coordsRotationHelper;

                // calculate angle, sine, and cosine
                var angle = Math.atan2(dy, dx),
                    sin = Math.sin(angle),
                    cos = Math.cos(angle),
                    e = 1,
                // rotate ball0's position
                    pos0 = {x: 0, y: 0}, //point
                // rotate ball1's position
                    pos1 = crh.rotateCoords(dx, dy, sin, cos, true),
                // rotate ball0's velocity
                    vel0 = crh.rotateCoords(this.vX, this.vY, sin, cos, true),
                // rotate ball1's velocity
                    vel1 = crh.rotateCoords(anotherBall.vX, anotherBall.vY, sin, cos, true);

                // apply conservation of momentum
                var tmp = 1 / (this.mass + anotherBall.mass);
                var newVxBall0 = (this.mass - e * anotherBall.mass) * vel0.x * tmp
                                    + (1 + e) * anotherBall.mass * vel1.x * tmp;

                var newVxBall1 = (1 + e) * this.mass * vel0.x * tmp
                                    + (anotherBall.mass - e * this.mass) * vel1.x * tmp;

                // update position to avoid objects becoming stuck together
                var absV = Math.abs(newVxBall0) + Math.abs(newVxBall1),
                    overlap = (this.radius + anotherBall.radius) - Math.abs(pos0.x - pos1.x);
                pos0.x += newVxBall0 / absV * overlap;
                pos1.x += newVxBall1 / absV * overlap;

                // rotate positions back
                var pos0F = crh.rotateCoords(pos0.x, pos0.y, sin, cos, false),
                    pos1F = crh.rotateCoords(pos1.x, pos1.y, sin, cos, false);

                // adjust positions to actual screen positions
                ball1.x = ball0.x + pos1F.x;
                ball1.y = ball0.y + pos1F.y;
                ball0.x = ball0.x + pos0F.x;
                ball0.y = ball0.y + pos0F.y;

                // rotate velocities back
                var vel0F = crh.rotateCoords(newVxBall0, vel0.y, sin, cos, false),
                    vel1F = crh.rotateCoords(newVxBall1, vel1.y, sin, cos, false);

                this.vX = vel0F.x;
                this.vY = vel0F.y;
                anotherBall.vX = vel1F.x;
                anotherBall.vY = vel1F.y;
            }
        }
    });

})(window, Hooray);
<commit_msg>remove obsolete uncommented portions of old collision response algorithm<commit_after>(function(W, Hooray) {
    "use strict";

    Hooray.defineClass('Billiard', '', 'Ball', {
        init: function(id, initX, initY, radius, mass) {
            Hooray.log('A new Billiard.Ball instance has been created with id "'+id+'"!');
            this.id     = id;
            this.initX  = initX;
            this.initY  = initY;
            this.radius = radius;
            this.mass   = mass;

            this.vX     = 3;
            this.vY     = 3;

            this.rotationHelper = Billiard.Helper.RotationHelper;
            this.coordsRotationHelper = Billiard.Helper.CoordsRotationHelper;

            // !!! A Billiard.Ball object will be augmented with a mesh property during initialization !!!
        },

        translate: function() {
            this.mesh.position.x += this.vX;
            this.mesh.position.y += this.vY;
        },

        rotate: function() {
            this.rotationHelper.rotateAroundWorldAxisX(this.mesh, -this.vY / this.radius);
            this.rotationHelper.rotateAroundWorldAxisY(this.mesh, this.vX / this.radius);
        },

        handleCushionCollision: function(table) {
            var m = this.mesh,
                r = this.radius,
                halfWidth  = table.getPlayingFieldWidth()  / 2,
                halfHeight = table.getPlayingFieldHeight() / 2;

            if (m.position.x+r > halfWidth) {
                m.position.x = halfWidth - r;
                this.vX *= -1;
            }
            else if (m.position.x-r < -halfWidth) {
                m.position.x = -halfWidth + r;
                this.vX *= -1;
            }

            if (m.position.y+r > halfHeight) {
                m.position.y = halfHeight - r;
                this.vY *= -1;
            }
            else if (m.position.y-r < -halfHeight) {
                m.position.y = -halfHeight + r;
                this.vY *= -1;
            }
        },

        handleBallCollision: function(anotherBall) {
            var ball0 = this.mesh.position,
                ball1 = anotherBall.mesh.position;

            var dx = ball1.x - ball0.x,
                dy = ball1.y - ball0.y,
                dist = Math.sqrt(dx * dx + dy * dy);

            // check for collision based on radius
            if (dist < this.radius + anotherBall.radius) {
                var crh = this.coordsRotationHelper;

                // calculate angle, sine, and cosine
                var angle = Math.atan2(dy, dx),
                    sin = Math.sin(angle),
                    cos = Math.cos(angle),
                    e = 1,
                // rotate ball0's position
                    pos0 = {x: 0, y: 0}, //point
                // rotate ball1's position
                    pos1 = crh.rotateCoords(dx, dy, sin, cos, true),
                // rotate ball0's velocity
                    vel0 = crh.rotateCoords(this.vX, this.vY, sin, cos, true),
                // rotate ball1's velocity
                    vel1 = crh.rotateCoords(anotherBall.vX, anotherBall.vY, sin, cos, true);

                // apply conservation of momentum
                var tmp = 1 / (this.mass + anotherBall.mass);
                var newVxBall0 = (this.mass - e * anotherBall.mass) * vel0.x * tmp
                                    + (1 + e) * anotherBall.mass * vel1.x * tmp;

                var newVxBall1 = (1 + e) * this.mass * vel0.x * tmp
                                    + (anotherBall.mass - e * this.mass) * vel1.x * tmp;

                // update position to avoid that objects become stuck together
                var absV = Math.abs(newVxBall0) + Math.abs(newVxBall1),
                    overlap = (this.radius + anotherBall.radius) - Math.abs(pos0.x - pos1.x);
                pos0.x += newVxBall0 / absV * overlap;
                pos1.x += newVxBall1 / absV * overlap;

                // rotate positions back
                var pos0F = crh.rotateCoords(pos0.x, pos0.y, sin, cos, false),
                    pos1F = crh.rotateCoords(pos1.x, pos1.y, sin, cos, false);

                // adjust positions to actual screen positions
                ball1.x = ball0.x + pos1F.x;
                ball1.y = ball0.y + pos1F.y;
                ball0.x = ball0.x + pos0F.x;
                ball0.y = ball0.y + pos0F.y;

                // rotate velocities back
                var vel0F = crh.rotateCoords(newVxBall0, vel0.y, sin, cos, false),
                    vel1F = crh.rotateCoords(newVxBall1, vel1.y, sin, cos, false);

                this.vX = vel0F.x;
                this.vY = vel0F.y;
                anotherBall.vX = vel1F.x;
                anotherBall.vY = vel1F.y;
            }
        }
    });

})(window, Hooray);
<|endoftext|>


<commit_before>/*
 * Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
 * http://paperjs.org/
 *
 * Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

module('Item Contains');

function testPoint(item, point, inside) {
	equals(item.contains(point), inside, 'The point ' + point
			+ ' should be ' + (inside ? 'inside' : 'outside') + '.');
}

test('Path#contains (Regular Polygon)', function() {
	var path = new Path.RegularPolygon([0, 0], 6, 20);

	testPoint(path, new Point(0, -20), true);
	testPoint(path, new Point(0, -10), true);
	testPoint(path, new Point(0, 0), true);
	testPoint(path, new Point(0, 10), true);
	testPoint(path, new Point(0, 20), true);

	testPoint(path, new Point(-10, -20), false);
	testPoint(path, new Point(-10, -10), true);
	testPoint(path, new Point(-10, 0), true);
	testPoint(path, new Point(-10, 10), true);
	testPoint(path, new Point(-10, 20), false);

	testPoint(path, new Point(10, -20), false);
	testPoint(path, new Point(10, -10), true);
	testPoint(path, new Point(10, 0), true);
	testPoint(path, new Point(10, 10), true);
	testPoint(path, new Point(10, 20), false);
});

test('CompoundPath#contains (Donut)', function() {
	var path = new CompoundPath([
		new Path.Circle([0, 0], 50),
		new Path.Circle([0, 0], 25)
	]);

	equals(path.contains(new Point(0, 0)), false,
		'The center point should be outside the donut.');
	equals(path.contains(new Point(-35, 0)), true,
		'A vertically centered point on the left side should be inside the donut.');
	equals(path.contains(new Point(35, 0)), true,
		'A vertically centered point on the right side should be inside the donut.');
	equals(path.contains(new Point(0, 49)), true,
		'The near bottom center point of the outer circle should be inside the donut.');
	equals(path.contains(new Point(0, 50)), true,
		'The bottom center point of the outer circle should be inside the donut.');
	equals(path.contains(new Point(0, 51)), false,
		'The near bottom center point of the outer circle should be outside the donut.');
	equals(path.contains(new Point({ length: 50, angle: 30 })), true,
		'A random point on the periphery of the outer circle should be inside the donut.');
	equals(path.contains(new Point(0, 25)), false,
		'The bottom center point of the inner circle should be outside the donut.');
	equals(path.contains(new Point({ length: 25, angle: 30 })), false,
		'A random point on the periphery of the inner circle should be outside the donut.');
	equals(path.contains(new Point(-50, -50)), false,
		'The top left point of bounding box should be outside the donut.');
	equals(path.contains(new Point(-50, 50)), false,
		'The bottom left point of bounding box should be outside the donut.');
	equals(path.contains(new Point(-45, 45)), false,
		'The near bottom left point of bounding box should be outside the donut.');
});

test('Shape#contains', function() {
	var shape = new Shape.Circle([0, 0], 100);

	testPoint(shape, new Point(0, 0), true);
	testPoint(shape, new Point(0, -100), true);
	testPoint(shape, new Point({ length: 99, angle: 45 }), true);
	testPoint(shape, new Point({ length: 100, angle: 45 }), true);
	testPoint(shape, new Point({ length: 101, angle: 45 }), false);
});<commit_msg>Define more unit tests for Shape#contains().<commit_after>/*
 * Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
 * http://paperjs.org/
 *
 * Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

module('Item Contains');

function testPoint(item, point, inside) {
	equals(item.contains(point), inside, 'The point ' + point
			+ ' should be ' + (inside ? 'inside' : 'outside') + '.');
}

test('Path#contains (Regular Polygon)', function() {
	var path = new Path.RegularPolygon([0, 0], 6, 20);

	testPoint(path, new Point(0, -20), true);
	testPoint(path, new Point(0, -10), true);
	testPoint(path, new Point(0, 0), true);
	testPoint(path, new Point(0, 10), true);
	testPoint(path, new Point(0, 20), true);

	testPoint(path, new Point(-10, -20), false);
	testPoint(path, new Point(-10, -10), true);
	testPoint(path, new Point(-10, 0), true);
	testPoint(path, new Point(-10, 10), true);
	testPoint(path, new Point(-10, 20), false);

	testPoint(path, new Point(10, -20), false);
	testPoint(path, new Point(10, -10), true);
	testPoint(path, new Point(10, 0), true);
	testPoint(path, new Point(10, 10), true);
	testPoint(path, new Point(10, 20), false);
});

test('CompoundPath#contains (Donut)', function() {
	var path = new CompoundPath([
		new Path.Circle([0, 0], 50),
		new Path.Circle([0, 0], 25)
	]);

	equals(path.contains(new Point(0, 0)), false,
		'The center point should be outside the donut.');
	equals(path.contains(new Point(-35, 0)), true,
		'A vertically centered point on the left side should be inside the donut.');
	equals(path.contains(new Point(35, 0)), true,
		'A vertically centered point on the right side should be inside the donut.');
	equals(path.contains(new Point(0, 49)), true,
		'The near bottom center point of the outer circle should be inside the donut.');
	equals(path.contains(new Point(0, 50)), true,
		'The bottom center point of the outer circle should be inside the donut.');
	equals(path.contains(new Point(0, 51)), false,
		'The near bottom center point of the outer circle should be outside the donut.');
	equals(path.contains(new Point({ length: 50, angle: 30 })), true,
		'A random point on the periphery of the outer circle should be inside the donut.');
	equals(path.contains(new Point(0, 25)), false,
		'The bottom center point of the inner circle should be outside the donut.');
	equals(path.contains(new Point({ length: 25, angle: 30 })), false,
		'A random point on the periphery of the inner circle should be outside the donut.');
	equals(path.contains(new Point(-50, -50)), false,
		'The top left point of bounding box should be outside the donut.');
	equals(path.contains(new Point(-50, 50)), false,
		'The bottom left point of bounding box should be outside the donut.');
	equals(path.contains(new Point(-45, 45)), false,
		'The near bottom left point of bounding box should be outside the donut.');
});

test('Shape#contains', function() {
	var shape = new Shape.Circle([0, 0], 100);

	testPoint(shape, new Point(0, 0), true);
	testPoint(shape, new Point(0, -100), true);
	testPoint(shape, new Point({ length: 99, angle: 45 }), true);
	testPoint(shape, new Point({ length: 100, angle: 45 }), true);
	testPoint(shape, new Point({ length: 101, angle: 45 }), false);

	var size = new Size(100, 200),
		half = size.divide(2),
		shape = new Shape.Ellipse(half.negate(), size);
	testPoint(shape, new Point(0, 0), true);
	testPoint(shape, new Point(0, -1).multiply(half), true);
	testPoint(shape, new Point({ length: 0.9, angle: 45 }).multiply(half), true);
	testPoint(shape, new Point({ length: 1, angle: 45 }).multiply(half), true);
	testPoint(shape, new Point({ length: 1.1, angle: 45 }).multiply(half), false);

	var size = new Size(100, 200),
		half = size.divide(2),
		shape = new Shape.Rectangle(half.negate(), size);
	testPoint(shape, new Point(0, 0), true);
	testPoint(shape, new Point(0, 0.9).multiply(half), true);
	testPoint(shape, new Point(0, 1).multiply(half), true);
	testPoint(shape, new Point(0, 1.1).multiply(half), false);
	testPoint(shape, new Point(0.9, 0).multiply(half), true);
	testPoint(shape, new Point(1, 0).multiply(half), true);
	testPoint(shape, new Point(1.1, 0).multiply(half), false);
});
<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var log = require('debug')('broadcast:db-api');

var Team = mongoose.model('Team');
var User = mongoose.model('User');

var async = require('async');

/**
 * Get all teams
 */
exports.allTeams = function allTeams (fn) {
  Team
  .find()
  .exec(function (err, teams) {
    if (err) return log(err), fn(err);

    if (!teams) return log('No teams found – returning null'), fn(null);

    return log('Found teams %s', teams.map(t => t.id)), fn(null, teams);
  });
}

/**
 * Add's `sender` to `reciever`'s accepts if `accepts`, else removes
 */
exports.modifyAccepts = function modifyAccepts (recieverDomain, senderDomain, accepts, fn) {
  Team
  .findOne({domain: recieverDomain})
  .exec(function (err, reciever) {
    if (err) return log(err), fn(err);

    Team
    .findOne({domain: senderDomain})
    .exec(function (err, sender) {
      if (err) return log(err), fn(err);

      if (accepts) {
        // add sender to reciever's accepts
        reciever.accepts.push(sender.id);
      } else {
        // if reciever currently accepts sender, remove sender from reciever's accepts
        if (reicever.accepts.indexOf(sender.id) > -1) {
          reciever.accepts.splice(sender.accepts.indexOf(sender.id), 1);
        }
      }

      reciever.save(function (err) {
        if (err) return log(err), fn(err);

        log('Successfully %s %s to %s\'s accepts', accepts ? 'added' : 'removed', senderDomain, recieverDomain);
        return fn(null, reciever);
      });
    });
  });
}

/**
 * Add a new team with data in `team`
 */
exports.addTeam = function addTeam (team, fn) {
  team.accepts = [];

  exports.allTeams(function (err, teams) {
    if (err) return log(err), fn(err);

    teams.forEach(t => {
      team.accepts.push(t.id);
    });

    var newTeam = new Team(team);

    newTeam.save(function (err) {
      if (err) return log(err), fn(err);

      async.parallel( teams.map(t => modifyAccepts(t.domain, newTeam.domain, true) ), function (err, teams) {
        if (err) return log(err), fn(err);

        return fn(null, newTeam);
      });
    });
  });

}

/**
 * Get the teams that `outTeam` is allowed to send messages to
 */
exports.teamsFor = function (outTeamDomain, fn) {
  exports.allTeams(function (err, teams) {
    if (err) return fn(err);

    var outTeam = teams.filter(function (t) {
      return t.domain == outTeamDomain;
    })[0];

    if (outTeam) var outTeamId = outTeam.id;

    var teamsFor = teams.filter(function (t) {
      return t.accepts.indexOf(outTeamId) > -1;
    });

    log('%s is allowed to send to %s', outTeam, teamsFor);
    return fn(null, teamsFor);
  });
}

/**
 * Get a particular user
 */
exports.getUser = function getUser (username, fn) {
  User
  .findOne({username: username})
  .exec(function (err, user) {
    if (err) return log(err), fn(err);

    if (!user) return log('User with username %s not found', username), fn(null);

    return fn(null, user);
  });
}

/**
 * Get a particular user, creating one if it doesn't exist
 */
exports.ensureUser = function ensureUser (username, fn) {
  exports.getUser(function (err, user) {
    if (err) return log(err), fn(err);

    if (!user) {
      log('User with username %s not found, creating one...', username);
      var newUser = new User({username: username});
      newUser.save(function (err) {
        if (err) return log(err), fn(err);

        fn(null, newUser);
      });
    }

    return fn(null, user);
  });
}

/**
 * Makes user with username admin
 */
exports.makeUserAdmin = function (username, fn) {
  exports.ensureUser(username, function (err, user) {
    if (err) return fn(err); if (!user) fn(null);

    user.admin = true;
    user.save(function (err, user) {
      if (err) return log(err), fn(err);

      return log('Make %s admin', username), fn(null, user);
    });
  });
}

/**
 * Ban a particular user
 */
exports.modifySend = function (username, canSend, fn) {
  exports.ensureUser(username, function (err, user) {
    if (err) return fn(err); if (!user) fn(null);

    user.send = canSend;
    user.save(function (err, user) {
      if (err) return log(err), fn(err);

      return log('Make user %s\'s send privileges = %s', username, canSend), fn(null, user);
    });
  });
}

<commit_msg>modifying new team to include itself as an accept<commit_after>var mongoose = require('mongoose');
var log = require('debug')('broadcast:db-api');

var Team = mongoose.model('Team');
var User = mongoose.model('User');

var async = require('async');

/**
 * Get all teams
 */
exports.allTeams = function allTeams (fn) {
  Team
  .find()
  .exec(function (err, teams) {
    if (err) return log(err), fn(err);

    if (!teams) return log('No teams found – returning null'), fn(null);

    return log('Found teams %s', teams.map(t => t.id)), fn(null, teams);
  });
}

/**
 * Add's `sender` to `reciever`'s accepts if `accepts`, else removes
 */
exports.modifyAccepts = function modifyAccepts (recieverDomain, senderDomain, accepts, fn) {
  Team
  .findOne({domain: recieverDomain})
  .exec(function (err, reciever) {
    if (err) return log(err), fn(err);

    Team
    .findOne({domain: senderDomain})
    .exec(function (err, sender) {
      if (err) return log(err), fn(err);

      if (accepts) {
        // add sender to reciever's accepts
        reciever.accepts.push(sender.id);
      } else {
        // if reciever currently accepts sender, remove sender from reciever's accepts
        if (reicever.accepts.indexOf(sender.id) > -1) {
          reciever.accepts.splice(sender.accepts.indexOf(sender.id), 1);
        }
      }

      reciever.save(function (err) {
        if (err) return log(err), fn(err);

        log('Successfully %s %s to %s\'s accepts', accepts ? 'added' : 'removed', senderDomain, recieverDomain);
        return fn(null, reciever);
      });
    });
  });
}

/**
 * Add a new team with data in `team`
 */
exports.addTeam = function addTeam (team, fn) {
  team.accepts = [];

  exports.allTeams(function (err, teams) {
    if (err) return log(err), fn(err);

    teams.forEach(t => {
      team.accepts.push(t.id);
    });

    var newTeam = new Team(team);

    newTeam.save(function (err) {
      if (err) return log(err), fn(err);

      exports.allTeams(function (err, teams) {
        async.parallel( teams.map(t => modifyAccepts(t.domain, newTeam.domain, true) ), function (err, teams) {
          if (err) return log(err), fn(err);

          return fn(null, newTeam);
        });
      });

    });
  });

}

/**
 * Get the teams that `outTeam` is allowed to send messages to
 */
exports.teamsFor = function (outTeamDomain, fn) {
  exports.allTeams(function (err, teams) {
    if (err) return fn(err);

    var outTeam = teams.filter(function (t) {
      return t.domain == outTeamDomain;
    })[0];

    if (outTeam) var outTeamId = outTeam.id;

    var teamsFor = teams.filter(function (t) {
      return t.accepts.indexOf(outTeamId) > -1;
    });

    log('%s is allowed to send to %s', outTeam, teamsFor);
    return fn(null, teamsFor);
  });
}

/**
 * Get a particular user
 */
exports.getUser = function getUser (username, fn) {
  User
  .findOne({username: username})
  .exec(function (err, user) {
    if (err) return log(err), fn(err);

    if (!user) return log('User with username %s not found', username), fn(null);

    return fn(null, user);
  });
}

/**
 * Get a particular user, creating one if it doesn't exist
 */
exports.ensureUser = function ensureUser (username, fn) {
  exports.getUser(function (err, user) {
    if (err) return log(err), fn(err);

    if (!user) {
      log('User with username %s not found, creating one...', username);
      var newUser = new User({username: username});
      newUser.save(function (err) {
        if (err) return log(err), fn(err);

        fn(null, newUser);
      });
    }

    return fn(null, user);
  });
}

/**
 * Makes user with username admin
 */
exports.makeUserAdmin = function (username, fn) {
  exports.ensureUser(username, function (err, user) {
    if (err) return fn(err); if (!user) fn(null);

    user.admin = true;
    user.save(function (err, user) {
      if (err) return log(err), fn(err);

      return log('Make %s admin', username), fn(null, user);
    });
  });
}

/**
 * Ban a particular user
 */
exports.modifySend = function (username, canSend, fn) {
  exports.ensureUser(username, function (err, user) {
    if (err) return fn(err); if (!user) fn(null);

    user.send = canSend;
    user.save(function (err, user) {
      if (err) return log(err), fn(err);

      return log('Make user %s\'s send privileges = %s', username, canSend), fn(null, user);
    });
  });
}

<|endoftext|>


<commit_before>var addEvent = (function ()
{
    if (document.addEventListener)
    {
        return function (el, type, fn)
        {
            if (el && el.nodeName || el === window)
            {
                el.addEventListener(type, fn, false);
            }
            else if (el && el.length)
            {
                for (var i = 0; i < el.length; i++)
                {
                    addEvent(el[i], type, fn);
                }
            }
        };
    }
    else
    {
        return function (el, type, fn) {
            if (el && el.nodeName || el === window)
            {
                el.attachEvent('on' + type, function () { return fn.call(el, window.event); });
            }
            else if (el && el.length)
            {
                for (var i = 0; i < el.length; i++)
                {
                    addEvent(el[i], type, fn);
                }
            }
        };
    }
})();

Object.prototype.merge = function(newObject)
{
    for (var item in newObject)
    {
        if(newObject[item].constructor==Object)
        {
            this[item].merge(newObject[item]);
        }
        else
        {
            this[item] = newObject[item];
        }
    }
    return this;
};
/*Object.prototype.mergeRecursive(obj1, obj2) {

  for (var p in obj2) {
    try {
      // Property in destination object set; update its value.
      if ( obj2[p].constructor==Object ) {
        obj1[p] = MergeRecursive(obj1[p], obj2[p]);

      } else {
        obj1[p] = obj2[p];

      }

    } catch(e) {
      // Property in destination object not set; create it and set its value.
      obj1[p] = obj2[p];

    }
  }

  return obj1;
}*/
(function(_w){

    var defaultSetting = {
        element : document,
        debug: false
    };

    var uploadZoneElement = {
            tag: 'div',
                attr:{
                id:'ajax-upload',
                class:"default hide"
            },
            content:{
                tag:'div',
                attr:{
                    id:'ajax-upload-marco'
                },
                content:{
                    tag:'center',
                    content:'Suelte Aquí para comenzar a subir'
                }
            }
    };

    var FileUpload = function(file)
    {
        this.file = file;
        return this;
    }
    FileUpload.prototype.bytesMegas = function()
    {
        return Math.round((this.file.size/1024)*100)/100;
    };
    FileUpload.prototype.fileExtencion = function()
    {
        return this.file.name.split(".").pop();
    };
    FileUpload.prototype.fileInfo = function()
    {
        return {
            name : this.file.name,
            size : this.bytesMegas(this.file.size)+"Mb",
            type : this.file.type,
            extn : this.fileExtencion(this.file.name),
            last : this.file.lastModifiedDate.toLocaleDateString()
        };
    };

    var Element = function(objElem)
    {
        this.objElem = objElem;
        this.element = null;
        if(!!objElem.tag)
        {
            this.element = document.createElement(objElem.tag);
            this
                .attr()
                .content()
            ;
        }
        return this.element;
    };
    Element.prototype.attr = function()
    {
        if (!!this.objElem.attr)
        {
            for(var item in this.objElem.attr)
            {
                if (typeof(this.objElem.attr[item])=='string')
                {
                    this.element.setAttribute(item,this.objElem.attr[item]);
                }
            }
        }
        return this;
    };
    Element.prototype.content = function()
    {
        if (!!this.objElem.content)
        {
            this.objElem.content
            switch(typeof(this.objElem.content))
            {
                case "string":
                    this.element.innerHTML=this.objElem.content
                    break;
                case "object":
                    var elem  = new Element(this.objElem.content);
                    this.element.appendChild(elem);
                    break;
            }
        }
        return this;
    };

    var AjaxUpload = function(settings)
    {
        var ajaxupload = false;

        if(!!this.validateBrowser())
        {
            this.settings = typeof(settings)=="object"?defaultSetting.merge(settings):defaultSetting;
            this.parent = this.getParent();
            this.uploadzone = this.getUploadZone();
        }

        return ajaxupload;

        // var paarent =            var elem = elem || document;
        // var cont = App.nElem('contenedor');
        // var mrco = App.nElem('marco');

    };

    AjaxUpload.prototype.validateBrowser = function()
    {
        var isValid = _w.File && _w.FileList && _w.FileReader;
        if(!isValid && !!this.settings.debug)
        {
            console.log("Este navegador no soporta el API")
        }
        return isValid;
    };

    AjaxUpload.prototype.getParent = function()
    {
        var element = this.settings.element;

        if (typeof(element)=='string')
        {
            var element = document.querySelector(element);
        }

        if(element == null && !!this.settings.debug)
        {
            console.log("No se encontro un Objeto Paadre")
        }

        return element;
    };

    AjaxUpload.prototype.getUploadZone = function()
    {
        var uploadzone = new Element(uploadZoneElement);
        console.log(uploadzone)

    };
/*  AjaxUpload.prototype.getElement = function(name)
    {
        var data = this.elementos[name]||null, elem = null;
        if(!!data)
        {
            elem = document.createElement(data[0]);
        }
    }*/

    var App = {
        elementos:{
            contenedor : ['div',{id:'ajax-upload',class:"default hide"}],
            marco:['div',{id:'ajax-upload-marco'},"Suelte Aquí para comenzar a subir"]
        },
        nElem : function (nm){
            var data = App.elementos[nm]||null;
            var elem = null;
            if (!!data){
                elem = document.createElement(data[0]);
                if(!!data[1]){
                    for(var item in data[1]){
                        elem.setAttribute(item,data[1][item]);
                    }
                }
                if(!!data[2]){
                    switch(typeof(data[2])){
                        case "string":
                            elem.innerHTML=data[2]
                        break;
                    }

                }
            }
            return elem;
        },
        stop:function(e){
            if (e.preventDefault) e.preventDefault();
            e.dataTransfer.dropEffect = 'copy';
            return false;
        },
        esXHR2 : function(){
            return !!App.xhr()?App.xhr().upload:false;
        },
        XHR: function(){
            if (_w.XMLHttpRequest){ return new XMLHttpRequest();}
            else if (_w.ActiveXObject)
            {
                try {return  new ActiveXObject("MSXML2.XMLHTTP");}
                catch (e) {
                    try {return  new ActiveXObject("Microsoft.XMLHTTP");}
                    catch (e) {}
                }
            }
            return false;
        },
/*      bytesMegas:function(num){return Math.round((num/1024)*100)/100;},
        fileExtencion:function(nm){ return nm.split(".").pop();},
        fileInfo:function(file){
            return {
                name : file.name,
                size : App.bytesMegas(file.size)+"Mb",
                type : file.type,
                extn : App.fileExtencion(file.name)
            };
        },*/
        classStatus:function(stt){
            var stt        = stt|| false;
            var elem       = document.querySelector('#ajax-upload');
            var classList  = elem.classList;
            elem.classList[!!stt?"add":"remove"]("hide");
            return false;
            //elem.classList[classList.contains('hide')?"remove":"add"]("hide");
        },
        leave:function(e){
            App.stop(e);
            App.classStatus(true);
            return false;
        },
        over: function(e){
            App.stop(e);
            App.classStatus();
            return false;
        },
        hover: function(e) {App.stop(e);App.classStatus();return false;},
        drop:function(e) {
            App.stop(e);App.classStatus(true);
            var files = e.target.files || e.dataTransfer.files;
            App.upload(files);
            return false;

        },
        upload:function(files){
            var files = files || [];
            for($I=0;$I<files.length;$I++){
                var formdata = new FormData();
                var ajax = new App.XHR();
                console.log(App.fileInfo(files[$I]));
                formdata.append("X_FILENAME", files[$I]);
                ajax.upload.addEventListener("progress", function(e){}, false);
                ajax.addEventListener("load", function(e){}, false);
                ajax.addEventListener("error", function(e){}, false);
                ajax.addEventListener("abort", function(e){}, false);
                ajax.open("POST", "file_upload_parser.php");
                ajax.send(formdata);
            }
        },
        init:function(elem){
            var elem = elem || document;
            var cont = App.nElem('contenedor');
            var mrco = App.nElem('marco');
            if(_w.File && _w.FileList && _w.FileReader) {
                elem.addEventListener("dragenter", App.hover, false);
                elem.addEventListener("dragleave", App.leave, false);
                elem.addEventListener("drop", App.drop, false);
                elem.addEventListener("dragover",App.over,false);
                document.body.appendChild(cont);
                cont.appendChild(mrco);
            }

        }

    };

    function progressHandler(event)
    {
        _("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
        var percent = (event.loaded / event.total) * 100; _("progressBar").value = Math.round(percent);
        _("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
    }
    function completeHandler(event)
    {
        _("status").innerHTML = event.target.responseText; _("progressBar").value = 0;
    }
    function errorHandler(event)
    {
        _("status").innerHTML = "Upload Failed";
    }
    function abortHandler(event)
    {
        _("status").innerHTML = "Upload Aborted";
    }

    _w.ajaxUpload = function(settings)
    {
        var ajaxUploadObject = new AjaxUpload(settings);
        //App.init()
    };
})(window);

/*
chrome: 4.0
ie: 8.0
firefox:3.5
safari:3.2
opera:10.o
*/
 <commit_msg>commit de respaldo<commit_after>var addEvent = (function ()
{
    if (document.addEventListener)
    {
        return function (el, type, fn)
        {
            if (el && el.nodeName || el === window)
            {
                el.addEventListener(type, fn, false);
            }
            else if (el && el.length)
            {
                for (var i = 0; i < el.length; i++)
                {
                    addEvent(el[i], type, fn);
                }
            }
        };
    }
    else
    {
        return function (el, type, fn) {
            if (el && el.nodeName || el === window)
            {
                el.attachEvent('on' + type, function () { return fn.call(el, window.event); });
            }
            else if (el && el.length)
            {
                for (var i = 0; i < el.length; i++)
                {
                    addEvent(el[i], type, fn);
                }
            }
        };
    }
})();

Object.prototype.merge = function(newObject)
{
    for (var item in newObject)
    {
        if(newObject[item].constructor==Object)
        {
            this[item].merge(newObject[item]);
        }
        else
        {
            this[item] = newObject[item];
        }
    }
    return this;
};

(function(_w){

    var defaultSetting = {
        element : document,
        debug: false
    };

    var uploadZoneElement = {
            tag: 'div',
                attr:{
                id:'ajax-upload',
                class:"default hide"
            },
            content:{
                tag:'div',
                attr:{
                    id:'ajax-upload-marco'
                },
                content:{
                    tag:'center',
                    content:'Suelte Aquí para comenzar a subir'
                }
            }
    };

    var uploadzone = null;

    var dragAndDropStatus = false;

    var stopEvent = function(event)
    {
        if (event.preventDefault)
        {
            event.preventDefault();
        }
        event.dataTransfer.dropEffect = 'copy';
        return false;
    };

    var classStatus = function(status)
    {
        var status     = status|| false;
        var classList  = uploadzone.classList;
        uploadzone.classList[!!status?"add":"remove"]("hide");
        return false;
    };

    var FileUpload = function(file)
    {
        this.file = file;
        return this;
    }

    var dragEnter = function(event)
    {
        stopEvent(event);
        classStatus();
        return false;
    };
    // var dragLeave = function(event)
    // {
    //     stopEvent(event);
    //     classStatus(true);
    //     return false;
    // };

    var mouseOut = function(event)
    {
        classStatus(true);
        dragAndDropStatus = false;
        console.log('mouseout')
    }

    FileUpload.prototype.bytesMegas = function()
    {
        return Math.round((this.file.size/1024)*100)/100;
    };
    FileUpload.prototype.fileExtencion = function()
    {
        return this.file.name.split(".").pop();
    };
    FileUpload.prototype.fileInfo = function()
    {
        return {
            name : this.file.name,
            size : this.bytesMegas(this.file.size)+"Mb",
            type : this.file.type,
            extn : this.fileExtencion(this.file.name),
            last : this.file.lastModifiedDate.toLocaleDateString()
        };
    };

    var Element = function(objElem)
    {
        this.objElem = objElem;
        this.element = null;
        if(!!objElem.tag)
        {
            this.element = document.createElement(objElem.tag);
            this
                .attr()
                .content()
            ;
        }
        return this.element;
    };
    Element.prototype.attr = function()
    {
        if (!!this.objElem.attr)
        {
            for(var item in this.objElem.attr)
            {
                if (typeof(this.objElem.attr[item])=='string')
                {
                    this.element.setAttribute(item,this.objElem.attr[item]);
                }
            }
        }
        return this;
    };
    Element.prototype.content = function()
    {
        if (!!this.objElem.content)
        {
            this.objElem.content
            switch(typeof(this.objElem.content))
            {
                case "string":
                    this.element.innerHTML=this.objElem.content
                    break;
                case "object":
                    var elem  = new Element(this.objElem.content);
                    this.element.appendChild(elem);
                    break;
            }
        }
        return this;
    };

    var AjaxUpload = function(settings)
    {
        var ajaxupload = false;

        if(!!this.validateBrowser())
        {
            this.settings = typeof(settings)=="object"?defaultSetting.merge(settings):defaultSetting;
            this.parent = this.getParent();
            uploadzone = this.getUploadZone();

            addEvent(this.parent,"dragenter",dragEnter);
            addEvent(this.parent,"mouseout",mouseOut);

            //addEvent(this.parent,"dragleave",dragLeave);
            //addEvent(this.parent,'dragend', function(){console.log('dragend')});

                //             elem.addEventListener("dragenter", App.dragEnter, false);
                // elem.addEventListener("dragleave", App.leave, false);
                // elem.addEventListener("drop", App.drop, false);
                // elem.addEventListener("dragover",App.over,false);
            //console.log(this.parentUploadzone)
            //this.parentUploadzone.appendChild(this.uploadzone);
        }

        return ajaxupload;
    };

    AjaxUpload.prototype.validateBrowser = function()
    {
        var isValid = _w.File && _w.FileList && _w.FileReader;
        if(!isValid && !!this.settings.debug)
        {
            console.log("Este navegador no soporta el API")
        }
        return isValid;
    };

    AjaxUpload.prototype.getParent = function()
    {
        var element = this.settings.element;

        if (typeof(element)=='string')
        {
            var element = document.querySelector(element);
        }

        if(element == null && !!this.settings.debug)
        {
            console.log("No se encontro un Objeto Paadre")
        }

        return element;
    };

    AjaxUpload.prototype.getUploadZone = function()
    {
        var uploadzone = new Element(uploadZoneElement);
        var parentUploadzone = this.parent == document?document.body:this.parent;

        parentUploadzone.appendChild(uploadzone);

        return uploadzone;
    };

    var App = {
        elementos:{
            contenedor : ['div',{id:'ajax-upload',class:"default hide"}],
            marco:['div',{id:'ajax-upload-marco'},"Suelte Aquí para comenzar a subir"]
        },
        nElem : function (nm){
            var data = App.elementos[nm]||null;
            var elem = null;
            if (!!data){
                elem = document.createElement(data[0]);
                if(!!data[1]){
                    for(var item in data[1]){
                        elem.setAttribute(item,data[1][item]);
                    }
                }
                if(!!data[2]){
                    switch(typeof(data[2])){
                        case "string":
                            elem.innerHTML=data[2]
                        break;
                    }

                }
            }
            return elem;
        },
        stop:function(e){
            if (e.preventDefault) e.preventDefault();
            e.dataTransfer.dropEffect = 'copy';
            return false;
        },
        esXHR2 : function(){
            return !!App.xhr()?App.xhr().upload:false;
        },
        XHR: function(){
            if (_w.XMLHttpRequest){ return new XMLHttpRequest();}
            else if (_w.ActiveXObject)
            {
                try {return  new ActiveXObject("MSXML2.XMLHTTP");}
                catch (e) {
                    try {return  new ActiveXObject("Microsoft.XMLHTTP");}
                    catch (e) {}
                }
            }
            return false;
        },
      bytesMegas:function(num){return Math.round((num/1024)*100)/100;},
        fileExtencion:function(nm){ return nm.split(".").pop();},
        fileInfo:function(file){
            return {
                name : file.name,
                size : App.bytesMegas(file.size)+"Mb",
                type : file.type,
                extn : App.fileExtencion(file.name)
            };
        },
        classStatus:function(stt){
            var stt        = stt|| false;
            var elem       = document.querySelector('#ajax-upload');
            var classList  = elem.classList;
            elem.classList[!!stt?"add":"remove"]("hide");
            return false;
            //elem.classList[classList.contains('hide')?"remove":"add"]("hide");
        },
        leave:function(e){
            App.stop(e);
            App.classStatus(true);
            return false;
        },
        over: function(e){
            App.stop(e);
            App.classStatus();
            return false;
        },
        hover: function(e) {App.stop(e);App.classStatus();return false;},
        drop:function(e) {
            App.stop(e);App.classStatus(true);
            var files = e.target.files || e.dataTransfer.files;
            App.upload(files);
            return false;

        },
        upload:function(files){
            var files = files || [];
            for($I=0;$I<files.length;$I++){
                var formdata = new FormData();
                var ajax = new App.XHR();
                console.log(App.fileInfo(files[$I]));
                formdata.append("X_FILENAME", files[$I]);
                ajax.upload.addEventListener("progress", function(e){}, false);
                ajax.addEventListener("load", function(e){}, false);
                ajax.addEventListener("error", function(e){}, false);
                ajax.addEventListener("abort", function(e){}, false);
                ajax.open("POST", "file_upload_parser.php");
                ajax.send(formdata);
            }
        },
        init:function(elem){
            var elem = elem || document;
            var cont = App.nElem('contenedor');
            var mrco = App.nElem('marco');
            if(_w.File && _w.FileList && _w.FileReader) {
                elem.addEventListener("dragenter", App.hover, false);
                elem.addEventListener("dragleave", App.leave, false);
                elem.addEventListener("drop", App.drop, false);
                elem.addEventListener("dragover",App.over,false);
                document.body.appendChild(cont);
                cont.appendChild(mrco);
            }

        }

    };

    function progressHandler(event)
    {
        _("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
        var percent = (event.loaded / event.total) * 100; _("progressBar").value = Math.round(percent);
        _("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
    }
    function completeHandler(event)
    {
        _("status").innerHTML = event.target.responseText; _("progressBar").value = 0;
    }
    function errorHandler(event)
    {
        _("status").innerHTML = "Upload Failed";
    }
    function abortHandler(event)
    {
        _("status").innerHTML = "Upload Aborted";
    }

    _w.ajaxUpload = function(settings)
    {
        var ajaxUploadObject = new AjaxUpload(settings);
        //App.init()
    };
})(window);

/*
chrome: 4.0
ie: 8.0
firefox:3.5
safari:3.2
opera:10.o
*/
 <|endoftext|>


<commit_before>/* eslint-disable no-redeclare */
'use strict';

/**
* Test if a value is a finite number.
*
* @module @stdlib/assert/is-finite
*
* @example
* var isFinite = require( '@stdlib/assert/is-finite' );
*
* var bool = isFinite( 5.0 );
* // returns true
*
* bool = isFinite( new Number( 5.0 ) );
* // returns true
*
* bool = isFinite( 1.0/0.0 );
* // returns false
*
* bool = isFinite( null );
* // returns false
*
* @example
* var isFinite = require( '@stdlib/assert/is-finite' ).isPrimitive;
*
* var bool = isFinite( -3.0 );
* // returns true
*
* bool = isFinite( new Number( -3.0 ) );
* // returns false
*
* @example
* var isFinite = require( '@stdlib/assert/is-integer' ).isObject;
*
* var bool = isFinite.isObject( 3.0 );
* // returns false
*
* bool = isFinite.isObject( new Number( 3.0 ) );
* // returns true
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
var isFinite = require( './generic.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );

// MAIN //

setReadOnly( isFinite, 'isPrimitive', isPrimitive );
setReadOnly( isFinite, 'isObject', isObject );

// EXPORTS //

module.exports = isFinite;
<commit_msg>Fix require statement<commit_after>/* eslint-disable no-redeclare */
'use strict';

/**
* Test if a value is a finite number.
*
* @module @stdlib/assert/is-finite
*
* @example
* var isFinite = require( '@stdlib/assert/is-finite' );
*
* var bool = isFinite( 5.0 );
* // returns true
*
* bool = isFinite( new Number( 5.0 ) );
* // returns true
*
* bool = isFinite( 1.0/0.0 );
* // returns false
*
* bool = isFinite( null );
* // returns false
*
* @example
* var isFinite = require( '@stdlib/assert/is-finite' ).isPrimitive;
*
* var bool = isFinite( -3.0 );
* // returns true
*
* bool = isFinite( new Number( -3.0 ) );
* // returns false
*
* @example
* var isFinite = require( '@stdlib/assert/is-finite' ).isObject;
*
* var bool = isFinite.isObject( 3.0 );
* // returns false
*
* bool = isFinite.isObject( new Number( 3.0 ) );
* // returns true
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
var isFinite = require( './generic.js' );
var isPrimitive = require( './primitive.js' );
var isObject = require( './object.js' );

// MAIN //

setReadOnly( isFinite, 'isPrimitive', isPrimitive );
setReadOnly( isFinite, 'isObject', isObject );

// EXPORTS //

module.exports = isFinite;
<|endoftext|>


<commit_before>// ==UserScript==
// @name         SFcomic Viewer
// @namespace
// @version      1.1.1
// @description  A userscript for convenient viewing SFcomic.
// @author       AntonioTsai
// @include      /^http[s]?\:\/\/comic.sfacg.com\/HTML\/.*\/$/
// @include      /^http[s]?\:\/\/manhua.sfacg.com\/mh\/.*\/$/
// @include      /^http[s]?\:\/\/www.acg456.com\/HTML\/.*\/$/
// @grant        none
// @downloadURL  https://github.com/AntonioTsai/SFcomic-Viewer/raw/master/SFcomicViewer.user.js
// ==/UserScript==

/* global picAy */
(() => {
  const imgTable = document.querySelector('table tbody')
  const tempTr = document.createElement('tr')
  tempTr.appendChild(document.createElement('td'))

  // Remove original image & social media icon
  imgTable.querySelector('tr').remove()

  // Render all images
  // picAy - global array defined by site
  picAy.map((pic) => {
    const imgTr = tempTr.cloneNode(true)
    const img = document.createElement('img')

    img.src = pic
    img.className = 'scalable'
    imgTr.querySelector('td').appendChild(img)
    imgTable.appendChild(imgTr)
  })

  // Add CSS style
  let link = document.createElement('link')
  const cssFileUrl = 'https://raw.githubusercontent.com/AntonioTsai/SFcomic-Viewer/master/css/style.css'
  link.setAttribute('rel', 'stylesheet')
  link.setAttribute('type', 'text/css')
  link.setAttribute('href', cssFileUrl)
  document.head.appendChild(link)

  const topPagination = document.querySelector('.Reduction_top + .wrap > .page_turning')

  // Remove tips
  topPagination.lastChild.remove()

  // Remove unnecessary NextPage & PrePage button
  // Select the button on the top
  const topButtons = topPagination.querySelectorAll(':not(:nth-child(n+6)):not(:nth-child(-n+2))')
  topButtons.forEach((current) => {
    current.remove()
  })

  // Select the button at the bottom
  const bottomButtons = document.querySelectorAll('table + .wrap > .page_turning > :not(:nth-child(n+5)):not(:nth-child(-n+1))')
  bottomButtons.forEach((current) => {
    current.remove()
  })
})()
<commit_msg>Use selected host decided by site<commit_after>// ==UserScript==
// @name         SFcomic Viewer
// @namespace
// @version      1.1.1
// @description  A userscript for convenient viewing SFcomic.
// @author       AntonioTsai
// @include      /^http[s]?\:\/\/comic.sfacg.com\/HTML\/.*\/$/
// @include      /^http[s]?\:\/\/manhua.sfacg.com\/mh\/.*\/$/
// @include      /^http[s]?\:\/\/www.acg456.com\/HTML\/.*\/$/
// @grant        none
// @downloadURL  https://github.com/AntonioTsai/SFcomic-Viewer/raw/master/SFcomicViewer.user.js
// ==/UserScript==

/* global picAy hosts getHost */
/**
 * {Array} picAy - Array of img urls of current volume
 * {Array} hosts - Array of possible host
 * {Function} getHost - Return the index of selected host in string type
 */
(() => {
  const imgTable = document.querySelector('table tbody')
  const tempTr = document.createElement('tr')
  tempTr.appendChild(document.createElement('td'))

  let host = ''
  if (Array.isArray(hosts) & typeof getHost === 'function') {
    host = hosts[parseInt(getHost())]
  }

  // Remove original image & social media icon
  imgTable.querySelector('tr').remove()

  // Render all images
  // picAy - global array defined by site
  picAy.map((pic) => {
    const imgTr = tempTr.cloneNode(true)
    const img = document.createElement('img')

    img.src = host + pic
    img.className = 'scalable'
    imgTr.querySelector('td').appendChild(img)
    imgTable.appendChild(imgTr)
  })

  // Add CSS style
  let link = document.createElement('link')
  const cssFileUrl = 'https://raw.githubusercontent.com/AntonioTsai/SFcomic-Viewer/master/css/style.css'
  link.setAttribute('rel', 'stylesheet')
  link.setAttribute('type', 'text/css')
  link.setAttribute('href', cssFileUrl)
  document.head.appendChild(link)

  const topPagination = document.querySelector('.Reduction_top + .wrap > .page_turning')

  // Remove tips
  topPagination.lastChild.remove()

  // Remove unnecessary NextPage & PrePage button
  // Select the button on the top
  const topButtons = topPagination.querySelectorAll(':not(:nth-child(n+6)):not(:nth-child(-n+2))')
  topButtons.forEach((current) => {
    current.remove()
  })

  // Select the button at the bottom
  const bottomButtons = document.querySelectorAll('table + .wrap > .page_turning > :not(:nth-child(n+5)):not(:nth-child(-n+1))')
  bottomButtons.forEach((current) => {
    current.remove()
  })
})()
<|endoftext|>