<commit_before>// tempart templating library

;(function(tempartCompiler) {
	////-----------------------------------------------------------------------------------------
	// you need to overwrite this function, to have working partial support
	tempartCompiler.partial = function(block, context, currentValues, dirties, path ){
		// @TODO do a better api for that..
		console.error('Overwrite the function tempartCompiler.partial to have partials');
		return '';
	};
	////-----------------------------------------------------------------------------------------
	// returns the html and adds context to currentValues
	// path is not used, it only is passed to partial
	tempartCompiler.compile = function( blocks, content, currentValues, dirties, path, prefix ){
		if(!prefix) prefix = '';
		var local = {};
		return this._handleBlocks(blocks, content, local, currentValues, this._batchDirties( dirties ), path, prefix);
	};
	////-----------------------------------------------------------------------------------------
	// batches the dirties
	tempartCompiler._batchDirties = function( dirties ){
		if( dirties === '*' ) return dirties;
		var result = {};
		var batchMap = {push: 'append', unshift: 'prepend'};
		// @TODO update / remove
		for( var key in dirties ){
			if( dirties.hasOwnProperty( key )){
				var dirty = dirties[ key ];
				result[key] = {append: [], prepend: []};
				for( var i = 0; i < dirty.length; i++ ){
					var entity = dirty[ i ];
					result[ key ][ batchMap[ entity.type ]].push( entity.value );
				}
			}
		}
		return result;
	};

	////-----------------------------------------------------------------------------------------
	// iterates threw the block on one level and calls the type-handler
	tempartCompiler._handleBlocks = function( blocks, content, local, currentValues, dirties, path, prefix ){
		var result = "";
		for( var i = 0; i < blocks.length; i++ ){
			result += this._handleBlock( blocks[i], content, local, currentValues, dirties, path, prefix );
		}
		return result;
	};
	////-----------------------------------------------------------------------------------------
	// returns the compiled block, depending on the inserted data
	tempartCompiler._handleBlock = function( block, content, local, currentValues, dirties, path, prefix ){
		var detailPrefix = prefix + this.types.executes.options.prefixDelimiter + block.id;
		if(block.type === 'log') { // No need for pre and suffix at an log
			return this.types[block.type]( block, content, local, currentValues, dirties, path, prefix );
		} else {
			if( dirties === '*' ){
				return this.types.executes.prefix( detailPrefix ) + this.types[ block.type ]( block, content, local, currentValues, dirties, path, prefix ) + this.types.executes.suffix( detailPrefix );
			} else {
				return this.types.dirties[ block.type ]( block, content, local, currentValues, dirties, path, prefix );
			}
		}

	};

	////-----------------------------------------------------------------------------------------
	// Contains the possible handlers
	tempartCompiler.types = {
		////-----------------------------------------------------------------------------------------
		// returns a variable
		variable: function( block, content, local, currentValues, dirties ){
			var value = this.executes.get(block.depending[ 0 ], content, local );
			currentValues[ block.id ] = value;
			return value;
		},
		////-----------------------------------------------------------------------------------------
		// returns html
		echo: function( block, content, local, currentValues, dirties ){
			return block.content;
		},
		////-----------------------------------------------------------------------------------------
		// calls handleBlocks depending on the data contributed
		if: function( block, content, local, currentValues, dirties, path, prefix ) {
			var type   = 'elseContains';
			if(this.executes.get(block.depending[ 0 ], content, local )) {
				type   = 'contains';
			}

			if( dirties != '*' && currentValues[ block.id ] != type) {
				throw 'Not yet implemented';
			} else {
				currentValues[ block.id ] = type;
			}
			prefix += this.executes.options.prefixDelimiter + block.id;

			return tempartCompiler._handleBlocks(block[type], content, local, currentValues, dirties, path, prefix);
		},
		////-----------------------------------------------------------------------------------------
		// sets a variable of an array and calls handleBlocks in the containing level
		each: function( block, content, local, currentValues, dirties, path, prefix ) {
			var value = this.executes.get(block.depending[ 0 ], content, local );
			currentValues[block.id] = {values: {}, order: []};

			if( value && value.length ){
				var result = "";
				for(var i = 0; i < value.length; i++) {
					var rand = this.executes.random();
					currentValues[ block.id ].values[ rand ] = {};
					currentValues[block.id].order.push( rand );
					var detailPrefix = prefix + this.executes.options.prefixDelimiter + block.id + ':' + rand;
					this.executes.set( block.depending[2], value[i], local );
					result += tempartCompiler._handleBlocks( block.contains, content, local, currentValues[ block.id ].values[ rand ], dirties, path, detailPrefix );
				}
				return result;
			} else {
				var elsePrefix = prefix + this.executes.options.prefixDelimiter + block.id;
				return tempartCompiler._handleBlocks( block.elseContains, content, local, currentValues, dirties, path, elsePrefix);
			}
		},
		////-----------------------------------------------------------------------------------------
		// puts values in the console
		log: function(block, content, local) {
			console.log( this.executes.get(block.depending[ 0 ], content, local ));
			return "";
		},
		////-----------------------------------------------------------------------------------------
		// patial handler, for rewriting contexts and stuff
		partial: function( block, content, local, currentValues, dirties, path ) {
			if(block.path !== '/') {
				path = path + '/' + block.path;
			}
			return tempartCompiler.partial(block, content, currentValues, dirties, path);
		},
		executes: {
			////-----------------------------------------------------------------------------------------
			// Executables are in need of options too!
			options: {
				domNode:   'script',
				attrStart: 'tempartStart',
				attrEnd: 'tempartEnd',
				prefixDelimiter: '-'
			},
			////-----------------------------------------------------------------------------------------
			// Checks if something is in the local space
			get: function( key, global, local ){
				if( local.hasOwnProperty( key )){
					return local[ key ];
				} else {
					return this._get( key.split( '.' ), global );
				}
			},
			////-----------------------------------------------------------------------------------------
			// handles dotnotation for getting values
			_get: function( keyParts, global) {
				var firstKey = keyParts.shift();
				if(!keyParts.length) {

					return global[ firstKey ];
				} else {
					return this.get( keyParts, value, global[ firstKey ] );
				}
			},
			////-----------------------------------------------------------------------------------------
			// sets things in the local space, we dont want to manipulate the original object
			set: function( key, value, scope ){
				scope[ key ] = value;
			},
			unset: function( key, scope ){
				delete scope[key];
			},
			prefix: function( prefix ){
				return '<' +this.options.domNode+ ' ' +this.options.attrStart+ '="' +prefix + '"></' +this.options.domNode+ '>';
			},
			suffix: function( suffix ){
				// debugger;
				return '<' +this.options.domNode+ ' ' +this.options.attrEnd+ '="' +suffix + '"></' +this.options.domNode+ '>';
			},
			random: function() {
				return Math.random().toString(36).substring(7);
			}
		},
		dirties: {
			////-----------------------------------------------------------------------------------------
			// only changed values should be iterated, or when in contains dependings something changed
			each: function( block, content, local, currentValues, dirties, path, prefix ){
				var previous = currentValues[ block.id ];
				var key = block.depending[ 0 ];
				if( dirties[ key ] !== undefined ){
					var types = ['prepend', 'append'];
					for( var i = 0; i < types.length; i++ ){
						var type  = types[ i ];
						var value = dirties[ key ][ type ];
						if( value.length ){
							tempartCompiler.types.executes.set( key, value, local );
							var tmpCurrentValues = {};
							var result = tempartCompiler.types[ block.type ]( block, content, local, tmpCurrentValues, '*', path, prefix );
							for( var orderIndex = 0; orderIndex < tmpCurrentValues[ block.id ].order.length; orderIndex++ ) {
								var rand = null;
								if( type == 'append' ){
									rand =  tmpCurrentValues[ block.id ].order[ orderIndex ];
									currentValues[ block.id ].order.push( rand );
								} else {
									var order = tmpCurrentValues[ block.id ].order;
									rand =  order[ order.length - orderIndex - 1];
									currentValues[ block.id ].order.unshift( rand );
								}
								currentValues[ block.id ].values[ rand ] = tmpCurrentValues[ block.id ].values[ rand ];
							}
							tempartCompiler.dom[ type ]( prefix + tempartCompiler.types.executes.options.prefixDelimiter + block.id, result );
							tempartCompiler.types.executes.unset( key, local ); // @FIXME is this actually needed?
						}
					}
				} else {
					// @TODO searchblocks
					throw "Not yet implemented";
				}

			},
			////-----------------------------------------------------------------------------------------
			// checks if a variable changed
			variable: function( block, content, local, currentValues, dirties, path, prefix ){
				var previous = currentValues[ block.id ];
				var now      = tempartCompiler.types[ block.type ]( block, content, local, currentValues, dirties );
				if( previous != now ){
					debugger;
				}
			},
			////-----------------------------------------------------------------------------------------
			// an echo of a constant never changes
			echo: function() {},
			////-----------------------------------------------------------------------------------------
			// only updates when something is different, or an contains depending changed
			// @TODO
			if: function() {

			},
			////-----------------------------------------------------------------------------------------
			// I actually don't know what exactly will happen here, some dependencieneeds to be done...
			// @TODO
			partial: function() {

			}
		},
	};

	tempartCompiler.dom = {
		prepend: function( prefix, html ){
			this.obj( prefix, tempartCompiler.types.executes.options.attrStart).after( html );
		},
		append: function( prefix, html ){
			this.obj( prefix, tempartCompiler.types.executes.options.attrEnd).before( html );
		},
		obj: function( prefix, attr ){
			return $('[' + attr + '=' + prefix + ']' );
		}
	};
}(typeof module == 'object' ? module.exports : window.tempartCompiler= {}));
<commit_msg>[dependencies] removed jquery dependency<commit_after>// tempart templating library

;(function(tempartCompiler) {
	////-----------------------------------------------------------------------------------------
	// you need to overwrite this function, to have working partial support
	tempartCompiler.partial = function(block, context, currentValues, dirties, path ){
		// @TODO do a better api for that..
		console.error('Overwrite the function tempartCompiler.partial to have partials');
		return '';
	};
	////-----------------------------------------------------------------------------------------
	// returns the html and adds context to currentValues
	// path is not used, it only is passed to partial
	tempartCompiler.compile = function( blocks, content, currentValues, dirties, path, prefix ){
		if(!prefix) prefix = '';
		var local = {};
		return this._handleBlocks(blocks, content, local, currentValues, this._batchDirties( dirties ), path, prefix);
	};
	////-----------------------------------------------------------------------------------------
	// batches the dirties
	tempartCompiler._batchDirties = function( dirties ){
		if( dirties === '*' ) return dirties;
		var result = {};
		var batchMap = {push: 'append', unshift: 'prepend'};
		// @TODO update / remove
		for( var key in dirties ){
			if( dirties.hasOwnProperty( key )){
				var dirty = dirties[ key ];
				result[key] = {append: [], prepend: []};
				for( var i = 0; i < dirty.length; i++ ){
					var entity = dirty[ i ];
					result[ key ][ batchMap[ entity.type ]].push( entity.value );
				}
			}
		}
		return result;
	};

	////-----------------------------------------------------------------------------------------
	// iterates threw the block on one level and calls the type-handler
	tempartCompiler._handleBlocks = function( blocks, content, local, currentValues, dirties, path, prefix ){
		var result = "";
		for( var i = 0; i < blocks.length; i++ ){
			result += this._handleBlock( blocks[i], content, local, currentValues, dirties, path, prefix );
		}
		return result;
	};
	////-----------------------------------------------------------------------------------------
	// returns the compiled block, depending on the inserted data
	tempartCompiler._handleBlock = function( block, content, local, currentValues, dirties, path, prefix ){
		var detailPrefix = prefix + this.types.executes.options.prefixDelimiter + block.id;
		if(block.type === 'log') { // No need for pre and suffix at an log
			return this.types[block.type]( block, content, local, currentValues, dirties, path, prefix );
		} else {
			if( dirties === '*' ){
				return this.types.executes.prefix( detailPrefix ) + this.types[ block.type ]( block, content, local, currentValues, dirties, path, prefix ) + this.types.executes.suffix( detailPrefix );
			} else {
				return this.types.dirties[ block.type ]( block, content, local, currentValues, dirties, path, prefix );
			}
		}

	};

	////-----------------------------------------------------------------------------------------
	// Contains the possible handlers
	tempartCompiler.types = {
		////-----------------------------------------------------------------------------------------
		// returns a variable
		variable: function( block, content, local, currentValues, dirties ){
			var value = this.executes.get(block.depending[ 0 ], content, local );
			currentValues[ block.id ] = value;
			return value;
		},
		////-----------------------------------------------------------------------------------------
		// returns html
		echo: function( block, content, local, currentValues, dirties ){
			return block.content;
		},
		////-----------------------------------------------------------------------------------------
		// calls handleBlocks depending on the data contributed
		if: function( block, content, local, currentValues, dirties, path, prefix ) {
			var type   = 'elseContains';
			if(this.executes.get(block.depending[ 0 ], content, local )) {
				type   = 'contains';
			}

			if( dirties != '*' && currentValues[ block.id ] != type) {
				throw 'Not yet implemented';
			} else {
				currentValues[ block.id ] = type;
			}
			prefix += this.executes.options.prefixDelimiter + block.id;

			return tempartCompiler._handleBlocks(block[type], content, local, currentValues, dirties, path, prefix);
		},
		////-----------------------------------------------------------------------------------------
		// sets a variable of an array and calls handleBlocks in the containing level
		each: function( block, content, local, currentValues, dirties, path, prefix ) {
			var value = this.executes.get(block.depending[ 0 ], content, local );
			currentValues[block.id] = {values: {}, order: []};

			if( value && value.length ){
				var result = "";
				for(var i = 0; i < value.length; i++) {
					var rand = this.executes.random();
					currentValues[ block.id ].values[ rand ] = {};
					currentValues[block.id].order.push( rand );
					var detailPrefix = prefix + this.executes.options.prefixDelimiter + block.id + ':' + rand;
					this.executes.set( block.depending[2], value[i], local );
					result += tempartCompiler._handleBlocks( block.contains, content, local, currentValues[ block.id ].values[ rand ], dirties, path, detailPrefix );
				}
				return result;
			} else {
				var elsePrefix = prefix + this.executes.options.prefixDelimiter + block.id;
				return tempartCompiler._handleBlocks( block.elseContains, content, local, currentValues, dirties, path, elsePrefix);
			}
		},
		////-----------------------------------------------------------------------------------------
		// puts values in the console
		log: function(block, content, local) {
			console.log( this.executes.get(block.depending[ 0 ], content, local ));
			return "";
		},
		////-----------------------------------------------------------------------------------------
		// patial handler, for rewriting contexts and stuff
		partial: function( block, content, local, currentValues, dirties, path ) {
			if(block.path !== '/') {
				path = path + '/' + block.path;
			}
			return tempartCompiler.partial(block, content, currentValues, dirties, path);
		},
		executes: {
			////-----------------------------------------------------------------------------------------
			// Executables are in need of options too!
			options: {
				domNode:   'script',
				attrStart: 'tempartStart',
				attrEnd: 'tempartEnd',
				prefixDelimiter: '-'
			},
			////-----------------------------------------------------------------------------------------
			// Checks if something is in the local space
			get: function( key, global, local ){
				if( local.hasOwnProperty( key )){
					return local[ key ];
				} else {
					return this._get( key.split( '.' ), global );
				}
			},
			////-----------------------------------------------------------------------------------------
			// handles dotnotation for getting values
			_get: function( keyParts, global) {
				var firstKey = keyParts.shift();
				if(!keyParts.length) {

					return global[ firstKey ];
				} else {
					return this.get( keyParts, value, global[ firstKey ] );
				}
			},
			////-----------------------------------------------------------------------------------------
			// sets things in the local space, we dont want to manipulate the original object
			set: function( key, value, scope ){
				scope[ key ] = value;
			},
			unset: function( key, scope ){
				delete scope[key];
			},
			prefix: function( prefix ){
				return '<' +this.options.domNode+ ' ' +this.options.attrStart+ '="' +prefix + '"></' +this.options.domNode+ '>';
			},
			suffix: function( suffix ){
				return '<' +this.options.domNode+ ' ' +this.options.attrEnd+ '="' +suffix + '"></' +this.options.domNode+ '>';
			},
			random: function() {
				return Math.random().toString(36).substring(7);
			}
		},
		dirties: {
			////-----------------------------------------------------------------------------------------
			// only changed values should be iterated, or when in contains dependings something changed
			each: function( block, content, local, currentValues, dirties, path, prefix ){
				var previous = currentValues[ block.id ];
				var key = block.depending[ 0 ];
				if( dirties[ key ] !== undefined ){
					var types = ['prepend', 'append'];
					for( var i = 0; i < types.length; i++ ){
						var type  = types[ i ];
						var value = dirties[ key ][ type ];
						if( value.length ){
							tempartCompiler.types.executes.set( key, value, local );
							var tmpCurrentValues = {};
							var result = tempartCompiler.types[ block.type ]( block, content, local, tmpCurrentValues, '*', path, prefix );
							for( var orderIndex = 0; orderIndex < tmpCurrentValues[ block.id ].order.length; orderIndex++ ) {
								var rand = null;
								if( type == 'append' ){
									rand =  tmpCurrentValues[ block.id ].order[ orderIndex ];
									currentValues[ block.id ].order.push( rand );
								} else {
									var order = tmpCurrentValues[ block.id ].order;
									rand =  order[ order.length - orderIndex - 1];
									currentValues[ block.id ].order.unshift( rand );
								}
								currentValues[ block.id ].values[ rand ] = tmpCurrentValues[ block.id ].values[ rand ];
							}
							tempartCompiler.dom[ type ]( prefix + tempartCompiler.types.executes.options.prefixDelimiter + block.id, result );
							tempartCompiler.types.executes.unset( key, local ); // @FIXME is this actually needed?
						}
					}
				} else {
					// @TODO searchblocks
					throw "Not yet implemented";
				}

			},
			////-----------------------------------------------------------------------------------------
			// checks if a variable changed
			variable: function( block, content, local, currentValues, dirties, path, prefix ){
				var previous = currentValues[ block.id ];
				var now      = tempartCompiler.types[ block.type ]( block, content, local, currentValues, dirties );
				if( previous != now ){
					debugger;
				}
			},
			////-----------------------------------------------------------------------------------------
			// an echo of a constant never changes
			echo: function() {},
			////-----------------------------------------------------------------------------------------
			// only updates when something is different, or an contains depending changed
			// @TODO
			if: function() {

			},
			////-----------------------------------------------------------------------------------------
			// I actually don't know what exactly will happen here, some dependencieneeds to be done...
			// @TODO
			partial: function() {

			}
		},
	};

	tempartCompiler.dom = {
		////-----------------------------------------------------------------------------------------
		// Puts the things where they belong
		prepend: function( prefix, html ){
			this.obj( prefix, tempartCompiler.types.executes.options.attrStart).insertAdjacentHTML( 'afterend', html );
		},
		////-----------------------------------------------------------------------------------------
		// Puts the things where they belong
		append: function( prefix, html ){
			this.obj( prefix, tempartCompiler.types.executes.options.attrEnd).insertAdjacentHTML( 'beforebegin', html );
		},
		////-----------------------------------------------------------------------------------------
		// Builds jquery-query
		// @FIXME change this to browser-behaviour to avoid dependency
		obj: function( prefix, attr ){
			var objs = document.querySelectorAll( '[' + attr + ']' );
			for(var i = 0; i < objs.length; i++) {
				var obj = objs[ i ];
				if( obj.getAttribute( attr ) === prefix ){
					return obj;
				}
			}
		}
	};
}(typeof module == 'object' ? module.exports : window.tempartCompiler= {}));
<|endoftext|>


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

/**
 * Object for actual element properties (symbol, radius, etc.)
 *
 * @author Jonathan Olson <olsonsjc@gmail.com>
 */

define( function( require ) {
  'use strict';

  var Atom = function( element ) {
    this.element = element;
    this.symbol = element.symbol;
    this.radius = element.radius;
    this.diameter = element.radius * 2;
    this.electronegativity = element.electronegativity;
    this.atomicWeight = element.atomicWeight;
    this.color = element.color;
  };

  Atom.prototype = {
    constructor: Atom,

    hasSameElement: function( atom ) {
      return this.element.isSameElement( atom.element );
    },

    isHydrogen: function() {
      return this.element.isHydrogen();
    },

    isCarbon: function() {
      return this.element.isCarbon();
    },

    isOxygen: function() {
      return this.element.isOxygen();
    },

    toString: function() {
      return this.symbol;
    }
  };

  return Atom;
} );
<commit_msg>Adding IDs and createAtomFromSymbol to Atom<commit_after>// Copyright 2002-2013, University of Colorado Boulder

/**
 * Object for actual element properties (symbol, radius, etc.)
 *
 * @author Jonathan Olson <olsonsjc@gmail.com>
 */

define( function( require ) {
  'use strict';

  var Element = require( 'NITROGLYCERIN/Element' );

  var idCounter = 1;

  var Atom = function( element ) {
    this.element = element;
    this.symbol = element.symbol;
    this.radius = element.radius;
    this.diameter = element.radius * 2;
    this.electronegativity = element.electronegativity;
    this.atomicWeight = element.atomicWeight;
    this.color = element.color;

    // IDs for uniqueness and fast lookups
    this.reference = (idCounter++).toString( 16 );
    this.id = this.symbol + '_' + this.reference;
  };

  Atom.prototype = {
    constructor: Atom,

    hasSameElement: function( atom ) {
      return this.element.isSameElement( atom.element );
    },

    isHydrogen: function() {
      return this.element.isHydrogen();
    },

    isCarbon: function() {
      return this.element.isCarbon();
    },

    isOxygen: function() {
      return this.element.isOxygen();
    },

    toString: function() {
      return this.symbol;
    }
  };

  Atom.createAtomFromSymbol = function( symbol ) {
    return new Atom( Element.getElementBySymbol( symbol ) );
  };

  return Atom;
} );
<|endoftext|>


<commit_before>function init(){
	var map = new L.Map("map");

	/* Tilestream Layer example: */
	var landshadeUrl = "/tiles/v2/landShade/{z}/{x}/{y}.png",
		landshade = new L.TileLayer(landshadeUrl, {maxZoom: 12});

	/* ESRI tiled service example: */
	/* var natGeoLayer = new L.TileLayer.ESRI("http://services.arcgisonline.com/ArcGIS/rest/services/NatGeo_World_Map/MapServer");*/
	//var worldTransportation = new L.TileLayer.ESRI("http://services.arcgisonline.com/ArcGIS/rest/services/Reference/World_Transportation/MapServer");
	//var worldImagery = new L.TileLayer.ESRI("http://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer");
	//var worldBoundaries = new L.TileLayer.ESRI("http://services.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places/MapServer");

	// Cloudmade / OpenStreetMap tiled layer
	/*var cmUrl = 'http://{s}.tile.cloudmade.com/f7d28795be6846849741b30c3e4db9a9/997/256/{z}/{x}/{y}.png',
		cmAttribution = 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery  CloudMade',
		cmOptions = { maxZoom: 18, attribution: cmAttribution };

	var cloudmade = new L.TileLayer(cmUrl, cmOptions);//, {styleId: 999});*/

	/*set opacity*/
	//worldTransportation.setOpacity(0.5)
	//worldBoundaries.setOpacity(1)

	/* Bing maps example:
	var bingLayer = new L.TileLayer.Bing(<<Bing Maps API Key>>, "Road"); */

	/* WMS layer example: */
	var wmsUrl = "/geoserver/wms",
		wmsLayer = new L.TileLayer.WMS(wmsUrl, {
			maxZoom: 10,
			layers: "vae:azmines",
			format: "image/png",
			transparent: true
		});
	/**/

	var iconHeight = 60;
	var symbolRules = {
		"State Park": new L.Icon({
	    	iconUrl: "style/images/azpark.png",
	    	iconSize: new L.Point(iconHeight * (258/454),iconHeight),
			shadowUrl: "style/images/azpark-shadow.png",
			shadowSize: new L.Point(iconHeight * (258/454),iconHeight)
		}),
		"National Park": new L.Icon({
	    	iconUrl: "style/images/nps-logo.png",
	    	iconSize: new L.Point(iconHeight * (265/284), iconHeight),
	    	shadowUrl: "style/images/nps-logo-shadow.png",
			shadowSize: new L.Point(iconHeight * (265/284),iconHeight)
		})
	};

	/* WFS GeoJSON layer example: */
	var wfsLayer = new L.GeoJSON.WFS("/geoserver/wfs", "vae:azparks", {
		pointToLayer: function(latlng) { return new L.Marker.AttributeFilter(latlng, "type", { rules: symbolRules }); },
		popupObj: new JadeContent("templates/example.jade"),
		popupOptions: { maxWidth: 530, centered: true },
		hoverFld: "name"
	});

	var center = new L.LatLng(34.1618, -111.53332);
	map.setView(center, 7);
	map.addLayer(wfsLayer);
	map.addLayer(landshade);

	/*setTimeout(function() {
		map.addLayer(worldBoundaries);
		setTimeout(function() {
			map.addLayer(worldTransportation);
		}, 250)
	}, 250)*/

	}<commit_msg>this is a test<commit_after>function init(){
	var map = new L.Map("map");

	/* Tilestream Layer example: */
	var landshadeUrl = "/tiles/v2/landShade/{z}/{x}/{y}.png",
		landshade = new L.TileLayer(landshadeUrl, {maxZoom: 12});
	//
	/* ESRI tiled service example: */
	/* var natGeoLayer = new L.TileLayer.ESRI("http://services.arcgisonline.com/ArcGIS/rest/services/NatGeo_World_Map/MapServer");*/
	//var worldTransportation = new L.TileLayer.ESRI("http://services.arcgisonline.com/ArcGIS/rest/services/Reference/World_Transportation/MapServer");
	//var worldImagery = new L.TileLayer.ESRI("http://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer");
	//var worldBoundaries = new L.TileLayer.ESRI("http://services.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places/MapServer");

	// Cloudmade / OpenStreetMap tiled layer
	/*var cmUrl = 'http://{s}.tile.cloudmade.com/f7d28795be6846849741b30c3e4db9a9/997/256/{z}/{x}/{y}.png',
		cmAttribution = 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery  CloudMade',
		cmOptions = { maxZoom: 18, attribution: cmAttribution };

	var cloudmade = new L.TileLayer(cmUrl, cmOptions);//, {styleId: 999});*/

	/*set opacity*/
	//worldTransportation.setOpacity(0.5)
	//worldBoundaries.setOpacity(1)

	/* Bing maps example:
	var bingLayer = new L.TileLayer.Bing(<<Bing Maps API Key>>, "Road"); */

	/* WMS layer example: */
	var wmsUrl = "/geoserver/wms",
		wmsLayer = new L.TileLayer.WMS(wmsUrl, {
			maxZoom: 10,
			layers: "vae:azmines",
			format: "image/png",
			transparent: true
		});
	/**/

	var iconHeight = 60;
	var symbolRules = {
		"State Park": new L.Icon({
	    	iconUrl: "style/images/azpark.png",
	    	iconSize: new L.Point(iconHeight * (258/454),iconHeight),
			shadowUrl: "style/images/azpark-shadow.png",
			shadowSize: new L.Point(iconHeight * (258/454),iconHeight)
		}),
		"National Park": new L.Icon({
	    	iconUrl: "style/images/nps-logo.png",
	    	iconSize: new L.Point(iconHeight * (265/284), iconHeight),
	    	shadowUrl: "style/images/nps-logo-shadow.png",
			shadowSize: new L.Point(iconHeight * (265/284),iconHeight)
		})
	};

	/* WFS GeoJSON layer example: */
	var wfsLayer = new L.GeoJSON.WFS("/geoserver/wfs", "vae:azparks", {
		pointToLayer: function(latlng) { return new L.Marker.AttributeFilter(latlng, "type", { rules: symbolRules }); },
		popupObj: new JadeContent("templates/example.jade"),
		popupOptions: { maxWidth: 530, centered: true },
		hoverFld: "name"
	});

	var center = new L.LatLng(34.1618, -111.53332);
	map.setView(center, 7);
	map.addLayer(wfsLayer);
	map.addLayer(landshade);

	/*setTimeout(function() {
		map.addLayer(worldBoundaries);
		setTimeout(function() {
			map.addLayer(worldTransportation);
		}, 250)
	}, 250)*/

	}<|endoftext|>


<commit_before>/*global describe, beforeEach, it*/
'use strict';

var path = require('path');
var assert = require('yeoman-generator').assert;
var helpers = require('yeoman-generator').test;
var os = require('os');

describe('react-reflux:app', function () {
  before(function (done) {
    helpers.run(path.join(__dirname, '../app'))
      .inDir(path.join(os.tmpdir(), './temp-test'))
      .withOptions({ 'skip-install': true })
      .withPrompt({
        projectName: 'test',
        desc: 'A test project',
        author: 'Test Testington',
        version: '1.0.1',
        license: 'MIT',
        features: [
          'includeModernizr',
          'includeSass'
        ]
      })
      .on('end', done);
  });

  it('creates files', function () {
    assert.file([
      'app/images',
      'app/scripts/actions',
      'app/scripts/stores',

      'app/favicon.ico',
      'app/robots.txt',
      'app/scripts/app.js',
      'app/scripts/router.jsx',
      'app/scripts/components/layout.jsx',
      'app/scripts/components/home.jsx',
      'app/styles/main.scss',
      'app/index.html',

      'gulpfile.js',
      'bower.json',
      'package.json',
      '.editorconfig',
      '.jshintrc',
      'README.md'
    ]);
  });
});<commit_msg>Wrote more tests<commit_after>/*global describe, beforeEach, it*/
'use strict';

var path = require('path');
var assert = require('yeoman-generator').assert;
var helpers = require('yeoman-generator').test;
var os = require('os');

describe('react-reflux:app', function () {
  describe('when using no features', function () {
    before(function (done) {
      helpers.run(path.join(__dirname, '../app'))
      .inDir(path.join(os.tmpdir(), './temp-test'))
      .withOptions({ 'skip-install': true })
      .withPrompt({
        projectName: 'test',
        desc: 'A test project',
        author: 'Test Testington',
        version: '1.0.1',
        license: 'MIT',
        features: [
        ]
      })
      .on('end', done);
    });

    it('creates files', function () {
      assert.file([
        'app/images',
        'app/scripts/actions',
        'app/scripts/stores',

        'app/favicon.ico',
        'app/robots.txt',
        'app/scripts/app.js',
        'app/scripts/router.jsx',
        'app/scripts/components/layout.jsx',
        'app/scripts/components/home.jsx',
        'app/styles/main.css',
        'app/index.html',

        'gulpfile.js',
        'bower.json',
        'package.json',
        '.editorconfig',
        '.jshintrc',
        'README.md'
      ]);
    });
  });

  describe('when using modernizr', function () {
    before(function (done) {
      helpers.run(path.join(__dirname, '../app'))
      .inDir(path.join(os.tmpdir(), './temp-test'))
      .withOptions({ 'skip-install': true })
      .withPrompt({
        projectName: 'test',
        desc: 'A test project',
        author: 'Test Testington',
        version: '1.0.1',
        license: 'MIT',
        features: [
          'includeModernizr'
        ]
      })
      .on('end', done);
    });

    it('inserts modernizr to html', function () {
      assert.fileContent('app/index.html', /<script src="vendor\/modernizr\/modernizr.js"><\/script>/);
    });

    it('inserts modernizr to bower', function () {
      assert.fileContent('bower.json', /"modernizr"/);
    });
  });

  describe('when using compass', function () {
    before(function (done) {
      helpers.run(path.join(__dirname, '../app'))
      .inDir(path.join(os.tmpdir(), './temp-test'))
      .withOptions({ 'skip-install': true })
      .withPrompt({
        projectName: 'test',
        desc: 'A test project',
        author: 'Test Testington',
        version: '1.0.1',
        license: 'MIT',
        features: [
          'includeModernizr',
          'includeSass'
        ]
      })
      .on('end', done);
    });

    it('creates sass files', function () {
      assert.file([
        'app/styles/main.scss'
      ]);
    });

    it('doesn\'t create css files', function () {
      assert.noFile([
        'app/styles/main.css'
      ]);
    });

    it('inserts compass to gulp', function () {
      assert.fileContent('gulpfile.js', /'compass'/);
    });

    it('inserts modernizr to package.json', function () {
      assert.fileContent('package.json', /"gulp-compass"/);
    });

    it('inserts modernizr to home html component', function () {
      assert.fileContent('app/scripts/components/home.jsx', /<li>Modernizr<\/li>/);
    });
  });
});<|endoftext|>


<commit_before>// OpenWrap
// Author: Nuno Aguiar
// Dev

OpenWrap.dev = function() {
	return ow.dev;
};

OpenWrap.dev.prototype.loadPoolDB = function() {
	ow.loadCh();
	ow.loadObj();

	ow.ch.__types.pooldb = {
		__o: { },
		create       : function(aName, shouldCompress, options) {
			this.__o[aName] = options || {};

			if (isUnDef(this.__o[aName].dbPool)) {
				this.__o[aName].dbPool = ow.obj.pool.DB("org.h2.Driver", "jdbc:h2:mem:", "sa", "sa");
			}

			if (isUnDef(this.__o[aName].tableName)) {
				throw "Need a specific options.tableName";
			}
		},
		destroy      : function(aName) { },
		size         : function(aName) {
			var parent = this, res;
			this.__o[aName].dbPool.use((aDb) => {
				res = Number(aDb.q("select count(*) C from " + parent.__o[aName].tableName).results[0].C);
			});

			return res;
		},
		forEach      : function(aName, aFunction, x) { },
		getKeys      : function(aName, full) { },
		getSortedKeys: function(aName, full) { },
		getSet       : function getSet(aName, aMatch, aK, aV, aTimestamp)  { },
		set          : function(aName, ak, av, aTimestamp) { },
		setAll       : function(aName, anArrayOfKeys, anArrayOfMapData, aTimestamp) { },
		get          : function(aName, aKey) { },
		pop          : function(aName) { },
		shift        : function(aName) { },
		unset        : function(aName, aKey) { }
	};
};

OpenWrap.dev.prototype.loadIgnite = function(aGridName, aIgnite, secretKey, isClient) {
	ow.dev.__i = [];

	var initI = () => {
		plugin("Ignite");
		var grid = (isUnDef(aGridName)) ? "default" : aGridName;
		if (isUnDef(aIgnite)) {
			ow.dev.__i[grid] = new Ignite();
			ow.dev.__i[grid].start(aGridName, secretKey, isClient);
		} else {
			ow.dev.__i[grid] = aIgnite;
		}
	};

	oPromise.prototype.thenAny = function(aFunc, aRejFunc, aGridName) {
		if (isUnDef(ow.dev.__i)) initI();
		return this.then(() => {
			var grid = (isUnDef(aGridName)) ? "default" : aGridName;
			return ow.dev.__i[grid].call(ow.dev.__i[grid].getIgnite(), aFunc.toSource().replace(/[^{]*{([\s\S]*)}[^}]*/, "$1").replace(/"/mg, "\\\""));
		}, aRejFunc);
	};

	oPromise.prototype.thenAll = function(aFunc, aRejFunc, aGridName) {
		if (isUnDef(ow.dev.__i)) initI();
		return this.then(() => {
			var grid = (isUnDef(aGridName)) ? "default" : aGridName;
			return ow.dev.__i[grid].broadcast(ow.dev.__i[grid].getIgnite(), aFunc.toSource().replace(/[^{]*{([\s\S]*)}[^}]*/, "$1").replace(/"/mg, "\\\""));
		}, aRejFunc);
	};

	initI();
};

OpenWrap.dev.prototype.table = function(aValue, aWidth, aTheme, useAnsi, colorMap) {
    if (isUnDef(colorMap)) colorMap = {};
    if (isUnDef(colorMap.lines)) colorMap.title = "bold";
    if (isUnDef(colorMap.values)) colorMap.values = "cyan";

    // replace(\033\[[0-9;]*m/g, "")

    __initializeCon();
    var matrix = [], matrixrule = [], maxX = 0, maxY = 0, cM = [];

    var _getColor = (aValue) => {
       if (isNumber(aValue)) return __colorFormat.number;
       if (isString(aValue)) return __colorFormat.string;
       if (isBoolean(aValue)) return __colorFormat.boolean;
       return __colorFormat.default;
    }

    var _r = (aValue, igX, igY) => {
        if (isMap(aValue) || isArray(aValue)) {
            igX = _$(igX).isNumber().default(0);
            igY = _$(igY).isNumber().default(0);

            var x = igX, y = igY;
            if (isMap(aValue)) {
		var doRule = true;
                for(var key in aValue) {
                    var value = aValue[key];
                    var origX = x;

                    if (isUnDef(matrix[x])) matrix[x] = [];
                    matrix[x][igY] = key;
                    if (useAnsi) {
                        if (isUnDef(cM[x])) cM[x] = [];
                        cM[x][igY] = __colorFormat.key;
                    }
                    if (!isMap(value) && !isArray(value)) {
                        matrix[x][igY + 1] = String(value);
                        if (useAnsi) {
                            if (isUnDef(cM[x])) cM[x] = [];
                            cM[x][igY + 1] = _getColor(value);
                        }
                        x++;
                    } else {
                        x = x + _r(value, x, igY + 1) - 1;
			//matrixrule.push(x); doRule = false;
                    }
                }
                if (Object.keys(aValue).length == 0) {
                    matrix[x][igY] = "";
                    matrix[x][igY + 1] = "";
                    if (useAnsi) {
                        if (isUnDef(cM[x])) cM[x] = [];
                        cM[x][igY] = __colorFormat.key;
                        cM[x][igY + 1] = _getColor(void 0);
                    }
                }
                if (doRule) matrixrule.push(x);
            }
            if (isArray(aValue)) {
                var origX = x;
                for(var ii in aValue) {
                    var o = aValue[ii];

                    origX = x;
                    if (isUnDef(matrix[x])) matrix[x] = [];
                    matrix[x][igY] = "(" + ii + ")";
                    if (useAnsi) {
                        if (isUnDef(cM[x])) cM[x] = [];
                        cM[x][igY] = __colorFormat.key;
                    }

                    if (!isMap(o) && !isArray(o)) {
                        matrix[x][igY + 1] = String(o);
                        if (useAnsi) {
                            if (isUnDef(cM[x])) cM[x] = [];
                            cM[x][igY + 1] = _getColor(o);
                        }
                        x++;
                    } else {
                        x = x + _r(o, x, igY + 1);
                    }
                }
                if (aValue.length == 0) {
		    if (isUnDef(matrix[x])) matrix[x] = [];
                    matrix[x][igY] = "()";
                    matrix[x][igY + 1] = "-";
                    if (useAnsi) {
                        if (isUnDef(cM[x])) cM[x] = [];
                        cM[x][igY] = __colorFormat.key;
                        cM[x][igY + 1] = _getColor(void 0);
                    }
		    x++;
                }
                matrixrule.push(x);
                x++;
            }

            return x - igX;
        }

        return 0;
    };

    _r(aValue);
    maxX = matrix.length;
    for(var x in matrix) {
        if (maxY < matrix[x].length) maxY = matrix[x].length;
    }

    var cM2EmptyLine = () => { cM2[cm2Line] = []; for(var y = 0; y < maxY; y++) { cM2[cm2Line][y] = "" }; cm2Line++; };
    var cM2 = [], cm2Line = 0;
    var out = new Packages.de.vandermeer.asciitable.v2.V2_AsciiTable();
    out.addRule(); cM2EmptyLine();
    for(var x = 0; x < maxX; x++) {
        if (matrixrule.indexOf(x) >= 0) { out.addRule(); cM2EmptyLine(); }
        if (isUnDef(matrix[x])) matrix[x] = [];
	if (isUnDef(cM2[cm2Line])) cM2[cm2Line] = [];
        for (var y = 0; y < maxY; y++) {
            if (isUnDef(matrix[x][y])) {
                matrix[x][y] = "";
		cM2[cm2Line][y] = "";
            } else {
	        cM2[cm2Line][y] = cM[x][y];
	    }
        }
	cm2Line++;
        out.addRow.apply(out, matrix[x]);
    }
    out.addRule(); cM2EmptyLine();
    global.__matrix = matrix;
    global.__matrixrule = matrixrule;
    global.__cm = cM2;

    aTheme = _$(aTheme).default(Packages.de.vandermeer.asciitable.v2.themes.V2_E_TableThemes.UTF_LIGHT.get());
    aWidth = _$(aWidth).isNumber().default(__con.getTerminal().getWidth() - 1);
    var rt = new Packages.openaf.asciitable.render.AnsiAsciiTableRenderer(true);
    rt.setTheme(aTheme);
    rt.setWidth(new Packages.openaf.asciitable.render.WidthAnsiLongestWordTab(aWidth));
    var o;
    if (useAnsi)
        o = String(rt.render(out, cM2));
    else
        o = String(rt.render(out));
    if (o.indexOf("\n") > aWidth) {
        rt.setWidth(new Packages.openaf.asciitable.render.WidthAnsiLongestWordTab(aWidth - (o.indexOf("\n")- aWidth)));
        o = String(rt.render(out));
    }

    return o;
};

OpenWrap.dev.prototype.view = function(aObj) {
    ansiStart();
    print(ow.dev.table(aObj, void 0, void 0, true));
    ansiStop();
};
<commit_msg>ow.dev.table: handle empty cells and text alignment<commit_after>// OpenWrap
// Author: Nuno Aguiar
// Dev

OpenWrap.dev = function() {
	return ow.dev;
};

OpenWrap.dev.prototype.loadPoolDB = function() {
	ow.loadCh();
	ow.loadObj();

	ow.ch.__types.pooldb = {
		__o: { },
		create       : function(aName, shouldCompress, options) {
			this.__o[aName] = options || {};

			if (isUnDef(this.__o[aName].dbPool)) {
				this.__o[aName].dbPool = ow.obj.pool.DB("org.h2.Driver", "jdbc:h2:mem:", "sa", "sa");
			}

			if (isUnDef(this.__o[aName].tableName)) {
				throw "Need a specific options.tableName";
			}
		},
		destroy      : function(aName) { },
		size         : function(aName) {
			var parent = this, res;
			this.__o[aName].dbPool.use((aDb) => {
				res = Number(aDb.q("select count(*) C from " + parent.__o[aName].tableName).results[0].C);
			});

			return res;
		},
		forEach      : function(aName, aFunction, x) { },
		getKeys      : function(aName, full) { },
		getSortedKeys: function(aName, full) { },
		getSet       : function getSet(aName, aMatch, aK, aV, aTimestamp)  { },
		set          : function(aName, ak, av, aTimestamp) { },
		setAll       : function(aName, anArrayOfKeys, anArrayOfMapData, aTimestamp) { },
		get          : function(aName, aKey) { },
		pop          : function(aName) { },
		shift        : function(aName) { },
		unset        : function(aName, aKey) { }
	};
};

OpenWrap.dev.prototype.loadIgnite = function(aGridName, aIgnite, secretKey, isClient) {
	ow.dev.__i = [];

	var initI = () => {
		plugin("Ignite");
		var grid = (isUnDef(aGridName)) ? "default" : aGridName;
		if (isUnDef(aIgnite)) {
			ow.dev.__i[grid] = new Ignite();
			ow.dev.__i[grid].start(aGridName, secretKey, isClient);
		} else {
			ow.dev.__i[grid] = aIgnite;
		}
	};

	oPromise.prototype.thenAny = function(aFunc, aRejFunc, aGridName) {
		if (isUnDef(ow.dev.__i)) initI();
		return this.then(() => {
			var grid = (isUnDef(aGridName)) ? "default" : aGridName;
			return ow.dev.__i[grid].call(ow.dev.__i[grid].getIgnite(), aFunc.toSource().replace(/[^{]*{([\s\S]*)}[^}]*/, "$1").replace(/"/mg, "\\\""));
		}, aRejFunc);
	};

	oPromise.prototype.thenAll = function(aFunc, aRejFunc, aGridName) {
		if (isUnDef(ow.dev.__i)) initI();
		return this.then(() => {
			var grid = (isUnDef(aGridName)) ? "default" : aGridName;
			return ow.dev.__i[grid].broadcast(ow.dev.__i[grid].getIgnite(), aFunc.toSource().replace(/[^{]*{([\s\S]*)}[^}]*/, "$1").replace(/"/mg, "\\\""));
		}, aRejFunc);
	};

	initI();
};

OpenWrap.dev.prototype.table = function(aValue, aWidth, aTheme, useAnsi) {
    // replace(\033\[[0-9;]*m/g, "")

    __initializeCon();
    var matrix = [], matrixrule = [], maxX = 0, maxY = 0, cM = [], al = [];

    var _getColor = (aValue) => {
       if (isNumber(aValue)) return __colorFormat.number;
       if (isString(aValue)) return __colorFormat.string;
       if (isBoolean(aValue)) return __colorFormat.boolean;
       return __colorFormat.default;
    }

    var _r = (aValue, igX, igY) => {
        if (isMap(aValue) || isArray(aValue)) {
            igX = _$(igX).isNumber().default(0);
            igY = _$(igY).isNumber().default(0);

            var x = igX, y = igY;
            if (isMap(aValue)) {
		var origX = x;
                for(var key in aValue) {

                    var value = aValue[key];

		    origX = x;
                    if (isUnDef(matrix[x])) matrix[x] = [];
                    matrix[x][igY] = key + ":";
                    if (useAnsi) {
                        if (isUnDef(cM[x])) cM[x] = [];
			if (isUnDef(al[x])) al[x] = [];
                        cM[x][igY] = __colorFormat.key;
			al[x][igY] = "r";
                    }
                    if (!isMap(value) && !isArray(value)) {
                        matrix[x][igY + 1] = String(value);
			al[x][igY + 1] = "l";
                        if (useAnsi) {
                            if (isUnDef(cM[x])) cM[x] = [];
                            cM[x][igY + 1] = _getColor(value);
                        }
                        x++;
                    } else {
			if (x != 0 && matrixrule.indexOf(x-1) < 0) matrixrule.push(x);
                        x = x + _r(value, x, igY + 1) - 1;
                    }
                }
                if (Object.keys(aValue).length == 0) {
                    matrix[x][igY] = "{}";
		    al[x][igY] = "c";
                    matrix[x][igY + 1] = "-";
		    al[x][igY + 1] = "l";
                    if (useAnsi) {
                        if (isUnDef(cM[x])) cM[x] = [];
                        cM[x][igY] = __colorFormat.key;
                        cM[x][igY + 1] = _getColor(void 0);
                    }
		    x++;
                }
                matrixrule.push(x);
	        x++;
            }
            if (isArray(aValue)) {
                var origX = x;
                for(var ii in aValue) {
                    var o = aValue[ii];

                    origX = x;
                    if (isUnDef(matrix[x])) matrix[x] = [];
		    if (isUnDef(al[x])) al[x] = [];
                    matrix[x][igY] = "[" + ii + "]";
		    al[x][igY] = "r";
                    if (useAnsi) {
                        if (isUnDef(cM[x])) cM[x] = [];
                        cM[x][igY] = __colorFormat.key;
                    }

                    if (!isMap(o) && !isArray(o)) {
                        matrix[x][igY + 1] = String(o);
			al[x][igY + 1] = "l";
                        if (useAnsi) {
                            if (isUnDef(cM[x])) cM[x] = [];
                            cM[x][igY + 1] = _getColor(o);
                        }
                        x++;
                    } else {
			if (x != 0 && matrixrule.indexOf(x-1) < 0) matrixrule.push(x)
                        x = x + _r(o, x, igY + 1) - 1;
                    }
                }
                if (aValue.length == 0) {
                    matrix[x][igY] = "[]";
		    al[x][igY] = "c";
                    matrix[x][igY + 1] = "-";
		    al[x][igY + 1] = "l";
                    if (useAnsi) {
                        if (isUnDef(cM[x])) cM[x] = [];
                        cM[x][igY] = __colorFormat.key;
                        cM[x][igY + 1] = _getColor(void 0);
                    }
		    x++;
                }
                matrixrule.push(x);
                x++;
            }

            return x - igX;
        }

        return 0;
    };

    _r(aValue);
    maxX = matrix.length;
    for(var x in matrix) {
        if (maxY < matrix[x].length) maxY = matrix[x].length;
    }

    var cM2EmptyLine = () => { cM2[cm2Line] = []; for(var y = 0; y < maxY; y++) { cM2[cm2Line][y] = "" }; cm2Line++; };
    var cM2 = [], cm2Line = 0;
    var out = new Packages.de.vandermeer.asciitable.v2.V2_AsciiTable();
    out.addRule(); cM2EmptyLine();
    for(var x = 0; x < maxX; x++) {
        if (matrixrule.indexOf(x) >= 0) { out.addRule(); cM2EmptyLine(); }
        if (isUnDef(matrix[x])) matrix[x] = [];
	if (isUnDef(al[x])) al[x] = [];
	if (isUnDef(cM2[cm2Line])) cM2[cm2Line] = [];
        for (var y = 0; y < maxY; y++) {
            if (isUnDef(matrix[x][y])) {
                matrix[x][y] = "";
		al[x][y] = "l";
		cM2[cm2Line][y] = "";
            } else {
	        cM2[cm2Line][y] = cM[x][y];
	    }
        }
	cm2Line++;
        out.addRow.apply(out, matrix[x]).setAlignment(al[x]);
    }
    out.addRule(); cM2EmptyLine();
    global.__matrix = matrix;
    global.__matrixrule = matrixrule;
    global.__cm = cM2;

    aTheme = _$(aTheme).default(Packages.de.vandermeer.asciitable.v2.themes.V2_E_TableThemes.UTF_LIGHT.get());
    aWidth = _$(aWidth).isNumber().default(__con.getTerminal().getWidth() - 1);
    var rt = new Packages.openaf.asciitable.render.AnsiAsciiTableRenderer(true);
    rt.setTheme(aTheme);
    rt.setWidth(new Packages.openaf.asciitable.render.WidthAnsiLongestWordTab(aWidth));
    var o;
    if (useAnsi)
        o = String(rt.render(out, cM2));
    else
        o = String(rt.render(out));
    if (o.indexOf("\n") > aWidth) {
        rt.setWidth(new Packages.openaf.asciitable.render.WidthAnsiLongestWordTab(aWidth - (o.indexOf("\n")- aWidth)));
        o = String(rt.render(out));
    }

    return o;
};

OpenWrap.dev.prototype.view = function(aObj) {
    ansiStart();
    print(ow.dev.table(aObj, void 0, void 0, true));
    ansiStop();
};
<|endoftext|>


<commit_before>module.exports = function (window) {
    "use strict";

    require('./css/i-input.css');
    require('itags.core')(window);

    var itagName = 'i-input', // <-- define your own itag-name here
        ITSA = window.ITSA,
        Event = ITSA.Event,
        Itag, IFormElement;

    if (!window.ITAGS[itagName]) {

        IFormElement = require('i-formelement')(window);

        Event.before(itagName+':manualfocus', function(e) {
            // the i-select itself is unfocussable, but its button is
            // we need to patch `manualfocus`,
            // which is emitted on node.focus()
            // a focus by userinteraction will always appear on the button itself
            // so we don't bother that
            var element = e.target;
            e.preventDefault();
            element.itagReady().then(
                function() {
                    var input = element.getElement('input');
                    input && input.focus(true);
                }
            );
        });

        Event.after('valuechange', function(e) {
            var element = e.target.getParent(),
                newValue = e.value,
                model = element.model,
                prevValue = model.value,
                validNumber, min, max;
            model.value = newValue;
            switch (model.type) {
                case 'number':
                    validNumber = model.floated ? newValue.validateFloat() : newValue.validateNumber();
                    if (validNumber) {
                        min = model.min;
                        max = model.max;
                        if ((typeof min==='number') && (newValue<min)) {
                            validNumber = false;
                        }
                        else if ((typeof max==='number') && (newValue>max)) {
                            validNumber = false;
                        }
                    }
                    model.invalid = !validNumber;
                    break;
                case 'email':
                    model.invalid = !newValue.validateEmail();
                    break;
                case 'url':
                    model.invalid = !newValue.validateURL();
                    break;
                default:
                    model.invalid = false;
            }
            /**
            * Emitted when a the i-select changes its value
            *
            * @event i-select:valuechange
            * @param e {Object} eventobject including:
            * @param e.target {HtmlElement} the i-input element
            * @param e.prevValue {String}
            * @param e.newValue {String}
            * @since 0.1
            */
            element.emit('valuechange', {
                prevValue: prevValue,
                newValue: newValue
            });
        }, 'i-input > input');

        Itag = IFormElement.subClass(itagName, {
            attrs: {
                'i-prop': 'string',
                'reset-value': 'string',
                placeholder: 'string',
                readonly: 'boolean',
                primaryonenter: 'boolean',
                min: 'number',
                max: 'number',
                floated: 'boolean',
                type: 'string',
                invalid: 'boolean',
                format: 'string'
            },

            init: function() {
                var element = this,
                    designNode = element.getItagContainer(),
                    model = element.model,
                    value = designNode.getText(),
                    validNumber, min, max;

                element.defineWhenUndefined('value', value)
                       // set the reset-value to the inital-value in case `reset-value` was not present
                       .defineWhenUndefined('reset-value', value);
                value = model.value;
                switch (model.type) {
                    case 'number':
                        validNumber = model.floated ? value.validateFloat() : value.validateNumber();
                        if (validNumber) {
                            min = model.min;
                            max = model.max;
                            if ((typeof min==='number') && (value<min)) {
                                validNumber = false;
                            }
                            else if ((typeof max==='number') && (value>max)) {
                                validNumber = false;
                            }
                        }
                        model.invalid = !validNumber;
                        break;
                    case 'email':
                        model.invalid = !value.validateEmail();
                        break;
                    case 'url':
                        model.invalid = !value.validateURL();
                        break;
                    default:
                        model.invalid = false;
                }
            },

            render: function() {
                this.setHTML('<input type="text" value="'+this.model.value+'" />');
            },

            sync: function() {
                var element = this,
                    model = element.model,
                    input = element.getElement('>input');
                // it is safe to use setValue --> when the content hasn't changed, `setValue` doesn't do anything
                input.setValue(model.value);
                if (model.placeholder) {
                    input.setAttr('placeholder', model.placeholder, true);
                }
                else {
                    input.removeAttr('placeholder', true);
                }
                if (model.primaryonenter) {
                    input.setAttr('fm-primaryonenter', model.primaryonenter, true);
                }
                else {
                    input.removeAttr('fm-primaryonenter', true);
                }
                if (model.readonly) {
                    input.setAttr('readonly', model.readonly, true);
                }
                else {
                    input.removeAttr('readonly', true);
                }
            },

            currentToReset: function() {
                var model = this.model;
                model['reset-value'] = model.value;
            },

            reset: function() {
                var model = this.model;
                model.value = model['reset-value'];
            }
        });

        window.ITAGS[itagName] = Itag;
    }

    return window.ITAGS[itagName];
};
<commit_msg>intermediate saving<commit_after>module.exports = function (window) {
    "use strict";

    require('./css/i-input.css');
    require('itags.core')(window);

    var itagName = 'i-input', // <-- define your own itag-name here
        ITSA = window.ITSA,
        Event = ITSA.Event,
        Itag, IFormElement;

    if (!window.ITAGS[itagName]) {

        IFormElement = require('i-formelement')(window);

        Event.before(itagName+':manualfocus', function(e) {
            // the i-select itself is unfocussable, but its button is
            // we need to patch `manualfocus`,
            // which is emitted on node.focus()
            // a focus by userinteraction will always appear on the button itself
            // so we don't bother that
            var element = e.target;
            e.preventDefault();
            element.itagReady().then(
                function() {
                    var input = element.getElement('input');
                    input && input.focus(true); // MUST be silent
                }
            );
        });

        Event.after(['keypress', 'mouseup', 'panup', 'mousedown', 'pandown'], function(e) {
            var inputNode = e.target,
                element = inputNode.getParent(),
                model = element.model;
            model['selection-start'] = inputNode.selectionStart || 0;
            model['selection-end'] = inputNode.selectionEnd || 0;
        }, 'i-input input');

        Event.after('valuechange', function(e) {
            var element = e.target.getParent(),
                newValue = e.value,
                model = element.model,
                prevValue = model.value,
                validNumber, min, max;
            model.value = newValue;
            switch (model.type) {
                case 'number':
                    validNumber = model.floated ? newValue.validateFloat() : newValue.validateNumber();
                    if (validNumber) {
                        min = model.min;
                        max = model.max;
                        if ((typeof min==='number') && (newValue<min)) {
                            validNumber = false;
                        }
                        else if ((typeof max==='number') && (newValue>max)) {
                            validNumber = false;
                        }
                    }
                    model.invalid = !validNumber;
                    break;
                case 'email':
                    model.invalid = !newValue.validateEmail();
                    break;
                case 'url':
                    model.invalid = !newValue.validateURL();
                    break;
                default:
                    model.invalid = false;
            }
            /**
            * Emitted when a the i-select changes its value
            *
            * @event i-select:valuechange
            * @param e {Object} eventobject including:
            * @param e.target {HtmlElement} the i-input element
            * @param e.prevValue {String}
            * @param e.newValue {String}
            * @since 0.1
            */
            element.emit('valuechange', {
                prevValue: prevValue,
                newValue: newValue
            });
        }, 'i-input > input');

        Itag = IFormElement.subClass(itagName, {
            attrs: {
                'i-prop': 'string',
                'reset-value': 'string',
                placeholder: 'string',
                readonly: 'boolean',
                primaryonenter: 'boolean',
                min: 'number',
                max: 'number',
                floated: 'boolean',
                type: 'string',
                invalid: 'boolean',
                format: 'string',
                'selection-start': 'number',
                'selection-end': 'number'
            },

            init: function() {
                var element = this,
                    designNode = element.getItagContainer(),
                    model = element.model,
                    value = designNode.getText(),
                    validNumber, min, max;

                element.defineWhenUndefined('value', value)
                       // set the reset-value to the inital-value in case `reset-value` was not present
                       .defineWhenUndefined('reset-value', value);
                value = model.value;
                switch (model.type) {
                    case 'number':
                        validNumber = model.floated ? value.validateFloat() : value.validateNumber();
                        if (validNumber) {
                            min = model.min;
                            max = model.max;
                            if ((typeof min==='number') && (value<min)) {
                                validNumber = false;
                            }
                            else if ((typeof max==='number') && (value>max)) {
                                validNumber = false;
                            }
                        }
                        model.invalid = !validNumber;
                        break;
                    case 'email':
                        model.invalid = !value.validateEmail();
                        break;
                    case 'url':
                        model.invalid = !value.validateURL();
                        break;
                    default:
                        model.invalid = false;
                }
            },

            render: function() {
                this.setHTML('<input type="text" value="'+this.model.value+'" />');
            },

            sync: function() {
                var element = this,
                    model = element.model,
                    input = element.getElement('>input'),
                    selectionEnd, selectionStart;
                // it is safe to use setValue --> when the content hasn't changed, `setValue` doesn't do anything
                input.setValue(model.value);

                // cautious: fm-selectionstart can be 0 --> which would lead into a falsy value
                selectionStart = model['selection-start'];
                (selectionStart===undefined) && (selectionStart=String(model.value).length);
                selectionEnd = Math.max(model['selection-end'] || selectionStart, selectionStart);
                input.selectionEnd = selectionEnd;
                input.selectionStart = selectionStart;

                if (model.placeholder) {
                    input.setAttr('placeholder', model.placeholder, true);
                }
                else {
                    input.removeAttr('placeholder', true);
                }
                if (model.primaryonenter) {
                    input.setAttr('fm-primaryonenter', model.primaryonenter, true);
                }
                else {
                    input.removeAttr('fm-primaryonenter', true);
                }
                if (model.readonly) {
                    input.setAttr('readonly', model.readonly, true);
                }
                else {
                    input.removeAttr('readonly', true);
                }
            },

            currentToReset: function() {
                var model = this.model;
                model['reset-value'] = model.value;
            },

            reset: function() {
                var model = this.model;
                model.value = model['reset-value'];
            },

            invalid: function() {
                return this.model.invalid;
            }
        });

        window.ITAGS[itagName] = Itag;
    }

    return window.ITAGS[itagName];
};
<|endoftext|>


<commit_before>var IMDB = (function () {

  function _infoClear() {
    var info = document.getElementById('info');
    info.innerHTML = '';
  }

  function _search(e) {
    var results = Object.keys(e.results);
    console.log("Success: " + e);
    console.log(e.results);
    for (var i = 0; i < e.results.length; i++) {
      console.log(JSON.stringify(e.results[i]));
      var show = document.createElement('div');
      show.id = i;
      var json = e.results[i];
      var poster = tmdb.images_uri + tmdb.size + e.results[i].poster_path;
      var name = e.results[i].title || e.results[i].original_name;
      var img = new Image();
      img.src = poster;
      info.appendChild(show);
      show.appendChild(img);
      if (img.src === 'http://image.tmdb.org/t/p/w500null') {
        img.src = 'http://colouringbook.org/SVG/2011/COLOURINGBOOK.ORG/cartoon_tv_black_white_line_art_scalable_vector_graphics_svg_inkscape_adobe_illustrator_clip_art_clipart_coloring_book_colouring-1331px.png';
      }
      show.innerHTML += '
' + name + '
';

      function click() {
        var display = document.getElementById('display');
        display.innerHTML = '';
        //img.src = '';
        var i = this.id;
        console.log(i);
        var displayPoster = tmdb.images_uri + tmdb.size + e.results[i].poster_path;
        img.src = displayPoster;
        if (img.src === 'http://image.tmdb.org/t/p/w500null') {
          img.src = 'http://colouringbook.org/SVG/2011/COLOURINGBOOK.ORG/cartoon_tv_black_white_line_art_scalable_vector_graphics_svg_inkscape_adobe_illustrator_clip_art_clipart_coloring_book_colouring-1331px.png';
        }
        display.appendChild(img);
        display.innerHTML += '
Air date: ' + e.results[i].release_date || e.results[i].first_air_date + '
';
        display.innerHTML += '
Name: ' + e.results[i].title || e.results[i].original_name + '
';
        display.innerHTML += '
Description: ' + e.results[i].overview + '
';

      };
      show.addEventListener('click', click, false);
    };
}
  function _searchTv() {
    var query = document.getElementById('query').value;
    tmdb.call('/search/tv', {
      'query': query,
    },
    function(e) {
      _search(e);
    },
      function(e) {
        console.log("Error: " + e)
      }
    )
  }
  function _searchMovies() {
    var query = document.getElementById('query').value;
    tmdb.call('/search/movie', {
      'query': query,
    },
    function(e) {
      _search(e);
    },
      function(e) {
        console.log("Error: " + e)
      }
    )
  }

function _topMovies() {
  tmdb.call('/movie/top_rated', {},
    function(e) {
      IMDB.clear();
      IMDB.search(e);
    },
    function(e) {
      console.log("Error: " + e)
    })
}

function _popular() {
  tmdb.call('/movie/popular', {},
    function(e) {
      IMDB.clear();
      IMDB.search(e);
    },
    function(e) {
      console.log("Error: " + e)
    }
  )
}

function _nowPlaying() {
  tmdb.call('/movie/now_playing', {},
    function(e) {
      IMDB.clear();
      IMDB.search(e);
    },
    function(e) {
      console.log("Error: " + e)
    })
}

function _upcoming() {
  tmdb.call('/movie/upcoming', {},
    function(e) {
      IMDB.clear();
      IMDB.search(e);
    },
    function(e) {
      console.log("Error: " + e)
    })
}

function _tvPopular() {
  tmdb.call('/tv/popular', {},
    function(e) {
      IMDB.clear();
      IMDB.search(e);
    },
    function(e) {
      console.log("Error: " + e)
    })
}

function _tvTopRated() {
  tmdb.call('/tv/top_rated', {},
    function(e) {
      IMDB.clear();
      IMDB.search(e);
    },
    function(e) {
      console.log("Error: " + e)
    })
}
  return {
  //Public API : Private function
    searchTv : _searchTv,
    searchMovies : _searchMovies,
    search : _search,
    clear : _infoClear,
    tvTop : _tvTopRated,
    movTop : _topMovies,
    tvPop : _tvPopular,
    movPop : _popular,
    soon : _upcoming,
    now : _nowPlaying,
  }

})();<commit_msg>Cached result.length in for loop<commit_after>var IMDB = (function () {

  function _infoClear() {
    var info = document.getElementById('info');
    info.innerHTML = '';
  }

  function _search(e) {
    var results = Object.keys(e.results);
    console.log("Success: " + e);
    console.log(e.results);
    var resultLen = e.results.length;
    for (var i = 0; i < resultLen; i++) {
      console.log(JSON.stringify(e.results[i]));
      var show = document.createElement('div');
      show.id = i;
      var json = e.results[i];
      var poster = tmdb.images_uri + tmdb.size + e.results[i].poster_path;
      var name = e.results[i].title || e.results[i].original_name;
      var img = new Image();
      img.src = poster;
      info.appendChild(show);
      show.appendChild(img);
      if (img.src === 'http://image.tmdb.org/t/p/w500null') {
        img.src = 'http://colouringbook.org/SVG/2011/COLOURINGBOOK.ORG/cartoon_tv_black_white_line_art_scalable_vector_graphics_svg_inkscape_adobe_illustrator_clip_art_clipart_coloring_book_colouring-1331px.png';
      }
      show.innerHTML += '
' + name + '
';

      function click() {
        var display = document.getElementById('display');
        display.innerHTML = '';
        //img.src = '';
        var i = this.id;
        console.log(i);
        var displayPoster = tmdb.images_uri + tmdb.size + e.results[i].poster_path;
        img.src = displayPoster;
        if (img.src === 'http://image.tmdb.org/t/p/w500null') {
          img.src = 'http://colouringbook.org/SVG/2011/COLOURINGBOOK.ORG/cartoon_tv_black_white_line_art_scalable_vector_graphics_svg_inkscape_adobe_illustrator_clip_art_clipart_coloring_book_colouring-1331px.png';
        }
        display.appendChild(img);
        display.innerHTML += '
Air date: ' + e.results[i].release_date || e.results[i].first_air_date + '
';
        display.innerHTML += '
Name: ' + e.results[i].title || e.results[i].original_name + '
';
        display.innerHTML += '
Description: ' + e.results[i].overview + '
';

      };
      show.addEventListener('click', click, false);
    };
}
  function _searchTv() {
    var query = document.getElementById('query').value;
    tmdb.call('/search/tv', {
      'query': query,
    },
    function(e) {
      _search(e);
    },
      function(e) {
        console.log("Error: " + e)
      }
    )
  }
  function _searchMovies() {
    var query = document.getElementById('query').value;
    tmdb.call('/search/movie', {
      'query': query,
    },
    function(e) {
      _search(e);
    },
      function(e) {
        console.log("Error: " + e)
      }
    )
  }

function _topMovies() {
  tmdb.call('/movie/top_rated', {},
    function(e) {
      IMDB.clear();
      IMDB.search(e);
    },
    function(e) {
      console.log("Error: " + e)
    })
}

function _popular() {
  tmdb.call('/movie/popular', {},
    function(e) {
      IMDB.clear();
      IMDB.search(e);
    },
    function(e) {
      console.log("Error: " + e)
    }
  )
}

function _nowPlaying() {
  tmdb.call('/movie/now_playing', {},
    function(e) {
      IMDB.clear();
      IMDB.search(e);
    },
    function(e) {
      console.log("Error: " + e)
    })
}

function _upcoming() {
  tmdb.call('/movie/upcoming', {},
    function(e) {
      IMDB.clear();
      IMDB.search(e);
    },
    function(e) {
      console.log("Error: " + e)
    })
}

function _tvPopular() {
  tmdb.call('/tv/popular', {},
    function(e) {
      IMDB.clear();
      IMDB.search(e);
    },
    function(e) {
      console.log("Error: " + e)
    })
}

function _tvTopRated() {
  tmdb.call('/tv/top_rated', {},
    function(e) {
      IMDB.clear();
      IMDB.search(e);
    },
    function(e) {
      console.log("Error: " + e)
    })
}
  return {
  //Public API : Private function
    searchTv : _searchTv,
    searchMovies : _searchMovies,
    search : _search,
    clear : _infoClear,
    tvTop : _tvTopRated,
    movTop : _topMovies,
    tvPop : _tvPopular,
    movPop : _popular,
    soon : _upcoming,
    now : _nowPlaying,
  }

})();
<|endoftext|>


<commit_before>/**
 * @author: Meki Cheraoui, Jeff Thompson
 * See COPYING for copyright and distribution information.
 * This class represents a Name as an array of components where each is a byte array.
 */

/*
 * Create a new Name from _components.
 * If _components is a string, parse it as a URI.  Otherwise it is an array of components
 * where each is a string, byte array, ArrayBuffer or Uint8Array.
 * Convert and store as an array of Uint8Array.
 * If a component is a string, encode as utf8.
 */
var Name = function Name(_components){
	if( typeof _components == 'string') {
		if(LOG>3)console.log('Content Name String '+_components);
		this.components = Name.createNameArray(_components);
	}
	else if(typeof _components === 'object'){
		if(LOG>4)console.log('Content Name Array '+_components);
		this.components = [];
        for (var i = 0; i < _components.length; ++i)
            this.add(_components[i]);
	}
	else if(_components==null)
		this.components =[];
	else
		if(LOG>1)console.log("NO CONTENT NAME GIVEN");
};

Name.prototype.getName = function() {
    return this.to_uri();
};

/* Parse name as a URI and return an array of Uint8Array components.
 *
 */
Name.createNameArray = function(name) {
    name = name.trim();
    if (name.length <= 0)
        return [];

    var iColon = name.indexOf(':');
    if (iColon >= 0) {
        // Make sure the colon came before a '/'.
        var iFirstSlash = name.indexOf('/');
        if (iFirstSlash < 0 || iColon < iFirstSlash)
            // Omit the leading protocol such as ndn:
            name = name.substr(iColon + 1, name.length - iColon - 1).trim();
    }

  	if (name[0] == '/') {
        if (name.length >= 2 && name[1] == '/') {
            // Strip the authority following "//".
            var iAfterAuthority = name.indexOf('/', 2);
            if (iAfterAuthority < 0)
                // Unusual case: there was only an authority.
                return [];
            else
                name = name.substr(iAfterAuthority + 1, name.length - iAfterAuthority - 1).trim();
        }
        else
            name = name.substr(1, name.length - 1).trim();
    }

	var array = name.split('/');

    // Unescape the components.
    for (var i = 0; i < array.length; ++i) {
        var component = unescape(array[i].trim());

        if (component.match(/[^.]/) == null) {
            // Special case for component of only periods.
            if (component.length <= 2) {
                // Zero, one or two periods is illegal.  Ignore this componenent to be
                //   consistent with the C implmentation.
                // This also gets rid of a trailing '/'.
                array.splice(i, 1);
                --i;
                continue;
            }
            else
                // Remove 3 periods.
                array[i] = component.substr(3, component.length - 3);
        }
        else
            array[i] = component;

        // Change the component to Uint8Array now.
        array[i] = DataUtils.toNumbersFromString(array[i]);
    }

	return array;
}

Name.prototype.from_ccnb = function(/*XMLDecoder*/ decoder)  {
		decoder.readStartElement(this.getElementLabel());

		this.components = new Array(); //new ArrayList<byte []>();

		while (decoder.peekStartElement(CCNProtocolDTags.Component)) {
			this.add(decoder.readBinaryElement(CCNProtocolDTags.Component));
		}

		decoder.readEndElement();
};

Name.prototype.to_ccnb = function(/*XMLEncoder*/ encoder)  {

		if( this.components ==null )
			throw new Error("CANNOT ENCODE EMPTY CONTENT NAME");

		encoder.writeStartElement(this.getElementLabel());
		var count = this.components.length;
		for (var i=0; i < count; i++) {
			encoder.writeElement(CCNProtocolDTags.Component, this.components[i]);
		}
		encoder.writeEndElement();
};

Name.prototype.getElementLabel = function(){
	return CCNProtocolDTags.Name;
};

/*
 * component is a string, byte array, ArrayBuffer or Uint8Array.
 * Convert to Uint8Array and add to this Name.
 * If a component is a string, encode as utf8.
 * Return the converted value.
 */
Name.prototype.add = function(component){
    var result;
    if(typeof component == 'string')
        result = DataUtils.stringToUtf8Array(component);
	else if(typeof component == 'object' && component instanceof Uint8Array)
        result = new Uint8Array(component);
	else if(typeof component == 'object' && component instanceof ArrayBuffer) {
        // Make a copy.  Don't use ArrayBuffer.slice since it isn't always supported.
        result = new Uint8Array(new ArrayBuffer(component.byteLength));
        result.set(new Uint8Array(component));
    }
	else if(typeof component == 'object')
        // Assume component is a byte array.  We can't check instanceof Array because
        //   this doesn't work in JavaScript if the array comes from a different module.
        result = new Uint8Array(component);
	else
		throw new Error("Cannot add Name element at index " + this.components.length +
            ": Invalid type");

	return this.components.push(result);
};

// Return the escaped name string according to "CCNx URI Scheme".
Name.prototype.to_uri = function() {
	var result = "";

	for(var i = 0; i < this.components.length; ++i)
		result += "/"+ Name.toEscapedString(this.components[i]);

	return result;
};

/*
 * Return a new Name with the first nComponents components of this Name.
 */
Name.prototype.getPrefix = function(nComponents) {
    return new Name(this.components.slice(0, nComponents));
}

/*
 * Return a new ArrayBuffer of the component at i.
 */
Name.prototype.getComponent = function(i) {
    var result = new ArrayBuffer(this.components[i].length);
    new Uint8Array(result).set(this.components[i]);
    return result;
}

/*
 * The "file name" in a name is the last component that isn't blank and doesn't start with one of the
 *   special marker octets (for version, etc.).  Return the index in this.components of
 *   the file name, or -1 if not found.
 */
Name.prototype.indexOfFileName = function() {
    for (var i = this.components.length - 1; i >= 0; --i) {
        var component = this.components[i];
        if (component.length <= 0)
            continue;

        if (component[0] == 0 || component[0] == 0xC0 || component[0] == 0xC1 ||
            (component[0] >= 0xF5 && component[0] <= 0xFF))
            continue;

        return i;
    }

    return -1;
}

/*
 * Return true if this Name has the same components as name.
 */
Name.prototype.equalsName = function(name) {
    if (this.components.length != name.components.length)
        return false;

    // Start from the last component because they are more likely to differ.
    for (var i = this.components.length - 1; i >= 0; --i) {
        if (!DataUtils.arraysEqual(this.components[i], name.components[i]))
            return false;
    }

    return true;
}

/*
 * Find the last component in name that has a ContentDigest and return the digest value as Uint8Array,
 *   or null if not found.
 * A ContentDigest component is Name.ContentDigestPrefix + 32 bytes + Name.ContentDigestSuffix.
 */
Name.prototype.getContentDigestValue = function() {
    var digestComponentLength = Name.ContentDigestPrefix.length + 32 + Name.ContentDigestSuffix.length;
    for (var i = this.components.length - 1; i >= 0; --i) {
        // Check for the correct length and equal ContentDigestPrefix and ContentDigestSuffix.
        if (this.components[i].length == digestComponentLength &&
            DataUtils.arraysEqual(this.components[i].subarray(0, Name.ContentDigestPrefix.length),
                                  Name.ContentDigestPrefix) &&
            DataUtils.arraysEqual(this.components[i].subarray
               (this.components[i].length - Name.ContentDigestSuffix.length, this.components[i].length),
                                  Name.ContentDigestSuffix))
           return this.components[i].subarray
               (Name.ContentDigestPrefix.length, Name.ContentDigestPrefix.length + 32);
    }

    return null;
}

// Meta GUID "%C1.M.G%C1" + ContentDigest with a 32 byte BLOB.
Name.ContentDigestPrefix = new Uint8Array([0xc1, 0x2e, 0x4d, 0x2e, 0x47, 0xc1, 0x01, 0xaa, 0x02, 0x85]);
Name.ContentDigestSuffix = new Uint8Array([0x00]);

/**
 * Return component as an escaped string according to "CCNx URI Scheme".
 * We can't use encodeURIComponent because that doesn't encode all the characters we want to.
 */
Name.toEscapedString = function(component) {
    var result = "";
    var gotNonDot = false;
    for (var i = 0; i < component.length; ++i) {
        if (component[i] != 0x2e) {
            gotNonDot = true;
            break;
        }
    }
    if (!gotNonDot) {
        // Special case for component of zero or more periods.  Add 3 periods.
        result = "...";
        for (var i = 0; i < component.length; ++i)
            result += ".";
    }
    else {
        for (var i = 0; i < component.length; ++i) {
            var value = component[i];
            // Check for 0-9, A-Z, a-z, (+), (-), (.), (_)
            if (value >= 0x30 && value <= 0x39 || value >= 0x41 && value <= 0x5a ||
                value >= 0x61 && value <= 0x7a || value == 0x2b || value == 0x2d ||
                value == 0x2e || value == 0x5f)
                result += String.fromCharCode(value);
            else
                result += "%" + (value < 16 ? "0" : "") + value.toString(16).toUpperCase();
        }
    }
    return result;
};
<commit_msg>Added Name.getComponentContentDigestValue and use in getContentDigestValue.<commit_after>/**
 * @author: Meki Cheraoui, Jeff Thompson
 * See COPYING for copyright and distribution information.
 * This class represents a Name as an array of components where each is a byte array.
 */

/*
 * Create a new Name from _components.
 * If _components is a string, parse it as a URI.  Otherwise it is an array of components
 * where each is a string, byte array, ArrayBuffer or Uint8Array.
 * Convert and store as an array of Uint8Array.
 * If a component is a string, encode as utf8.
 */
var Name = function Name(_components){
	if( typeof _components == 'string') {
		if(LOG>3)console.log('Content Name String '+_components);
		this.components = Name.createNameArray(_components);
	}
	else if(typeof _components === 'object'){
		if(LOG>4)console.log('Content Name Array '+_components);
		this.components = [];
        for (var i = 0; i < _components.length; ++i)
            this.add(_components[i]);
	}
	else if(_components==null)
		this.components =[];
	else
		if(LOG>1)console.log("NO CONTENT NAME GIVEN");
};

Name.prototype.getName = function() {
    return this.to_uri();
};

/* Parse name as a URI and return an array of Uint8Array components.
 *
 */
Name.createNameArray = function(name) {
    name = name.trim();
    if (name.length <= 0)
        return [];

    var iColon = name.indexOf(':');
    if (iColon >= 0) {
        // Make sure the colon came before a '/'.
        var iFirstSlash = name.indexOf('/');
        if (iFirstSlash < 0 || iColon < iFirstSlash)
            // Omit the leading protocol such as ndn:
            name = name.substr(iColon + 1, name.length - iColon - 1).trim();
    }

  	if (name[0] == '/') {
        if (name.length >= 2 && name[1] == '/') {
            // Strip the authority following "//".
            var iAfterAuthority = name.indexOf('/', 2);
            if (iAfterAuthority < 0)
                // Unusual case: there was only an authority.
                return [];
            else
                name = name.substr(iAfterAuthority + 1, name.length - iAfterAuthority - 1).trim();
        }
        else
            name = name.substr(1, name.length - 1).trim();
    }

	var array = name.split('/');

    // Unescape the components.
    for (var i = 0; i < array.length; ++i) {
        var component = unescape(array[i].trim());

        if (component.match(/[^.]/) == null) {
            // Special case for component of only periods.
            if (component.length <= 2) {
                // Zero, one or two periods is illegal.  Ignore this componenent to be
                //   consistent with the C implmentation.
                // This also gets rid of a trailing '/'.
                array.splice(i, 1);
                --i;
                continue;
            }
            else
                // Remove 3 periods.
                array[i] = component.substr(3, component.length - 3);
        }
        else
            array[i] = component;

        // Change the component to Uint8Array now.
        array[i] = DataUtils.toNumbersFromString(array[i]);
    }

	return array;
}

Name.prototype.from_ccnb = function(/*XMLDecoder*/ decoder)  {
		decoder.readStartElement(this.getElementLabel());

		this.components = new Array(); //new ArrayList<byte []>();

		while (decoder.peekStartElement(CCNProtocolDTags.Component)) {
			this.add(decoder.readBinaryElement(CCNProtocolDTags.Component));
		}

		decoder.readEndElement();
};

Name.prototype.to_ccnb = function(/*XMLEncoder*/ encoder)  {

		if( this.components ==null )
			throw new Error("CANNOT ENCODE EMPTY CONTENT NAME");

		encoder.writeStartElement(this.getElementLabel());
		var count = this.components.length;
		for (var i=0; i < count; i++) {
			encoder.writeElement(CCNProtocolDTags.Component, this.components[i]);
		}
		encoder.writeEndElement();
};

Name.prototype.getElementLabel = function(){
	return CCNProtocolDTags.Name;
};

/*
 * component is a string, byte array, ArrayBuffer or Uint8Array.
 * Convert to Uint8Array and add to this Name.
 * If a component is a string, encode as utf8.
 * Return the converted value.
 */
Name.prototype.add = function(component){
    var result;
    if(typeof component == 'string')
        result = DataUtils.stringToUtf8Array(component);
	else if(typeof component == 'object' && component instanceof Uint8Array)
        result = new Uint8Array(component);
	else if(typeof component == 'object' && component instanceof ArrayBuffer) {
        // Make a copy.  Don't use ArrayBuffer.slice since it isn't always supported.
        result = new Uint8Array(new ArrayBuffer(component.byteLength));
        result.set(new Uint8Array(component));
    }
	else if(typeof component == 'object')
        // Assume component is a byte array.  We can't check instanceof Array because
        //   this doesn't work in JavaScript if the array comes from a different module.
        result = new Uint8Array(component);
	else
		throw new Error("Cannot add Name element at index " + this.components.length +
            ": Invalid type");

	return this.components.push(result);
};

// Return the escaped name string according to "CCNx URI Scheme".
Name.prototype.to_uri = function() {
	var result = "";

	for(var i = 0; i < this.components.length; ++i)
		result += "/"+ Name.toEscapedString(this.components[i]);

	return result;
};

/*
 * Return a new Name with the first nComponents components of this Name.
 */
Name.prototype.getPrefix = function(nComponents) {
    return new Name(this.components.slice(0, nComponents));
}

/*
 * Return a new ArrayBuffer of the component at i.
 */
Name.prototype.getComponent = function(i) {
    var result = new ArrayBuffer(this.components[i].length);
    new Uint8Array(result).set(this.components[i]);
    return result;
}

/*
 * The "file name" in a name is the last component that isn't blank and doesn't start with one of the
 *   special marker octets (for version, etc.).  Return the index in this.components of
 *   the file name, or -1 if not found.
 */
Name.prototype.indexOfFileName = function() {
    for (var i = this.components.length - 1; i >= 0; --i) {
        var component = this.components[i];
        if (component.length <= 0)
            continue;

        if (component[0] == 0 || component[0] == 0xC0 || component[0] == 0xC1 ||
            (component[0] >= 0xF5 && component[0] <= 0xFF))
            continue;

        return i;
    }

    return -1;
}

/*
 * Return true if this Name has the same components as name.
 */
Name.prototype.equalsName = function(name) {
    if (this.components.length != name.components.length)
        return false;

    // Start from the last component because they are more likely to differ.
    for (var i = this.components.length - 1; i >= 0; --i) {
        if (!DataUtils.arraysEqual(this.components[i], name.components[i]))
            return false;
    }

    return true;
}

/*
 * Find the last component in name that has a ContentDigest and return the digest value as Uint8Array,
 *   or null if not found.  See Name.getComponentContentDigestValue.
 */
Name.prototype.getContentDigestValue = function() {
    for (var i = this.components.length - 1; i >= 0; --i) {
        var digestValue = Name.getComponentContentDigestValue(this.components[i]);
        if (digestValue != null)
           return digestValue;
    }

    return null;
}

/*
 * If component is a ContentDigest, return the digest value as a Uint8Array subarray (don't modify!).
 * If not a ContentDigest, return null.
 * A ContentDigest component is Name.ContentDigestPrefix + 32 bytes + Name.ContentDigestSuffix.
 */
Name.getComponentContentDigestValue = function(component) {
    var digestComponentLength = Name.ContentDigestPrefix.length + 32 + Name.ContentDigestSuffix.length;
    // Check for the correct length and equal ContentDigestPrefix and ContentDigestSuffix.
    if (component.length == digestComponentLength &&
        DataUtils.arraysEqual(component.subarray(0, Name.ContentDigestPrefix.length),
                              Name.ContentDigestPrefix) &&
        DataUtils.arraysEqual(component.subarray
           (component.length - Name.ContentDigestSuffix.length, component.length),
                              Name.ContentDigestSuffix))
       return component.subarray(Name.ContentDigestPrefix.length, Name.ContentDigestPrefix.length + 32);
   else
       return null;
}

// Meta GUID "%C1.M.G%C1" + ContentDigest with a 32 byte BLOB.
Name.ContentDigestPrefix = new Uint8Array([0xc1, 0x2e, 0x4d, 0x2e, 0x47, 0xc1, 0x01, 0xaa, 0x02, 0x85]);
Name.ContentDigestSuffix = new Uint8Array([0x00]);

/**
 * Return component as an escaped string according to "CCNx URI Scheme".
 * We can't use encodeURIComponent because that doesn't encode all the characters we want to.
 */
Name.toEscapedString = function(component) {
    var result = "";
    var gotNonDot = false;
    for (var i = 0; i < component.length; ++i) {
        if (component[i] != 0x2e) {
            gotNonDot = true;
            break;
        }
    }
    if (!gotNonDot) {
        // Special case for component of zero or more periods.  Add 3 periods.
        result = "...";
        for (var i = 0; i < component.length; ++i)
            result += ".";
    }
    else {
        for (var i = 0; i < component.length; ++i) {
            var value = component[i];
            // Check for 0-9, A-Z, a-z, (+), (-), (.), (_)
            if (value >= 0x30 && value <= 0x39 || value >= 0x41 && value <= 0x5a ||
                value >= 0x61 && value <= 0x7a || value == 0x2b || value == 0x2d ||
                value == 0x2e || value == 0x5f)
                result += String.fromCharCode(value);
            else
                result += "%" + (value < 16 ? "0" : "") + value.toString(16).toUpperCase();
        }
    }
    return result;
};
<|endoftext|>