<commit_before>var CANNON = require('cannon');
require('./wasd-physics-controls');
var coordinates = AFRAME.utils.coordinates;
var diff = AFRAME.utils.diff;

var rad = THREE.Math.degToRad;
var deg = THREE.Math.radToDeg;

// CANNON.World component.
AFRAME.registerComponent('physics-world', {
  schema: {
    gravity: { type: 'vec3', default: { x: 0, y: -9.82, z: 0 } }
  },

  init: function () {
    var el = this.el;
    var world = this.world = new CANNON.World();

    this.fixedTimeStep = 1.0 / 60.0;
    this.maxSubSteps = 3;

    // Artificially bubble physics-world events to entity.
    ['beginContact', 'endContact'].forEach(function (eventName) {
      world.addEventListener(eventName, function (event) {
        el.emit('physics-' + eventName, {
          bodyA: event.bodyA.el,
          bodyB: event.bodyB.el,
          target: event.target,
          bubbles: false
        });
      });
    });
  },

  update: function (oldData) {
    var gravity = this.data.gravity;
    var world = this.world;
    world.broadphase = new CANNON.NaiveBroadphase();
    world.gravity.set(gravity.x, gravity.y, gravity.z);
  },

  tick: function (time) {
    // Simulation loop.
    var fixedTimeStep = this.fixedTimeStep;
    var maxSubSteps = this.maxSubsteps;
    var world = this.world;

    if (this.lastTime !== undefined){
      var timeChange  = (time - this.lastTime) / 1000;
      world.step(fixedTimeStep, timeChange, maxSubSteps);
      world.bodies.forEach(function (body) {
        if (body.tickWorld) { body.tickWorld(); }
      });
    }
    this.lastTime = time;
  }
});

// CANNON.Body component.
AFRAME.registerComponent('physics-body', {
  dependencies: ['position'],

  schema: {
    angularVelocity: { type: 'vec3' },
    angularDamping: { default: 0.01 },
    boundingBox: { type: 'vec3' },
    linearDamping: { default: 0.01 },
    mass: { default: 1 },
    velocity: { type: 'vec3' }
  },

  /**
   * TODO: Don't force physics-world to be on scene to allow for multiple physics worlds.
   */
  init: function () {
    var self = this;
    var sceneEl = this.el.sceneEl;

    this.tickWorldBound = this.tickWorld.bind(this);

    // Wait for scene to load to initialize physics world.
    sceneEl.addEventListener('loaded', function () {
      if (!('physics-world' in sceneEl.components)) {
        console.warn('physics-world must be specified on scene for physics to work.');
      }
      var world = self.world = sceneEl.components['physics-world'].world;
      var body = self.body = self.getBody(self.el, self.data);
      world.add(body);
    });
  },

  update: function (oldData) {
    if (!this.world) { return; }
    var diffData = diff(this.data, oldData);

    if ('velocity' in diffData) {
      this.body.velocity.x = diffData.velocity.x;
      this.body.velocity.y = diffData.velocity.y;
      this.body.velocity.z = diffData.velocity.z;
    }
  },

  applyImpulse: function (forceVec3, pointVec3) {
    pointVec3 = pointVec3 || { x: 0, y: 0, z: 0 };
    this.body.applyImpulse(
      new CANNON.Vec3(forceVec3.x, forceVec3.y, forceVec3.z),
      new CANNON.Vec3(pointVec3.x, pointVec3.y, pointVec3.z)
    );
  },

  getBody: function (el, data) {
    var boundingBox = data.boundingBox;
    var position = el.getAttribute('position');
    var angularVelocity = data.angularVelocity;
    var velocity = data.velocity;

    var bodyProperties = {
      angularDamping: data.angularDamping,
      angularVelocity: new CANNON.Vec3(rad(angularVelocity.x), rad(angularVelocity.y),
                                       rad(angularVelocity.z)),
      linearDamping: data.linearDamping,
      mass: data.mass,
      position: new CANNON.Vec3(position.x, position.y, position.z),
      shape: new CANNON.Box(new CANNON.Vec3(boundingBox.x / 2, boundingBox.y / 2,
                                            boundingBox.z / 2)),
      velocity: new CANNON.Vec3(velocity.x, velocity.y, velocity.z)
    };

    body = new CANNON.Body(bodyProperties);

    // Attach A-Frame stuff.
    body.el = el;
    body.tickWorld = this.tickWorldBound;

    // Artificially bubble physics-body event to entity.
    body.addEventListener('collide', function (event) {
      el.emit('physics-collide', {
        body: event.body,
        contact: event.contact,
        target: event.target,
        bubbles: false
      });
    });

    return body;
  },

  /**
   * Copy CANNON rigid body properties to THREE object3D.
   */
  tickWorld: function () {
    var body = this.body;
    var el = this.el;
    el.setAttribute('position', body.position);

    // Don't rotate camera around.
    if (this.el.components.camera) { return; }

    el.setAttribute('rotation', {
      x: deg(body.quaternion.x),
      y: deg(body.quaternion.y),
      z: deg(body.quaternion.z)
    });
  }
});

// CANNON.Material component.
AFRAME.registerComponent('physics-material', {
  dependencies: ['physics-body'],

  schema: {
    angularVelocity: { type: 'vec3' },
    angularDamping: { default: 0.01 },
    boundingBox: { type: 'vec3' },
    linearDamping: { default: 0.01 },
    mass: { default: 1 },
    velocity: { type: 'vec3' }
  },

  /**
   * TODO: Don't force physics-world to be on scene to allow for multiple physics worlds.
   */
  init: function () {
    var self = this;
    var sceneEl = this.el.sceneEl;

    this.tickWorldBound = this.tickWorld.bind(this);

    // Wait for scene to load to initialize physics world.
    sceneEl.addEventListener('loaded', function () {
      if (!('physics-world' in sceneEl.components)) {
        console.warn('physics-world must be specified on scene for physics to work.');
      }
      var world = self.world = sceneEl.components['physics-world'].world;
      var body = self.body = self.getBody(self.el, self.data);
      world.add(body);
    });
  },

  update: function () {
    if (!this.world) { return; }
  },

  applyImpulse: function (forceVec3, pointVec3) {
    pointVec3 = pointVec3 || { x: 0, y: 0, z: 0 };
    this.body.applyImpulse(
      new CANNON.Vec3(forceVec3.x, forceVec3.y, forceVec3.z),
      new CANNON.Vec3(pointVec3.x, pointVec3.y, pointVec3.z)
    );
  },

  getBody: function (el, data) {
    var boundingBox = data.boundingBox;
    var position = el.getAttribute('position');
    var angularVelocity = data.angularVelocity;
    var velocity = data.velocity;

    var bodyProperties = {
      angularDamping: data.angularDamping,
      angularVelocity: new CANNON.Vec3(rad(angularVelocity.x), rad(angularVelocity.y),
                                       rad(angularVelocity.z)),
      linearDamping: data.linearDamping,
      mass: data.mass,
      position: new CANNON.Vec3(position.x, position.y, position.z),
      shape: new CANNON.Box(new CANNON.Vec3(boundingBox.x / 2, boundingBox.y / 2,
                                            boundingBox.z / 2)),
      velocity: new CANNON.Vec3(velocity.x, velocity.y, velocity.z)
    };

    body = new CANNON.Body(bodyProperties);

    // Attach A-Frame stuff.
    body.el = el;
    body.tick = this.tickWorldBound;

    // Artificially bubble physics-body event to entity.
    body.addEventListener('collide', function (event) {
      el.emit('physics-collide', {
        body: event.body,
        contact: event.contact,
        target: event.target,
        bubbles: false
      });
    });

    return body;
  },

  /**
   * Copy CANNON rigid body properties to THREE object3D.
   */
  tickWorld: function () {
    var body = this.body;
    var el = this.el;
    el.setAttribute('position', body.position);
    el.setAttribute('rotation', {
      x: deg(body.quaternion.x),
      y: deg(body.quaternion.y),
      z: deg(body.quaternion.z)
    });
  }
});
<commit_msg>run if already loaded<commit_after>var CANNON = require('cannon');
require('./wasd-physics-controls');
var coordinates = AFRAME.utils.coordinates;
var diff = AFRAME.utils.diff;

var rad = THREE.Math.degToRad;
var deg = THREE.Math.radToDeg;

// CANNON.World component.
AFRAME.registerComponent('physics-world', {
  schema: {
    gravity: { type: 'vec3', default: { x: 0, y: -9.82, z: 0 } }
  },

  init: function () {
    var el = this.el;
    var world = this.world = new CANNON.World();

    this.fixedTimeStep = 1.0 / 60.0;
    this.maxSubSteps = 3;

    // Artificially bubble physics-world events to entity.
    ['beginContact', 'endContact'].forEach(function (eventName) {
      world.addEventListener(eventName, function (event) {
        el.emit('physics-' + eventName, {
          bodyA: event.bodyA.el,
          bodyB: event.bodyB.el,
          target: event.target,
          bubbles: false
        });
      });
    });
  },

  update: function (oldData) {
    var gravity = this.data.gravity;
    var world = this.world;
    world.broadphase = new CANNON.NaiveBroadphase();
    world.gravity.set(gravity.x, gravity.y, gravity.z);
  },

  tick: function (time) {
    // Simulation loop.
    var fixedTimeStep = this.fixedTimeStep;
    var maxSubSteps = this.maxSubsteps;
    var world = this.world;

    if (this.lastTime !== undefined){
      var timeChange  = (time - this.lastTime) / 1000;
      world.step(fixedTimeStep, timeChange, maxSubSteps);
      world.bodies.forEach(function (body) {
        if (body.tickWorld) { body.tickWorld(); }
      });
    }
    this.lastTime = time;
  }
});

// CANNON.Body component.
AFRAME.registerComponent('physics-body', {
  dependencies: ['position'],

  schema: {
    angularVelocity: { type: 'vec3' },
    angularDamping: { default: 0.01 },
    boundingBox: { type: 'vec3' },
    linearDamping: { default: 0.01 },
    mass: { default: 1 },
    velocity: { type: 'vec3' }
  },

  /**
   * TODO: Don't force physics-world to be on scene to allow for multiple physics worlds.
   */
  init: function () {
    var self = this;
    var sceneEl = this.el.sceneEl;

    var run = function() {
      if (!('physics-world' in sceneEl.components)) {
        console.warn('physics-world must be specified on scene for physics to work.');
      }
      var world = self.world = sceneEl.components['physics-world'].world;
      var body = self.body = self.getBody(self.el, self.data);
      world.add(body);
    };

    this.tickWorldBound = this.tickWorld.bind(this);

    if (sceneEl.hasLoaded) {
      run();
    } else {
      sceneEl.addEventListener('loaded', run)
    };
  },

  update: function (oldData) {
    if (!this.world) { return; }
    var diffData = diff(this.data, oldData || this.data);

    if ('velocity' in diffData) {
      this.body.velocity.x = diffData.velocity.x;
      this.body.velocity.y = diffData.velocity.y;
      this.body.velocity.z = diffData.velocity.z;
    }
  },

  applyImpulse: function (forceVec3, pointVec3) {
    pointVec3 = pointVec3 || { x: 0, y: 0, z: 0 };
    this.body.applyImpulse(
      new CANNON.Vec3(forceVec3.x, forceVec3.y, forceVec3.z),
      new CANNON.Vec3(pointVec3.x, pointVec3.y, pointVec3.z)
    );
  },

  getBody: function (el, data) {
    var boundingBox = data.boundingBox;
    var position = el.getAttribute('position');
    var angularVelocity = data.angularVelocity;
    var velocity = data.velocity;

    var bodyProperties = {
      angularDamping: data.angularDamping,
      angularVelocity: new CANNON.Vec3(rad(angularVelocity.x), rad(angularVelocity.y),
                                       rad(angularVelocity.z)),
      linearDamping: data.linearDamping,
      mass: data.mass,
      position: new CANNON.Vec3(position.x, position.y, position.z),
      shape: new CANNON.Box(new CANNON.Vec3(boundingBox.x / 2, boundingBox.y / 2,
                                            boundingBox.z / 2)),
      velocity: new CANNON.Vec3(velocity.x, velocity.y, velocity.z)
    };

    body = new CANNON.Body(bodyProperties);

    // Attach A-Frame stuff.
    body.el = el;
    body.tickWorld = this.tickWorldBound;

    // Artificially bubble physics-body event to entity.
    body.addEventListener('collide', function (event) {
      el.emit('physics-collide', {
        body: event.body,
        contact: event.contact,
        target: event.target,
        bubbles: false
      });
    });

    return body;
  },

  /**
   * Copy CANNON rigid body properties to THREE object3D.
   */
  tickWorld: function () {
    var body = this.body;
    var el = this.el;
    el.setAttribute('position', body.position);

    // Don't rotate camera around.
    if (this.el.components.camera) { return; }

    el.setAttribute('rotation', {
      x: deg(body.quaternion.x),
      y: deg(body.quaternion.y),
      z: deg(body.quaternion.z)
    });
  }
});

// CANNON.Material component.
AFRAME.registerComponent('physics-material', {
  dependencies: ['physics-body'],

  schema: {
    angularVelocity: { type: 'vec3' },
    angularDamping: { default: 0.01 },
    boundingBox: { type: 'vec3' },
    linearDamping: { default: 0.01 },
    mass: { default: 1 },
    velocity: { type: 'vec3' }
  },

  /**
   * TODO: Don't force physics-world to be on scene to allow for multiple physics worlds.
   */
  init: function () {
    var self = this;
    var sceneEl = this.el.sceneEl;

    this.tickWorldBound = this.tickWorld.bind(this);

    // Wait for scene to load to initialize physics world.
    sceneEl.addEventListener('loaded', function () {
      if (!('physics-world' in sceneEl.components)) {
        console.warn('physics-world must be specified on scene for physics to work.');
      }
      var world = self.world = sceneEl.components['physics-world'].world;
      var body = self.body = self.getBody(self.el, self.data);
      world.add(body);
    });
  },

  update: function () {
    if (!this.world) { return; }
  },

  applyImpulse: function (forceVec3, pointVec3) {
    pointVec3 = pointVec3 || { x: 0, y: 0, z: 0 };
    this.body.applyImpulse(
      new CANNON.Vec3(forceVec3.x, forceVec3.y, forceVec3.z),
      new CANNON.Vec3(pointVec3.x, pointVec3.y, pointVec3.z)
    );
  },

  getBody: function (el, data) {
    var boundingBox = data.boundingBox;
    var position = el.getAttribute('position');
    var angularVelocity = data.angularVelocity;
    var velocity = data.velocity;

    var bodyProperties = {
      angularDamping: data.angularDamping,
      angularVelocity: new CANNON.Vec3(rad(angularVelocity.x), rad(angularVelocity.y),
                                       rad(angularVelocity.z)),
      linearDamping: data.linearDamping,
      mass: data.mass,
      position: new CANNON.Vec3(position.x, position.y, position.z),
      shape: new CANNON.Box(new CANNON.Vec3(boundingBox.x / 2, boundingBox.y / 2,
                                            boundingBox.z / 2)),
      velocity: new CANNON.Vec3(velocity.x, velocity.y, velocity.z)
    };

    body = new CANNON.Body(bodyProperties);

    // Attach A-Frame stuff.
    body.el = el;
    body.tick = this.tickWorldBound;

    // Artificially bubble physics-body event to entity.
    body.addEventListener('collide', function (event) {
      el.emit('physics-collide', {
        body: event.body,
        contact: event.contact,
        target: event.target,
        bubbles: false
      });
    });

    return body;
  },

  /**
   * Copy CANNON rigid body properties to THREE object3D.
   */
  tickWorld: function () {
    var body = this.body;
    var el = this.el;
    el.setAttribute('position', body.position);
    el.setAttribute('rotation', {
      x: deg(body.quaternion.x),
      y: deg(body.quaternion.y),
      z: deg(body.quaternion.z)
    });
  }
});
<|endoftext|>


<commit_before>var Arrow = require('arrow'),
	_ = require('lodash');

/**
 * Creates models from your schema (see "fetchSchema" for more information on the schema).
 */
exports.createModelsFromSchema = function () {
	var models = {};
	for (var modelName in this.schema.objects) {
		if (this.schema.objects.hasOwnProperty(modelName)) {
			var object = this.schema.objects[modelName],
				pk = this.schema.primary_keys[modelName],
				fields = {};

			if (!pk) {
				this.logger.info('Skipping generation of model from table ' + modelName + ' because it has no primary key in the schema.');
				continue;
			}

			for (var fieldName in object) {
				if (object.hasOwnProperty(fieldName)) {
					if (fieldName === 'id') {
						continue;
					}
					fields[fieldName] = {
						type: this.convertDataTypeToJSType(object[fieldName].DATA_TYPE),
						required: object.IS_NULLABLE === 'NO',
						readonly: object.DATA_TYPE === 'timestamp',
						custom: object.DATA_TYPE === 'timestamp'
					};
				}
			}

			var nsName = this.name + '/' + modelName;
			models[nsName] = Arrow.Model.extend(nsName, {
				name: nsName,
				autogen: !!this.config.modelAutogen,
				fields: fields,
				connector: this,
				generated: true
			});
		}
	}
	this.models = _.defaults(this.models || {}, models);
};
<commit_msg>[ARRCONN-238] Use primaryKey column with different name than 'id' in models<commit_after>var Arrow = require('arrow'),
	_ = require('lodash');

/**
 * Creates models from your schema (see "fetchSchema" for more information on the schema).
 */
exports.createModelsFromSchema = function () {
	var self = this,
		models = {},
		exposePrimaryKeyAsId = _.has(Arrow.getGlobal(), 'config.serialization.exposePrimaryKeyAsId') ? _.get(Arrow.getGlobal(), 'config.serialization.exposePrimaryKeyAsId') : false;

	/**
	 * Returns model's primary key column's name
	 * @param {string} modelName
	 * @returns {string}
	 */
	function getPrimaryKeyFromSchema(modelName) {
		return self.schema.primary_keys[modelName];
	}

	/**
	 * Get model fields except the primaryKey field
	 * @param {string} modelName
	 * @param {Object} modelSchema
	 * @returns {Object}
	 */
	function getFieldsExceptPrimaryKey(modelName, modelSchema) {
		return Object.keys(modelSchema)
			.filter(function (fieldName) {
				var primaryKeyColumnName = getPrimaryKeyFromSchema(modelName);
				return exposePrimaryKeyAsId && typeof primaryKeyColumnName !== 'undefined' && fieldName === primaryKeyColumnName ? false : (fieldName === 'id' ? false : true);
			})
			.reduce(function (fields, fieldName) {
				fields[fieldName] = {
					type: self.convertDataTypeToJSType(modelSchema[fieldName].DATA_TYPE),
					required: modelSchema.IS_NULLABLE === 'NO',
					readonly: modelSchema.DATA_TYPE === 'timestamp',
					custom: modelSchema.DATA_TYPE === 'timestamp'
				};

				return fields;
			}, {});
	}

	/**
	 * Generate Arrow Model base on model name and fields
	 * @param {string} modelName
	 * @param {Object} fields
	 * @returns {Object}
	 */
	function genModel (modelName, fields) {
		var primaryKeyColumnName = getPrimaryKeyFromSchema(modelName);

		var modelInfo = {
			name: self.name + '/' + modelName,
			autogen: !!self.config.modelAutogen,
			fields: fields,
			connector: self,
			generated: true
		};

		if (typeof primaryKeyColumnName !== undefined) {
			modelInfo.metadata = {
				primarykey: primaryKeyColumnName
			};
		}

		return Arrow.Model.extend(self.name + '/' + modelName, modelInfo);
	}

	// Generate models based on schema objects
	Object.keys(self.schema.objects)
		.filter(function (modelName) {
			var hasPk = typeof getPrimaryKeyFromSchema(modelName) === 'undefined';
			if (!hasPk) {
				this.logger.info('Skipping generation of model from table ' + modelName + ' because it has no primary key in the schema.');
			}

			return hasPk;
		})
		.forEach(function (modelName) {
			var object = self.schema.objects[modelName];

			var fields = getFieldsExceptPrimaryKey(modelName, object);
			models[self.name + '/' + modelName] = genModel(modelName, fields);
		});

	self.models = _.defaults(self.models || {}, models);
};

<|endoftext|>


<commit_before>//This variables will be global variable
var global_width=undefined;
var global_height=undefined;

//Orientation of the device, if is undefined; we assume a pc here
//Else it will be:
//      verticle:0 or 180
//      horizontal:90 or -90
var previousOrientation = window.orientation;

//Video initialization etc
var video = document.createElement('video');
video.autoplay=true;
video.playsInline = true;
video.setAttribute("playsinline", true);
video.setAttribute("controls", true);

var videoTexture = new THREE.Texture(video);
var surface_material_video = new THREE.MeshBasicMaterial ({
    map : videoTexture
});

//var videoSelect = document.querySelector('select#videoSource');
var videoSelect = document.querySelector('select#videoSource');
var selectors=[videoSelect];
var video_devices=[];
//Gets devices
function gotDevices(deviceInfos) {
    var values = selectors.map(function(select) {
        return select.value;
    });
    selectors.forEach(function(select) {
        while (select.firstChild) {
            select.removeChild(select.firstChild);
        }
    });
    for (var i = 0; i !== deviceInfos.length; ++i) {
        var deviceInfo = deviceInfos[i];
        var option = document.createElement('option');

        option.value = deviceInfo.deviceId;
        option.readyState = deviceInfo.readyState;
        if (deviceInfo.kind === 'videoinput') {
            option.text = deviceInfo.label || 'camera ' + (videoSelect.length + 1);

            // alert( option.text);
           videoSelect.appendChild(option);
            //video_devices.push(deviceInfo);

           // videoSelect.insertBefore(option, videoSelect.firstChild)
        }
    }

    selectors.forEach(function(select, selectorIndex) {
        if (Array.prototype.slice.call(select.childNodes).some(function(n) {
            return n.value === values[selectorIndex];
        })) {
            select.value = values[selectorIndex];
        }
    });
}

//enumerates the devices
navigator.mediaDevices.enumerateDevices().then(gotDevices).catch(handleError);

//If stream is received
function gotStream(stream) {
    window.stream = stream; // make stream available to console
    video.srcObject = stream;
  //  alert("got stream called");
    // Refresh button list in case labels have become available
    return navigator.mediaDevices.enumerateDevices();

}

function handleError(error) {
    console.log('navigator.getUserMedia error: ', error);
}

//switch value for videoSelect

function start() {
    if (window.stream) {
        window.stream.getTracks().forEach(function(track) {
            track.stop();
        });
    }

   // alert("Changed");
    //var audioSource = audioInputSelect.value;
    var videoSource = videoSelect.value;
    //var videoSource = text.camera_type.deviceId;
    //alert(videoSource)
    var constraints = {
        // audio: {deviceId: audioSource ? {exact: audioSource} : undefined},
        video: {deviceId: videoSource ? {exact: videoSource} : undefined},

    };

    //alert(videoSelect.length);
    navigator.mediaDevices.getUserMedia(constraints).
    then(gotStream).then(gotDevices).catch(handleError);
    //video.addEventListener("loadedmetadata");

    //if the meta data has changed;
    video.onloadedmetadata=function(){
        global_width=this.videoWidth;
        global_height=this.videoHeight;
    }

    /*
    video.onloadedmetadata = function() {
        console.log('width is', this.videoWidth);
        console.log('height is', this.videoHeight);

        if(this.videoWidth < 10){
            video.width = 480;
        } else {
            video.width = this.videoWidth;
        }

        if(this.videoHeigth <10){
            video.height = 640;
        } else{
            video.height = this.videoHeight;
        }
        // video.width = 480;
        // video.height = 640;

        //alert("f");
        //if it is undefined then it is on a pc (probably)
        if(previousOrientation ==false){
            plane.scale.set(video.width,video.height,1);
        } else{
            plane.scale.set(video.height,video.width,1);
            //if the orientation is verticle
            if ((previousOrientation==0)||(previousOrientation==180)){
                plane.scale.set(video.height,video.width,1);
            } else if((previousOrientation==90)||(previousOrientation==-90)){
                //if the device is orizontal
                plane.scale.set(video.width,video.height,1);
            }
        }

        //  alert("width : "+video.width);
        //alert("height : "+video.height);

        //alert("video width is: " +video.width);
        //alert("video height is: "+video.height);
    }
    */
    //alert("video width is: " +video.width);
    //  alert("video height is: "+video.height);
    //video.onloadedmetadata();
    //video.width =1000;
    //video.Height =1000;
    console.log(video.width);
    console.log(video.height);
    video.setAttribute("playsinline", true);
    video.setAttribute("controls", true);
}

videoSelect.onchange = start;

//cameraFolder.add(text, 'camera_type', [ 'pizza', 'chrome', 'hooray' ] ).onChange = start;
//checkOrientation();
start();

//Function for resizing the image plane in Zinc if the orientation is changed
var checkOrientation = function(){
    if(previousOrientation!==undefined){
        if(window.orientation!==previousOrientation){

            previousOrientation = window.orientation;

            //If the current orientation is horizontal we switch width <-> height
            var dummyGlobalHeight = global_height;
            global_height = global_width;
            global_width = dummyGlobalHeight;
          //  alert(previousOrientation);
            if((previousOrientation==90)||(previousOrientation==-90)){
                //document.getElementById('plane-slider').value = 400;
                text.planeSize = 400;
                //alert('changed');
            } else if((previousOrientation==0)||(previousOrientation==180)){
                 //document.getElementById('plane-slider').value = 0;
                text.planeSize = 0;
            }
        }
    }
}

 window.addEventListener("orientationchange", checkOrientation, false);

videoSource_defined = false;

<commit_msg>Added playsinline for ios support<commit_after>//This variables will be global variable
var global_width=undefined;
var global_height=undefined;

//Orientation of the device, if is undefined; we assume a pc here
//Else it will be:
//      verticle:0 or 180
//      horizontal:90 or -90
var previousOrientation = window.orientation;

//Video initialization etc
var video = document.createElement('video');
video.autoplay=true;
video.playsInline = true;
video.setAttribute("playsinline", true);
video.setAttribute("controls", true);

var videoTexture = new THREE.Texture(video);
var surface_material_video = new THREE.MeshBasicMaterial ({
    map : videoTexture
});

//var videoSelect = document.querySelector('select#videoSource');
var videoSelect = document.querySelector('select#videoSource');
var selectors=[videoSelect];
var video_devices=[];
//Gets devices
function gotDevices(deviceInfos) {
    var values = selectors.map(function(select) {
        return select.value;
    });
    selectors.forEach(function(select) {
        while (select.firstChild) {
            select.removeChild(select.firstChild);
        }
    });
    for (var i = 0; i !== deviceInfos.length; ++i) {
        var deviceInfo = deviceInfos[i];
        var option = document.createElement('option');

        option.value = deviceInfo.deviceId;
        option.readyState = deviceInfo.readyState;
        if (deviceInfo.kind === 'videoinput') {
            option.text = deviceInfo.label || 'camera ' + (videoSelect.length + 1);

            // alert( option.text);
           videoSelect.appendChild(option);
            //video_devices.push(deviceInfo);

           // videoSelect.insertBefore(option, videoSelect.firstChild)
        }
    }

    selectors.forEach(function(select, selectorIndex) {
        if (Array.prototype.slice.call(select.childNodes).some(function(n) {
            return n.value === values[selectorIndex];
        })) {
            select.value = values[selectorIndex];
        }
    });
}

//enumerates the devices
navigator.mediaDevices.enumerateDevices().then(gotDevices).catch(handleError);

//If stream is received
function gotStream(stream) {
    window.stream = stream; // make stream available to console
    video.srcObject = stream;
  //  alert("got stream called");
    // Refresh button list in case labels have become available
    return navigator.mediaDevices.enumerateDevices();

}

function handleError(error) {
    console.log('navigator.getUserMedia error: ', error);
}

//switch value for videoSelect

function start() {
    if (window.stream) {
        window.stream.getTracks().forEach(function(track) {
            track.stop();
        });
    }

   // alert("Changed");
    //var audioSource = audioInputSelect.value;
    var videoSource = videoSelect.value;
    //var videoSource = text.camera_type.deviceId;
    //alert(videoSource)
    video.setAttribute("playsinline", true);
    video.setAttribute("controls", true);
    var constraints = {
        // audio: {deviceId: audioSource ? {exact: audioSource} : undefined},
        video: {deviceId: videoSource ? {exact: videoSource} : undefined},

    };

    //alert(videoSelect.length);
    navigator.mediaDevices.getUserMedia(constraints).
    then(gotStream).then(gotDevices).catch(handleError);
    //video.addEventListener("loadedmetadata");

    //if the meta data has changed;
    video.onloadedmetadata=function(){
        global_width=this.videoWidth;
        global_height=this.videoHeight;
    }

    /*
    video.onloadedmetadata = function() {
        console.log('width is', this.videoWidth);
        console.log('height is', this.videoHeight);

        if(this.videoWidth < 10){
            video.width = 480;
        } else {
            video.width = this.videoWidth;
        }

        if(this.videoHeigth <10){
            video.height = 640;
        } else{
            video.height = this.videoHeight;
        }
        // video.width = 480;
        // video.height = 640;

        //alert("f");
        //if it is undefined then it is on a pc (probably)
        if(previousOrientation ==false){
            plane.scale.set(video.width,video.height,1);
        } else{
            plane.scale.set(video.height,video.width,1);
            //if the orientation is verticle
            if ((previousOrientation==0)||(previousOrientation==180)){
                plane.scale.set(video.height,video.width,1);
            } else if((previousOrientation==90)||(previousOrientation==-90)){
                //if the device is orizontal
                plane.scale.set(video.width,video.height,1);
            }
        }

        //  alert("width : "+video.width);
        //alert("height : "+video.height);

        //alert("video width is: " +video.width);
        //alert("video height is: "+video.height);
    }
    */
    //alert("video width is: " +video.width);
    //  alert("video height is: "+video.height);
    //video.onloadedmetadata();
    //video.width =1000;
    //video.Height =1000;
    console.log(video.width);
    console.log(video.height);

}

videoSelect.onchange = start;

//cameraFolder.add(text, 'camera_type', [ 'pizza', 'chrome', 'hooray' ] ).onChange = start;
//checkOrientation();
start();

//Function for resizing the image plane in Zinc if the orientation is changed
var checkOrientation = function(){
    if(previousOrientation!==undefined){
        if(window.orientation!==previousOrientation){

            previousOrientation = window.orientation;

            //If the current orientation is horizontal we switch width <-> height
            var dummyGlobalHeight = global_height;
            global_height = global_width;
            global_width = dummyGlobalHeight;
          //  alert(previousOrientation);
            if((previousOrientation==90)||(previousOrientation==-90)){
                //document.getElementById('plane-slider').value = 400;
                text.planeSize = 400;
                //alert('changed');
            } else if((previousOrientation==0)||(previousOrientation==180)){
                 //document.getElementById('plane-slider').value = 0;
                text.planeSize = 0;
            }
        }
    }
}

 window.addEventListener("orientationchange", checkOrientation, false);

videoSource_defined = false;

<|endoftext|>


<commit_before>"use strict";

var value = require("value");

var env = require("../env.js"),
    RemoteService;

if (env.isClient()) {
    RemoteService = require("../../client/RemoteService.class.js");
}

/**
 * process the response and modify the model-instance
 * @param {!Model} modelInstance
 * @param {!Object} response
 * @return {Error} err
 */
function processResponse(modelInstance, response) {

    var err = null,
        model = {};

    if (typeof response !== "object" || response === null) {
        return new Error("(alamid) Invalid Response: Object expected.");
    }

    if (response.status === "error") {
        return new Error(response.message || "An error occurred.");
    }

    if (response.data !== undefined && response.status === "success") {
        model = response.data;
    }

    if (!err) {

        //set parent ids
        if (model.ids !== undefined) {
            modelInstance.setIds(model.ids);
        }
        //set id
        if (model.id !== undefined) {
            modelInstance.setId(model.id);
        }

        if (model && value(model).notTypeOf(modelInstance.constructor)) {
            modelInstance.set(model);    // this may throw an exception
        }
    }

    return err;
}

/**
 * call the actual service
 * function acts like a proxy and strips unneeded params
 * it also handles sync / async service-responses
 *
 * @param {!Function} serviceFunction
 * @param {Boolean} remote
 * @param {Object} ids
 * @param {Object} data
 * @param {Function} callback
 */
function callService(serviceFunction, remote, ids, data, callback) {

    var args = Array.prototype.slice.call(arguments, 0);
    //the last param is callback dude!
    callback = args[args.length - 1];

    //remove the first element, because it's the function itself
    args.splice(0, 1);

    //remove "remote" attribute on the server
    if (env.isServer()) {
        args.splice(0, 1);
    }

    //async
    if (serviceFunction.length === args.length) {
        serviceFunction.apply(this, args);
    }
    //sync
    else if (serviceFunction.length === args.length - 1) {
        //remove the final callback
        args.splice(args.length - 1, 1);
        callback(serviceFunction.apply(this, args));
    }
    //invalid function passed
    else {
        throw new Error("(alamid) Function '" +
            serviceFunction.toString().replace(/\s\{.*/, "") + "' accepts unexpected number of arguments");
    }
}

/**
 * handle the service call and model-modification
 * returns an error and the service-call response
 *
 * @param {!Model} modelInstance
 * @param {!String} method
 * @param {!Boolean} remote
 * @param {!Function} callback
 */
function serviceAdapter(modelInstance, method, remote, callback) {

    var remoteService,
        serviceFunction,
        remoteServiceFunction,
        service = modelInstance.getService(),
        ids = modelInstance.getIds(),
        url = modelInstance.getUrl(),
        params;

    //only for readCollection
    if (typeof modelInstance.getParams === "function") {
        params = modelInstance.getParams();
    }

    function onServiceResponse(response) {
        var err;

        try {
            err = processResponse(modelInstance, response);

        } catch (err) {
            err.message = "(alamid) Service-Error [" + method + "] " + err.message;
        }

        if (!err) {
            modelInstance.emit(method);
        }

        callback(err, response);
    }

    if (service && service[method] !== undefined) {
        serviceFunction = service[method].bind(service);
    }

    //remote-services work only on the client
    if (env.isClient() && remote === true) {
        //load remote-service-adapter
        remoteService = new RemoteService(url);
        remoteServiceFunction = remoteService[method].bind(remoteService);
        //append to be used in service
        remote = remoteServiceFunction;
    }

    //No client service defined
    //append remote-service as main service and set remote to false
    if (!serviceFunction && remote !== false && env.isClient()) {
        serviceFunction = remoteServiceFunction;
        remote = true; // will be recycled by remoteService
    }

    if (!serviceFunction) {
        callback(new Error("(alamid) " + modelInstance.getUrl() + "[" + method + "] : There is no service available."));
        return;
    }

    //METHOD DEPENDENT CALLS
    switch (method) {

        case "create" :
            callService(serviceFunction, remote, ids, modelInstance, onServiceResponse);
            break;
        case "read" :
            callService(serviceFunction, remote, ids, onServiceResponse);
            break;
        case "readCollection" :
            //direct callback here, no processing, because there is no instance
            callService(serviceFunction, remote, ids, params, callback);
            break;
        case "update" :
            callService(serviceFunction, remote, ids, modelInstance, onServiceResponse);
            break;
        case "destroy" :
            callService(serviceFunction, remote, ids, onServiceResponse);
            break;
        default :
            onServiceResponse(new Error("(alamid) Service-Adapter - Invalid method '" + method + "'"));
    }
}

module.exports = serviceAdapter;<commit_msg>- fixed bug with hidden error in case processResponse doesn't work<commit_after>"use strict";

var value = require("value");

var env = require("../env.js"),
    RemoteService;

if (env.isClient()) {
    RemoteService = require("../../client/RemoteService.class.js");
}

/**
 * process the response and modify the model-instance
 * @param {!Model} modelInstance
 * @param {!Object} response
 * @return {Error} err
 */
function processResponse(modelInstance, response) {

    var modelData = {};

    if (typeof response !== "object" || response === null) {
        throw new Error("(alamid) Invalid Response: Object expected.");
    }

    if (response.status === "error") {
        throw new Error(response.message || "An error occurred.");
    }

    if (response.data !== undefined && response.status === "success") {
        modelData = response.data;
    }

    //set parent ids
    if (modelData.ids !== undefined) {
        modelInstance.setIds(modelData.ids);
    }
    //set id
    if (modelData.id !== undefined) {
        modelInstance.setId(modelData.id);
    }

    if (modelData && value(modelData).notTypeOf(modelInstance.constructor)) {
        modelInstance.set(modelData);    // this may throw an exception
    }
}

/**
 * call the actual service
 * function acts like a proxy and strips unneeded params
 * it also handles sync / async service-responses
 *
 * @param {!Function} serviceFunction
 * @param {Boolean} remote
 * @param {Object} ids
 * @param {Object} data
 * @param {Function} callback
 */
function callService(serviceFunction, remote, ids, data, callback) {

    var args = Array.prototype.slice.call(arguments, 0);
    //the last param is callback dude!
    callback = args[args.length - 1];

    //remove the first element, because it's the function itself
    args.splice(0, 1);

    //remove "remote" attribute on the server
    if (env.isServer()) {
        args.splice(0, 1);
    }

    //async
    if (serviceFunction.length === args.length) {
        serviceFunction.apply(this, args);
    }
    //sync
    else if (serviceFunction.length === args.length - 1) {
        //remove the final callback
        args.splice(args.length - 1, 1);
        callback(serviceFunction.apply(this, args));
    }
    //invalid function passed
    else {
        throw new Error("(alamid) Function '" +
            serviceFunction.toString().replace(/\s\{.*/, "") + "' accepts unexpected number of arguments");
    }
}

/**
 * handle the service call and model-modification
 * returns an error and the service-call response
 *
 * @param {!Model} modelInstance
 * @param {!String} method
 * @param {!Boolean} remote
 * @param {!Function} callback
 */
function serviceAdapter(modelInstance, method, remote, callback) {

    var remoteService,
        serviceFunction,
        remoteServiceFunction,
        service = modelInstance.getService(),
        ids = modelInstance.getIds(),
        url = modelInstance.getUrl(),
        params;

    //only for readCollection
    if (typeof modelInstance.getParams === "function") {
        params = modelInstance.getParams();
    }

    function onServiceResponse(response) {

        var err = null;

        try {
            processResponse(modelInstance, response);
        } catch (e) {
            e.message = "(alamid) Service-Error [" + method + "] " + e.message;
            err = e;
        }

        if (!err) {
            modelInstance.emit(method);
        }

        callback(err, response);
    }

    if (service && service[method] !== undefined) {
        serviceFunction = service[method].bind(service);
    }

    //remote-services work only on the client
    if (env.isClient() && remote === true) {
        //load remote-service-adapter
        remoteService = new RemoteService(url);
        remoteServiceFunction = remoteService[method].bind(remoteService);
        //append to be used in service
        remote = remoteServiceFunction;
    }

    //No client service defined
    //append remote-service as main service and set remote to false
    if (!serviceFunction && remote !== false && env.isClient()) {
        serviceFunction = remoteServiceFunction;
        remote = true; // will be recycled by remoteService
    }

    if (!serviceFunction) {
        callback(new Error("(alamid) " + modelInstance.getUrl() + "[" + method + "] : There is no service available."));
        return;
    }

    //METHOD DEPENDENT CALLS
    switch (method) {

        case "create" :
            callService(serviceFunction, remote, ids, modelInstance, onServiceResponse);
            break;
        case "read" :
            callService(serviceFunction, remote, ids, onServiceResponse);
            break;
        case "readCollection" :
            //direct callback here, no processing, because there is no instance
            callService(serviceFunction, remote, ids, params, callback);
            break;
        case "update" :
            callService(serviceFunction, remote, ids, modelInstance, onServiceResponse);
            break;
        case "destroy" :
            callService(serviceFunction, remote, ids, onServiceResponse);
            break;
        default :
            onServiceResponse(new Error("(alamid) Service-Adapter - Invalid method '" + method + "'"));
    }
}

module.exports = serviceAdapter;<|endoftext|>


<commit_before>Package.describe({
  name: 'meteorsteam:meteor-postgres',
  version: '0.1.0',
  // Brief, one-line summary of the package.
  summary: 'PostgreSQL support for Meteor',
  // URL to the Git repository containing the source code for this package.
  git: 'https://github.com/meteor-stream/meteor-postgres',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Npm.depends({
  'pg': '4.3.0'
});

Package.onUse(function (api) {
  // The order these files are imported is very important
  api.versionsFrom('1.1.0.1');
  api.use('underscore');
  api.use('tracker');
  api.use('ddp');

  // minisql
  api.addFiles(['minisql/alasql.js', 'minisql/alasql.js.map', 'minisql/minisql.js'], 'client');
  api.export('miniSQL', 'client');

  api.addFiles('postgres/serversql.js', 'server');
  api.export('serverSQL', 'server');

  api.addFiles('collection/collection.js');
  api.export('SQL');

});

Package.onTest(function (api) {
  api.versionsFrom('1.1');
  api.use(['spacebars', 'tinytest', 'test-helpers', 'underscore', 'tracker', 'ddp']);
  api.addFiles('postgres/serversql.js', 'server');
  api.export('serverSQL', 'server');
  api.addFiles('collection/collection.js', ['server', 'client']);
  api.export('SQL', ['server', 'client']);
  api.addFiles('collection/collection_tests.js');
  api.addFiles('postgres/sqlserver_tests.js', 'server');
});

<commit_msg>Updated package for publishing<commit_after>Package.describe({
  name: 'meteorsteam:meteor-postgres',
  version: '0.1.3',
  // Brief, one-line summary of the package.
  summary: 'PostgreSQL support for Meteor',
  // URL to the Git repository containing the source code for this package.
  git: 'https://github.com/meteor-stream/meteor-postgres',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Npm.depends({
  'pg': '4.3.0'
});

Package.onUse(function (api) {
  // The order these files are imported is very important
  api.versionsFrom('1.1.0.1');
  api.use('underscore');
  api.use('tracker');
  api.use('ddp');

  // minisql
  api.addFiles(['minisql/alasql.js', 'minisql/alasql.js.map', 'minisql/minisql.js'], 'client');
  api.export('miniSQL', 'client');

  api.addFiles('postgres/serversql.js', 'server');
  api.export('serverSQL', 'server');

  api.addFiles('collection/collection.js');
  api.export('SQL');

});

Package.onTest(function (api) {
  api.versionsFrom('1.1');
  api.use(['spacebars', 'tinytest', 'test-helpers', 'underscore', 'tracker', 'ddp']);
  api.addFiles('postgres/serversql.js', 'server');
  api.export('serverSQL', 'server');
  api.addFiles('collection/collection.js', ['server', 'client']);
  api.export('SQL', ['server', 'client']);
  api.addFiles('collection/collection_tests.js');
  api.addFiles('postgres/sqlserver_tests.js', 'server');
});

<|endoftext|>


<commit_before>function ITF14(string){
	this.valid = function(){
		return string.search(/^[0-9]{13,14}$/) !== -1 &&
			(string.length === 13 || string[13] == checksum(string));
	};

	this.encode = function(){
		//Create the variable that should be returned at the end of the function
		var result = "";

		//If checksum is not already calculated, do it
		if(string.length === 13){
			string += checksum(string);
		}

		//Always add the same start bits
		result += startBin;

		//Calculate all the digit pairs
		for(var i=0;i<14;i+=2){
			result += calculatePair(string.substr(i,2));
		}

		//Always add the same end bits
		result += endBin;

		return {data: result, text: string};
	};

	//The structure for the all digits, 1 is wide and 0 is narrow
	var digitStructure = {
		 "0":"00110"
		,"1":"10001"
		,"2":"01001"
		,"3":"11000"
		,"4":"00101"
		,"5":"10100"
		,"6":"01100"
		,"7":"00011"
		,"8":"10010"
		,"9":"01010"
	};

	//The start bits
	var startBin = "1010";
	//The end bits
	var endBin = "11101";

	//Calculate the data of a number pair
	function calculatePair(twoNumbers){
		var result = "";

		var number1Struct = digitStructure[twoNumbers[0]];
		var number2Struct = digitStructure[twoNumbers[1]];

		//Take every second bit and add to the result
		for(var i=0;i<5;i++){
			result += (number1Struct[i]=="1") ? "111" : "1";
			result += (number2Struct[i]=="1") ? "000" : "0";
		}
		return result;
	}

	//Calulate the checksum digit
	function checksum(numberString){
		var result = 0;

		for(var i=0;i<13;i++){
			result += parseInt(numberString[i]) * (3 - (i % 2) * 2);
		}

		return 10 - (result % 10);
	}
}

//Required to register for both browser and nodejs
function register(core){
	core.register(ITF14, /^ITF.?14$/i, 5);
}
export default register;
<commit_msg>Made ITF-14 ES6<commit_after>class ITF14{
	constructor(string){
		this.string = string;

		// Add checksum if it does not exist
		if(string.search(/^[0-9]{13}$/) !== -1){
			this.string += this.checksum(string);
		}

		this.binaryRepresentation = {
			 "0":"00110"
			,"1":"10001"
			,"2":"01001"
			,"3":"11000"
			,"4":"00101"
			,"5":"10100"
			,"6":"01100"
			,"7":"00011"
			,"8":"10010"
			,"9":"01010"
		};
	}

	valid(){
		return this.string.search(/^[0-9]{14}$/) !== -1 &&
			this.string[13] == this.checksum();
	}

	encode(){
		var result = "1010";

		//Calculate all the digit pairs
		for(var i=0;i<14;i+=2){
			result += this.calculatePair(this.string.substr(i,2));
		}

		//Always add the same end bits
		result += "11101";

		return {
			data: result,
			text: this.string
		};
	}

	//Calculate the data of a number pair
	calculatePair(numberPair){
		var result = "";

		var number1Struct = this.binaryRepresentation[numberPair[0]];
		var number2Struct = this.binaryRepresentation[numberPair[1]];

		//Take every second bit and add to the result
		for(var i=0;i<5;i++){
			result += (number1Struct[i]=="1") ? "111" : "1";
			result += (number2Struct[i]=="1") ? "000" : "0";
		}

		return result;
	}

	//Calulate the checksum digit
	checksum(){
		var result = 0;

		for(var i=0;i<13;i++){
				result += parseInt(this.string[i]) * (3 - (i % 2) * 2);
		}

		return 10 - (result % 10);
	}
}

//Required to register for both browser and nodejs
function register(core){
	core.register(ITF14, /^ITF.?14$/i, 5);
}
export default register;
<|endoftext|>


<commit_before>Ball.prototype = Object.create(THREE.Object3D.prototype);
Ball.prototype.constructor = Ball;

function Ball(scene, args) {
	THREE.Object3D.call(this);

	var radius = 0.5,
	segments = 6,
	rings = 6;

	this.speed = 0.1;

	// create the sphere's material
	// var sphereMaterial = new THREE.MeshPhongMaterial({color: 0xD43001, shading: THREE.SmoothShading});
	var sphereMaterial = new THREE.MeshLambertMaterial({color: 0xD43001});

	this.ball = new THREE.Mesh(
		new THREE.SphereGeometry(radius, segments, rings),
		sphereMaterial
	);

	// Position
	this.ball.position.x = 0;
    this.ball.position.y = 0;
    this.ball.position.z = -8;

	scene.add(this.ball);

	var root = this;

	var collidableMeshList = args.collidableMeshList;

	var ballDirX = 1, ballDirY = 1, ballDirZ = 1, ballSpeed = 0.1;

	scene.updatables.push(function(){

		//root.ball.position.x += root.speed;

		//root.ball.position.y += ballDirY * ballSpeed;

		// Collision detection
		/*
		var originPoint = root.ball.position.clone();
		for (var vertexIndex = 0; vertexIndex < root.ball.geometry.vertices.length; vertexIndex++)
		{
			var localVertex = root.ball.geometry.vertices[vertexIndex].clone();
			var globalVertex = localVertex.applyMatrix4( root.ball.matrix );
			var directionVector = globalVertex.sub( root.ball.position );

			var ray = new THREE.Raycaster( originPoint, directionVector.clone().normalize() );
			var collisionResults = ray.intersectObjects( collidableMeshList );
			if ( collisionResults.length > 0 && collisionResults[0].distance < directionVector.length() ) {
				console.log("Hit")
				ballDirX = -ballDirX;
			}
		}
		*/
		var newPosX = root.ball.position.x + (ballDirX * ballSpeed);
		var newPosZ = root.ball.position.z + (ballDirZ * ballSpeed);
		var newPosY = root.ball.position.y + (ballDirY * ballSpeed);

		var halfBoxHeight = (args.boxHeight / 2);
		var halfBoxWidth = (args.boxWidth / 2);
		var halfBoxDepth = (args.boxDepth / 2)

		// Keep in bounding box
		if (newPosX < (halfBoxWidth * -1)) {
			newPosX = (halfBoxWidth * -1);
			ballDirX = -ballDirX;
		}
		else if (newPosX > halfBoxWidth) {
			newPosX = halfBoxWidth;
			ballDirX = -ballDirX;
		}

		if (newPosZ < (halfBoxDepth * -1) + args.depthOffset) {
			newPosZ = (halfBoxDepth * -1) + args.depthOffset;
			ballDirZ = -ballDirZ;
		}
		else if (newPosZ > halfBoxDepth + args.depthOffset) {
			newPosZ = halfBoxDepth + args.depthOffset;
			ballDirZ = -ballDirZ;
		}

		if (newPosY < (halfBoxHeight * -1)) {
			newPosY = (halfBoxHeight * -1);
			ballDirY = -ballDirY;
		}
		else if (newPosY > halfBoxHeight) {
			newPosY = halfBoxHeight;
			ballDirY = -ballDirY;
		}

		root.ball.position.x = newPosX;
		root.ball.position.z = newPosZ;
		root.ball.position.y = newPosY;

	});

}
<commit_msg>Cleanup<commit_after>Ball.prototype = Object.create(THREE.Object3D.prototype);
Ball.prototype.constructor = Ball;

function Ball(scene, args) {
	THREE.Object3D.call(this);

	var radius = 0.5,
	segments = 6,
	rings = 6;

	this.speed = 0.1;

	// create the sphere's material
	// var sphereMaterial = new THREE.MeshPhongMaterial({color: 0xD43001, shading: THREE.SmoothShading});
	var sphereMaterial = new THREE.MeshLambertMaterial({color: 0xD43001});

	this.ball = new THREE.Mesh(
		new THREE.SphereGeometry(radius, segments, rings),
		sphereMaterial
	);

	// Position
	this.ball.position.x = 0;
    this.ball.position.y = 0;
    this.ball.position.z = -8;

	scene.add(this.ball);

	var root = this;

	var collidableMeshList = args.collidableMeshList;

	var ballSpeed = 0.1;

	this.resetStartPosition = function(){
		root.ballDirX = 1;
		root.ballDirY = 1;
		root.ballDirZ = -1;
		root.ballSpeed = 0.1;
	}

	this.resetStartPosition();

	scene.updatables.push(function(){

		// Collision detection
		/*
		var originPoint = root.ball.position.clone();
		for (var vertexIndex = 0; vertexIndex < root.ball.geometry.vertices.length; vertexIndex++)
		{
			var localVertex = root.ball.geometry.vertices[vertexIndex].clone();
			var globalVertex = localVertex.applyMatrix4( root.ball.matrix );
			var directionVector = globalVertex.sub( root.ball.position );

			var ray = new THREE.Raycaster( originPoint, directionVector.clone().normalize() );
			var collisionResults = ray.intersectObjects( collidableMeshList );
			if ( collisionResults.length > 0 && collisionResults[0].distance < directionVector.length() ) {
				console.log("Hit")
				ballDirX = -ballDirX;
			}
		}
		*/
		var newPosX = root.ball.position.x + (root.ballDirX * root.ballSpeed);
		var newPosZ = root.ball.position.z + (root.ballDirZ * root.ballSpeed);
		var newPosY = root.ball.position.y + (root.ballDirY * root.ballSpeed);

		var halfBoxHeight = (args.boxHeight / 2);
		var halfBoxWidth = (args.boxWidth / 2);
		var halfBoxDepth = (args.boxDepth / 2)

		// Keep in bounding box
		if (newPosX < (halfBoxWidth * -1)) {
			newPosX = (halfBoxWidth * -1);
			root.ballDirX = -root.ballDirX;
		}
		else if (newPosX > halfBoxWidth) {
			newPosX = halfBoxWidth;
			root.ballDirX = -root.ballDirX;
		}

		if (newPosZ < (halfBoxDepth * -1) + args.depthOffset) {
			newPosZ = (halfBoxDepth * -1) + args.depthOffset;
			root.ballDirZ = -root.ballDirZ;
		}
		else if (newPosZ > halfBoxDepth + args.depthOffset) {
			newPosZ = halfBoxDepth + args.depthOffset;
			root.ballDirZ = -root.ballDirZ;
		}

		if (newPosY < (halfBoxHeight * -1)) {
			newPosY = (halfBoxHeight * -1);
			root.ballDirY = -root.ballDirY;
		}
		else if (newPosY > halfBoxHeight) {
			newPosY = halfBoxHeight;
			root.ballDirY = -root.ballDirY;
		}

		root.ball.position.x = newPosX;
		root.ball.position.z = newPosZ;
		root.ball.position.y = newPosY;

	});

}
<|endoftext|>


<commit_before>define(["Ti/_/declare", "Ti/_/dom", "Ti/_/lang", "Ti/UI", "Ti/UI/View"], function(declare, dom, lang, UI, View) {

	var sessionId = Math.random(),historyStack = [],
		pageNum = 1,
		hist = window.history,
		POP_STATE_WAITING_FOR_OPERATION = -1,
		POP_STATE_UNDOING_OPERATION = -2,
		POP_STATE_PUSHING = -3,
		POP_STATE_REWINDING_HISTORY = -4,
		POP_STATE_RESETTING = -5,
		historyPopState = POP_STATE_WAITING_FOR_OPERATION,
		prefix = location.href.split("#")[0], // Strip off any hash incase the user reloaded the page and a hash currently exists
		widgetToClose;

	function pushToHistory(widget) {
		historyPopState = POP_STATE_PUSHING;
		historyStack.push(widget);
		location.href = prefix + "#" + widget.widgetId;
	}

	function removeFromHistory(widget, recursive) {
		if (historyPopState === POP_STATE_WAITING_FOR_OPERATION) {
			var historyStackIndex = historyStack.indexOf(widget);
			if (historyStackIndex !== -1) {
				historyStack.splice(historyStackIndex,recursive ? historyStack.length - historyStackIndex : 1);
				historyPopState = POP_STATE_REWINDING_HISTORY;
				hist.go(-historyStack.length - 1);
			}
		}
	}

	window.addEventListener("hashchange", function(e) {
		switch(historyPopState) {
			case POP_STATE_WAITING_FOR_OPERATION:
				// We need to undo the previous operation and redo it
				var listItem = window.location.href.split("#")[1];
				if (prefix === window.location.href) {
					listItem = historyStack[0].widgetId;
				}
				if (listItem) {
					var historyStackIndex = -1,
						historyStackLength = historyStack.length,
						widget;
					historyPopState = POP_STATE_UNDOING_OPERATION;
					for (var i = 0; i < historyStackLength; i++) {
						widget = historyStack[i];
						if (listItem === widget.widgetId) {
							historyStackIndex = i + 1;
							break;
						}
					}
					for (i = historyStackIndex; i < historyStackLength; i++) {
						historyStack[i].close();
					}
					widgetToClose = historyStack[historyStackIndex];
					hist.go(historyStackLength - historyStackIndex);
				}
				break;
			case POP_STATE_UNDOING_OPERATION:
				historyPopState = POP_STATE_WAITING_FOR_OPERATION;
				removeFromHistory(widgetToClose, true);
				break;
			case POP_STATE_PUSHING:
				historyPopState = POP_STATE_WAITING_FOR_OPERATION;
				break;
			case POP_STATE_REWINDING_HISTORY:
				historyPopState = POP_STATE_RESETTING;
				location.href = prefix + "#history_reset";
				break;
			case POP_STATE_RESETTING:
				historyPopState = 0;
				hist.back();
				break;
			default:
				if (historyPopState < historyStack.length) {
					var widget = historyStack[historyPopState++];
					location.href = prefix + "#" + widget.widgetId;
				} else {
					historyPopState = POP_STATE_WAITING_FOR_OPERATION;
				}
				break;
		}
	});

	return declare("Ti._.UI.SuperView", View, {

		constructor: function() {
			this.addEventListener("focus", lang.hitch(this, function() {
				this.setWindowTitle(this.title);
			}));
		},

		destroy: function() {
			this.close();
			View.prototype.destroy.apply(this, arguments);
		},

		open: function(args) {
			if (!this._opened) {
				this._opened = 1;
				UI._addWindow(this, 1).show();

				pushToHistory(this);

				this.fireEvent("open");
				this.fireEvent("focus", this._state);
			}
		},

		close: function(args) {
			if (this._opened) {
				this._opened = 0;
				UI._removeWindow(this);

				if (this === historyStack[historyStack.length - 1]) {
					var newTopWindow = historyStack[historyStack.length - 2];
					newTopWindow && this.setWindowTitle(newTopWindow.title);
				}
				if (historyPopState === POP_STATE_WAITING_FOR_OPERATION) {
					removeFromHistory(this);
				}

				this.fireEvent("close");
			}
		},

		setWindowTitle: function(title) {
			historyStack[historyStack.length - 1] === this && (document.title = title || require.config.project.name);
			return title;
		}

	});

});<commit_msg>[TIMOB-7566] Bug fix.<commit_after>define(["Ti/_/declare", "Ti/_/dom", "Ti/_/lang", "Ti/UI", "Ti/UI/View"], function(declare, dom, lang, UI, View) {

	var sessionId = Math.random(),historyStack = [],
		pageNum = 1,
		hist = window.history,
		POP_STATE_WAITING_FOR_OPERATION = -1,
		POP_STATE_UNDOING_OPERATION = -2,
		POP_STATE_PUSHING = -3,
		POP_STATE_REWINDING_HISTORY = -4,
		POP_STATE_RESETTING = -5,
		historyPopState = POP_STATE_WAITING_FOR_OPERATION,
		prefix = location.href.split("#")[0], // Strip off any hash incase the user reloaded the page and a hash currently exists
		widgetToClose;

	function pushToHistory(widget) {
		historyPopState = POP_STATE_PUSHING;
		historyStack.push(widget);
		location.href = prefix + "#" + widget.widgetId;
	}

	function removeFromHistory(widget, recursive) {
		if (historyPopState === POP_STATE_WAITING_FOR_OPERATION) {
			var historyStackIndex = historyStack.indexOf(widget);
			if (historyStackIndex !== -1) {
				historyStack.splice(historyStackIndex,recursive ? historyStack.length - historyStackIndex : 1);
				historyPopState = POP_STATE_REWINDING_HISTORY;
				hist.go(-historyStack.length - 1);
			}
		}
	}

	window.addEventListener("hashchange", function(e) {
		switch(historyPopState) {
			case POP_STATE_WAITING_FOR_OPERATION:
				// We need to undo the previous operation and redo it
				var listItem = window.location.href.split("#")[1];
				if (prefix === window.location.href) {
					listItem = historyStack[0].widgetId;
				}
				if (listItem) {
					var historyStackIndex = -1,
						historyStackLength = historyStack.length,
						widget;
					historyPopState = POP_STATE_UNDOING_OPERATION;
					for (var i = 0; i < historyStackLength; i++) {
						widget = historyStack[i];
						if (listItem === widget.widgetId) {
							historyStackIndex = i + 1;
							break;
						}
					}
					for (i = historyStackIndex; i < historyStackLength; i++) {
						historyStack[i].close();
					}
					widgetToClose = historyStack[historyStackIndex];
					hist.go(historyStackLength - historyStackIndex);
				}
				break;
			case POP_STATE_UNDOING_OPERATION:
				historyPopState = POP_STATE_WAITING_FOR_OPERATION;
				removeFromHistory(widgetToClose, true);
				break;
			case POP_STATE_PUSHING:
				historyPopState = POP_STATE_WAITING_FOR_OPERATION;
				break;
			case POP_STATE_REWINDING_HISTORY:
				historyPopState = POP_STATE_RESETTING;
				location.href = prefix + "#history_reset";
				break;
			case POP_STATE_RESETTING:
				historyPopState = 0;
				hist.back();
				break;
			default:
				if (historyPopState < historyStack.length) {
					var widget = historyStack[historyPopState++];
					location.href = prefix + "#" + widget.widgetId;
				} else {
					historyPopState = POP_STATE_WAITING_FOR_OPERATION;
				}
				break;
		}
	});

	return declare("Ti._.UI.SuperView", View, {

		constructor: function() {
			this.addEventListener("focus", lang.hitch(this, function() {
				this.setWindowTitle(this.title);
			}));
		},

		destroy: function() {
			this.close();
			View.prototype.destroy.apply(this, arguments);
		},

		open: function(args) {
			if (!this._opened) {
				this._opened = 1;
				UI._addWindow(this, 1).show();

				pushToHistory(this);

				this.fireEvent("open");
				this.fireEvent("focus", this._state);
			}
		},

		close: function(args) {
			if (this._opened) {
				this._opened = 0;
				UI._removeWindow(this);

				if (this === historyStack[historyStack.length - 1]) {
					var newTopWindow = historyStack[historyStack.length - 2];
					newTopWindow && this.setWindowTitle(newTopWindow.title);
				}
				if (historyPopState === POP_STATE_WAITING_FOR_OPERATION) {
					removeFromHistory(this);
				}

				this.fireEvent("close");
			}
		},

		setWindowTitle: function(title) {
			historyStack[historyStack.length - 1] === this && (document.title = title || require.config.app.name);
			return title;
		}

	});

});<|endoftext|>


<commit_before>/**
 * Example of how to create and publish an asset for sale.
 *
 * @author Manu Sporny
 *
 * BSD 3-Clause License
 * Copyright (c) 2011-2012 Digital Bazaar, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 *
 * Neither the name of the Digital Bazaar, Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
var async = require('async');
var program = require('commander');
var config = require('./config.js');
var payswarm = require('../lib/payswarm-client.js');
var path = require('path');
var fs = require('fs');
var querystring = require('querystring');
var request = require('request');

var assetRegistration = {};

assetRegistration.run = function() {
  var assetId = new Date().getTime().toString(16);
  program
    .version('1.0.0')
    // setup the command line options
    .option('--config <configfile>',
      'The configuration containing public/private keys (default: payswarm.cfg).')
    .option('--asset-name <title>',
      'The asset name (default: \'Test Asset ' + assetId + '\').')
    .option('--price <dollars>',
      'The price (in dollars) of the asset (default: 0.05).')
    .option('--listing-service <listing_url>',
      'The base URL for the listing service (default: http://listings.dev.payswarm.com/)')
    .option('--verbose',
      'Print more detailed program status updates (default: false).')
    .parse(process.argv);

  // initialize settings
  var cfgFile = program.config || 'payswarm.cfg';
  var cfg = {};
  var assetName = program.assetName || 'Test Asset ' + assetId;
  var price = program.price || '0.05';
  var listingService = program.listingService || 'http://listings.dev.payswarm.com/';
  var verbose = program.verbose || false;

  // generate the asset and listing validity dates (use the same ones in
  // this simple example, but an asset may have a validity range that is
  // larger than the listing's)
  var validFrom = new Date();
  var validUntil = new Date();
  validUntil.setFullYear(validFrom.getFullYear() + 1);

  /*
   * To publish an asset for sale, the following steps must be performed:
   *
   * 1. Create and digitally sign the asset.
   * 2. Create and digitally sign the listing.
   * 3. Publish the asset and listing data to the Web.
   */
  async.waterfall([
    function(callback) {
      // read the config file from disk
      config.readConfigFile(cfgFile, callback);
    },
    function(newCfg, callback) {
      cfg = newCfg;
      // Step #1: Create the asset and digitally sign it
      console.log("Generating asset...");
      var assetUrl = listingService + 'payswarm.js/' + assetId;
      var asset = {
        '@context': 'https://w3id.org/payswarm/v1',
        id: assetUrl + '#asset',
        type: ['Asset', 'pto:WebPage'],
        creator: {
          fullName: 'publish-asset-for-sale.js Example'
        },
        title: assetName,
        assetContent: assetUrl,
        assetProvider: cfg.owner,
        listingRestrictions: {
          vendor: cfg.owner,
          validFrom: payswarm.w3cDate(validFrom),
          validUntil: payswarm.w3cDate(validUntil)
        }
      };

      // sign the asset
      payswarm.sign(asset, {
        publicKeyId: cfg.publicKey.id,
        privateKeyPem: cfg.publicKey.privateKeyPem
      }, callback);
    },
    function(signedAsset, callback) {
      // generate a hash for the signed asset
      payswarm.hash(signedAsset, function(err, assetHash) {
        callback(err, signedAsset, assetHash);
      });
    },
    function(signedAsset, assetHash, callback) {
      // Step #2: Create and digitally sign the listing
      console.log('Generating listing...');
      var listingUrl = listingService + 'payswarm.js/' + assetId;

      var listing = {
        '@context': 'https://w3id.org/payswarm/v1',
        id: listingUrl + '#listing',
        type: ['Listing', 'gr:Offering'],
        vendor: cfg.owner,
        payee: [{
          id: listingUrl + '#listing-payee-1',
          type: 'Payee',
          destination: cfg.source,
          currency: 'USD',
          payeeGroup: ['vendor'],
          payeeRate: price,
          payeeRateType: 'FlatAmount',
          payeeApplyType: 'ApplyExclusively',
          comment: 'Payment for Test Asset ' + assetId + '.'
        }],
        payeeRule : [{
          type: 'PayeeRule',
          payeeGroupPrefix: ['authority'],
          maximumPayeeRate: '10.0000000',
          payeeRateType: 'Percentage',
          payeeApplyType: 'ApplyInclusively'
        }],
        asset: listingUrl + '#asset',
        assetHash: assetHash,
        license: 'https://w3id.org/payswarm/licenses/blogging',
        licenseHash: 'urn:sha256:' +
          'd9dcfb7b3ba057df52b99f777747e8fe0fc598a3bb364e3d3eb529f90d58e1b9',
        validFrom: payswarm.w3cDate(validFrom),
        validUntil: payswarm.w3cDate(validUntil)
      };

      // sign the listing
      payswarm.sign(listing, {
        publicKeyId: cfg.publicKey.id,
        privateKeyPem: cfg.publicKey.privateKeyPem
      }, function(err, signedListing) {
        callback(err, signedAsset, signedListing);
      });
    },
    function(signedAsset, signedListing, callback) {
      // Step #3: Register the signed asset and listing
      var assetAndListing = {
        '@context': 'https://w3id.org/payswarm/v1',
        '@graph': [signedAsset, signedListing]
      };

      var url = signedListing.id.split('#')[0];
      payswarm.postJsonLd(url, assetAndListing, function(err, result) {
        callback(err, assetAndListing);
      });
    },
    function(assetAndListing, callback) {
      // display registration details
      if(verbose) {
        console.log('Registered signed asset and listing: ' +
          JSON.stringify(assetAndListing, null, 2));
      }
      else {
        console.log('Registered signed asset:\n   ',
          assetAndListing['@graph'][0].id);
        console.log('Registered signed listing:\n   ',
          assetAndListing['@graph'][1].id);
      }
      callback(null);
    }
  ], function(err) {
    if(err) {
      console.log('Failed to register signed asset and listing:',
        err.toString());
    }
  });
};

// log uncaught exception and exit
process.on('uncaughtException', function(err) {
  console.log(err.toString(), err.stack ? {stack: err.stack} : null);
  process.removeAllListeners('uncaughtException');
  process.exit();
});

// run the program
assetRegistration.run();
<commit_msg>Add asset payee and payee rule restrictions in example.<commit_after>/**
 * Example of how to create and publish an asset for sale.
 *
 * @author Manu Sporny
 *
 * BSD 3-Clause License
 * Copyright (c) 2011-2012 Digital Bazaar, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 *
 * Neither the name of the Digital Bazaar, Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
var async = require('async');
var program = require('commander');
var config = require('./config.js');
var payswarm = require('../lib/payswarm-client.js');
var path = require('path');
var fs = require('fs');
var querystring = require('querystring');
var request = require('request');

var assetRegistration = {};

assetRegistration.run = function() {
  var assetId = new Date().getTime().toString(16);
  program
    .version('1.0.0')
    // setup the command line options
    .option('--config <configfile>',
      'The configuration containing public/private keys (default: payswarm.cfg).')
    .option('--asset-name <title>',
      'The asset name (default: \'Test Asset ' + assetId + '\').')
    .option('--price <dollars>',
      'The price (in dollars) of the asset (default: 0.05).')
    .option('--listing-service <listing_url>',
      'The base URL for the listing service (default: http://listings.dev.payswarm.com/)')
    .option('--verbose',
      'Print more detailed program status updates (default: false).')
    .parse(process.argv);

  // initialize settings
  var cfgFile = program.config || 'payswarm.cfg';
  var cfg = {};
  var assetName = program.assetName || 'Test Asset ' + assetId;
  var price = program.price || '0.05';
  var listingService = program.listingService || 'http://listings.dev.payswarm.com/';
  var verbose = program.verbose || false;

  // generate the asset and listing validity dates (use the same ones in
  // this simple example, but an asset may have a validity range that is
  // larger than the listing's)
  var validFrom = new Date();
  var validUntil = new Date();
  validUntil.setFullYear(validFrom.getFullYear() + 1);

  /*
   * To publish an asset for sale, the following steps must be performed:
   *
   * 1. Create and digitally sign the asset.
   * 2. Create and digitally sign the listing.
   * 3. Publish the asset and listing data to the Web.
   */
  async.waterfall([
    function(callback) {
      // read the config file from disk
      config.readConfigFile(cfgFile, callback);
    },
    function(newCfg, callback) {
      cfg = newCfg;
      // Step #1: Create the asset and digitally sign it
      console.log("Generating asset...");
      var assetUrl = listingService + 'payswarm.js/' + assetId;
      var asset = {
        '@context': 'https://w3id.org/payswarm/v1',
        id: assetUrl + '#asset',
        type: ['Asset', 'pto:WebPage'],
        creator: {
          fullName: 'publish-asset-for-sale.js Example'
        },
        title: assetName,
        assetContent: assetUrl,
        assetProvider: cfg.owner,
        listingRestrictions: {
          vendor: cfg.owner,
          validFrom: payswarm.w3cDate(validFrom),
          validUntil: payswarm.w3cDate(validUntil),
          payee: [{
            id: assetUrl + '#asset-payee-1',
            type: 'Payee',
            destination: cfg.source,
            currency: 'USD',
            payeeGroup: ['assetProvider'],
            payeeRate: '80',
            payeeRateType: 'Percentage',
            payeeApplyType: 'ApplyInclusively',
            payeeApplyGroup: ['vendor'],
            minimumAmount: '0.01',
            comment: 'Asset Provider Royalty'
          }],
          payeeRule: [{
            type: 'PayeeRule',
            payeeGroupPrefix: ['authority']
          }, {
            type: 'PayeeRule',
            payeeGroup: ['vendor'],
            payeeRateType: 'FlatAmount',
            payeeApplyType: 'ApplyExclusively'
          }]
        }
      };

      // sign the asset
      payswarm.sign(asset, {
        publicKeyId: cfg.publicKey.id,
        privateKeyPem: cfg.publicKey.privateKeyPem
      }, callback);
    },
    function(signedAsset, callback) {
      // generate a hash for the signed asset
      payswarm.hash(signedAsset, function(err, assetHash) {
        callback(err, signedAsset, assetHash);
      });
    },
    function(signedAsset, assetHash, callback) {
      // Step #2: Create and digitally sign the listing
      console.log('Generating listing...');
      var listingUrl = listingService + 'payswarm.js/' + assetId;

      var listing = {
        '@context': 'https://w3id.org/payswarm/v1',
        id: listingUrl + '#listing',
        type: ['Listing', 'gr:Offering'],
        vendor: cfg.owner,
        payee: [{
          id: listingUrl + '#listing-payee-1',
          type: 'Payee',
          destination: cfg.source,
          currency: 'USD',
          payeeGroup: ['vendor'],
          payeeRate: price,
          payeeRateType: 'FlatAmount',
          payeeApplyType: 'ApplyExclusively',
          comment: 'Payment for selling Test Asset ' + assetId + '.'
        }],
        payeeRule : [{
          type: 'PayeeRule',
          payeeGroupPrefix: ['authority'],
          maximumPayeeRate: '10',
          payeeRateType: 'Percentage',
          payeeApplyType: 'ApplyInclusively'
        }],
        asset: listingUrl + '#asset',
        assetHash: assetHash,
        license: 'https://w3id.org/payswarm/licenses/blogging',
        licenseHash: 'urn:sha256:' +
          'd9dcfb7b3ba057df52b99f777747e8fe0fc598a3bb364e3d3eb529f90d58e1b9',
        validFrom: payswarm.w3cDate(validFrom),
        validUntil: payswarm.w3cDate(validUntil)
      };

      // sign the listing
      payswarm.sign(listing, {
        publicKeyId: cfg.publicKey.id,
        privateKeyPem: cfg.publicKey.privateKeyPem
      }, function(err, signedListing) {
        callback(err, signedAsset, signedListing);
      });
    },
    function(signedAsset, signedListing, callback) {
      // Step #3: Register the signed asset and listing
      var assetAndListing = {
        '@context': 'https://w3id.org/payswarm/v1',
        '@graph': [signedAsset, signedListing]
      };

      var url = signedListing.id.split('#')[0];
      payswarm.postJsonLd(url, assetAndListing, function(err, result) {
        callback(err, assetAndListing);
      });
    },
    function(assetAndListing, callback) {
      // display registration details
      if(verbose) {
        console.log('Registered signed asset and listing: ' +
          JSON.stringify(assetAndListing, null, 2));
      }
      else {
        console.log('Registered signed asset:\n   ',
          assetAndListing['@graph'][0].id);
        console.log('Registered signed listing:\n   ',
          assetAndListing['@graph'][1].id);
      }
      callback(null);
    }
  ], function(err) {
    if(err) {
      console.log('Failed to register signed asset and listing:',
        err.toString());
    }
  });
};

// log uncaught exception and exit
process.on('uncaughtException', function(err) {
  console.log(err.toString(), err.stack ? {stack: err.stack} : null);
  process.removeAllListeners('uncaughtException');
  process.exit();
});

// run the program
assetRegistration.run();
<|endoftext|>


<commit_before>/* global rm, mkdir, exec, ls, cp */
require('shelljs/global');
var fs = require('fs');
var ms = require('ms');

var start = new Date();

console.log('Cleaning output directory "dist/"...');
rm('-rf', 'dist');
mkdir('-p', 'dist');

var entry = './app/main.prod.js';

console.log('Building app from "' + entry + '"...');
exec('webpack --entry \'' + entry + '\' --output-filename \'bundle.[hash].js\' --devtool source-map --colors --progress');

var end = new Date();
console.log('App built in ' + ms(end - start));
<commit_msg>Webpack minification for production builds<commit_after>/* global rm, mkdir, exec, ls, cp */
require('shelljs/global');
var fs = require('fs');
var ms = require('ms');

var start = new Date();

console.log('Cleaning output directory "dist/"...');
rm('-rf', 'dist');
mkdir('-p', 'dist');

var entry = './app/main.prod.js';

console.log('Building app from "' + entry + '"...');
exec('webpack --entry \'' + entry + '\' --output-filename \'bundle.[hash].js\' --devtool source-map --colors --progress --optimize-minimize');

var end = new Date();
console.log('App built in ' + ms(end - start));
<|endoftext|>


<commit_before>
/**
 *
 * Base panel. A lot of them will exist here, with some common properties.
 * Each class that extends pvc.base will be responsible to know how to use it
 *
 */
pvc.DataEngine = Base.extend({

  chart: null,
  metadata: null,
  resultset: null,
  seriesInRows: false,
  crosstabMode: true,
  translator: null,

  constructor: function(chart,metadata, resultset){

    this.chart = chart;
    this.metadata = metadata;
    this.resultset = resultset;

  },

  createTranslator: function(){

    // Create the appropriate translator
    if(this.crosstabMode){
      this.translator = new pvc.CrosstabTranslator();
    }
    else{
      this.translator = new pvc.RelationalTranslator();
    }

    this.translator.setTranspose(this.seriesInRows);
    this.translator.setData(this.metadata, this.resultset);

  },

  getInfo: function(){

    var out = "------------------------------------------\n";
    out+= "Dataset Information\n";

    out+= "  Series ( "+ this.getSeries().length +"   ): " + this.getSeries().slice(0,10) +"\n";
    out+= "  Categories ( "+ this.getCategories().length +"   ): " + this.getCategories().slice(0,10) +"\n";
    out+= "------------------------------------------\n";

    return out;

  },

  setCrosstabMode: function(crosstabMode){
    this.crosstabMode = crosstabMode;
  },

  isCrosstabMode: function(){
    return this.crosstabMode;
  },

  setSeriesInRows: function(seriesInRows){
    this.seriesInRows = seriesInRows;
  },

  isSeriesInRows: function(){
    return this.seriesInRows;
  }

});

pvc.DataTranslator = Base.extend({

  series: [],
  categories: [],
  values: [],
  metadata: null,
  resultset: null,
  transpose: false,

  constructor: function(data){
    this.transformData(data);
  },

  setData: function(metadata, resultset){
    this.metadata = metadata;
    this.resultset = resultset;
  },

  setTranspose: function(transpose){

    this.transpose = transpose;
  },

  getSeries: function(){
    return this.series;

  },

  getCategories: function(){
    return this.categories;
  },

  getSeriesSize: function(){
    return this.series.length;

  },

  getCategoriesSize: function(){
    return this.categories.length;
  },

  getValues: function(){
    return this.values;
  }

})<commit_msg>- implemented first version of CrosstabTranslator<commit_after>
/**
 *
 * Base panel. A lot of them will exist here, with some common properties.
 * Each class that extends pvc.base will be responsible to know how to use it
 *
 */
pvc.DataEngine = Base.extend({

  chart: null,
  metadata: null,
  resultset: null,
  seriesInRows: false,
  crosstabMode: true,
  translator: null,

  constructor: function(chart,metadata, resultset){

    this.chart = chart;
    this.metadata = metadata;
    this.resultset = resultset;

  },

  createTranslator: function(){

    // Create the appropriate translator
    if(this.crosstabMode){
      this.translator = new pvc.CrosstabTranslator();
    }
    else{
      this.translator = new pvc.RelationalTranslator();
    }

    this.translator.setTranspose(this.seriesInRows);
    this.translator.setData(this.metadata, this.resultset);

  },

  getInfo: function(){

    var out = "------------------------------------------\n";
    out+= "Dataset Information\n";

    out+= "  Series ( "+ this.getSeriesSize() +" ): " + this.getSeries().slice(0,10) +"\n";
    out+= "  Categories ( "+ this.getCategoriesSize() +" ): " + this.getCategories().slice(0,10) +"\n";
    out+= "------------------------------------------\n";

    return out;

  },

  getSeries: function(){
    return this.translator.getSeries();
  },

  getCategories: function(){
    return this.translator.getCategories();
  },

  getSeriesSize: function(){
    return this.translator.getSeries().length;
  },

  getCategoriesSize: function(){
    return this.translator.getCategories().length;
  },

  setCrosstabMode: function(crosstabMode){
    this.crosstabMode = crosstabMode;
  },

  isCrosstabMode: function(){
    return this.crosstabMode;
  },

  setSeriesInRows: function(seriesInRows){
    this.seriesInRows = seriesInRows;
  },

  isSeriesInRows: function(){
    return this.seriesInRows;
  }

});

pvc.DataTranslator = Base.extend({

  series: [],
  categories: [],
  values: [],
  metadata: null,
  resultset: null,
  transpose: false,

  constructor: function(){
  },

  setData: function(metadata, resultset){
    this.metadata = metadata;
    this.resultset = resultset;
  },

  setTranspose: function(transpose){

    this.transpose = transpose;
  },

  getSeries: function(){
    return this.transpose?this.getRows():this.getColumns();
  },

  getCategories: function(){
    return this.transpose?this.getColumns():this.getRows();
  },

  getValues: function(){
    return this.values;
  },

  getColumns: function(){
  // override me
  },

  getRows: function(){
  // override me
  }

})

pvc.CrosstabTranslator = pvc.DataTranslator.extend({

  getColumns: function(){

    // In crosstab mode, series are on the metadata, skipping first row
    return this.metadata.slice(1).map(function(d){
      return d.colName;
    })

  },

  getRows: function(){

    return this.resultset.map(function(d){
      return d[0];
    })
  }

});

pvc.RelationalTranslator = pvc.DataTranslator.extend({

  });<|endoftext|>


<commit_before>/**
 * todos
 */

var $ = require('jquery');
var NProgress = require('nprogress-183');
require('jquery-pjax-183');

function initPjax() {
    $(document).pjax('a', '#pjax-container');

    $(document).on('pjax:start', function() {
        NProgress.start();
    });

    $(document).on('pjax:end', function() {
        NProgress.done();
    });
}

var $newTodoInput = $("#new-todo");

var actions = {
    toggleAll: {
        url: '/todos/toggleall',
        method: 'PUT'
    },
    add: {
        url: '/todo',
        method: 'POST',
        data: {
            todo: $newTodoInput.val()
        }
    },
    edit: {
        url: '/todo/',
        method: 'PUT',
        event: ev: function(elem) {
            this.url += elem.parents('li').attr('data-id');
        },
        callback: function() {}
    },
    remove: {
        url: '/todo',
        method: 'DELETE',
        ev: function() {},
        callback: function() {}
    },
    clearCompleted: {
        url: '/todos/completed',
        method: 'DELETE',
        ev: function() {},
        callback: function() {}
    },
    completed: {
        url: '/todo/',
        method: 'PUT',
        ev: function() {},
        callback: function() {}
    },
    input: {
        ev: function() {}
    }
}

function initArr() {

}

function send() {

}<commit_msg>加了一些操作<commit_after>/**
 * todos
 */

var $ = require('jquery');
var NProgress = require('nprogress-183');
require('jquery-pjax-183');

function initPjax() {
    $(document).pjax('a', '#pjax-container');

    $(document).on('pjax:start', function() {
        NProgress.start();
    });

    $(document).on('pjax:end', function() {
        NProgress.done();
    });
}

var $newTodoInput = $("#new-todo"), //新建一个todo
    $listLi = $("#todo-list li"), //列表单元
    $listToggle = $("#todo-list .togggle"), //切换todo状态
    $listLiEdit = $("#todo-list .edit"), //编辑输入
    $toggleall = $("#toggle-all"), //切换所有的todo状态
    $listDestroy = $("#todo-list .destroy"), //删除todo
    $clearCompleted = $("#clear-completed"); //清除完成的

var actions = {
    toggleAll: {
        url: '/todos/toggleall',
        method: 'PUT'
    },
    add: {
        url: '/todo',
        method: 'POST',
        data: {
            todo: $newTodoInput.val()
        }
    },
    edit: {
        url: '/todo/',
        method: 'PUT',
        ev: function(elem) {
            this.url += elem.attr('data-id');
            var state = elem.find('.togggle').attr('checked') ? 1 : 0;
            this.data = {
                todo: elem.find('label').text(),
                state: state
            }
        },
        callback: function() {}
    },
    remove: {
        url: '/todo',
        method: 'DELETE',
        ev: function() {},
        callback: function() {}
    },
    clearCompleted: {
        url: '/todos/completed',
        method: 'DELETE',
        ev: function() {},
        callback: function() {}
    },
    completed: {
        url: '/todo/',
        method: 'PUT',
        ev: function() {},
        callback: function() {}
    },
    input: {
        ev: function() {}
    }
}

function initArr() {

}

function send() {

}<|endoftext|>