text:
/**
  * @author Kai Salmen / https://kaisalmen.de
  * Development repository: https://github.com/kaisalmen/WWOBJLoader
  */

'use strict';

if ( THREE.OBJLoader2 === undefined ) { THREE.OBJLoader2 = {} }

/**
 * OBJ data will be loaded by dynamically created web worker.
 * First feed instructions with: prepareRun
 * Then: Execute with: run
 * @class
 */
THREE.OBJLoader2.WWOBJLoader2 = (function () {

	var WWOBJLOADER2_VERSION = '1.2.1';

	var Validator = THREE.OBJLoader2.prototype._getValidator();

	function WWOBJLoader2() {
		this._init();
	}

	WWOBJLoader2.prototype._init = function () {
		console.log( "Using THREE.OBJLoader2.WWOBJLoader2 version: " + WWOBJLOADER2_VERSION );

		// check worker support first
		if ( window.Worker === undefined ) throw "This browser does not support web workers!";
		if ( window.Blob === undefined  ) throw "This browser does not support Blob!";
		if ( typeof window.URL.createObjectURL !== 'function'  ) throw "This browser does not support Object creation from URL!";

		this.instanceNo = 0;
		this.worker = null;
		this.workerCode = null;
		this.debug = false;

		this.sceneGraphBaseNode = null;
		this.streamMeshes = true;
		this.meshStore = null;
		this.modelName = 'none';
		this.validated = false;
		this.running = false;
		this.requestTerminate = false;

		this.clearAllCallbacks();

		this.manager = THREE.DefaultLoadingManager;
		this.fileLoader = new THREE.FileLoader( this.manager );
		this.mtlLoader = null;
		this.crossOrigin = null;

		this.dataAvailable = false;
		this.objAsArrayBuffer = null;
		this.fileObj = null;
		this.pathObj = null;

		this.fileMtl = null;
		this.mtlAsString = null;
		this.texturePath = null;

		this.materials = [];
		this.counter = 0;
	};

	/**
	 * Enable or disable debug logging.
	 * @memberOf THREE.OBJLoader2.WWOBJLoader2
	 *
	 * @param {boolean} enabled True or false
	 */
	WWOBJLoader2.prototype.setDebug = function ( enabled ) {
		this.debug = enabled;
	};

	/**
	 * Sets the CORS string to be used.
	 * @memberOf THREE.OBJLoader2.WWOBJLoader2
	 *
	 * @param {string} crossOrigin CORS value
	 */
	WWOBJLoader2.prototype.setCrossOrigin = function ( crossOrigin ) {
		this.crossOrigin = crossOrigin;
	};

	/**
	 * Register callback function that is invoked by internal function "_announceProgress" to print feedback.
	 * @memberOf THREE.OBJLoader2.WWOBJLoader2
	 *
	 * @param {callback} callbackProgress Callback function for described functionality
	 */
	WWOBJLoader2.prototype.registerCallbackProgress = function ( callbackProgress ) {
		if ( Validator.isValid( callbackProgress ) ) this.callbacks.progress.push( callbackProgress );
	};

	/**
	 * Register callback function that is called once loading of the complete model is completed.
	 * @memberOf THREE.OBJLoader2.WWOBJLoader2
	 *
	 * @param {callback} callbackCompletedLoading Callback function for described functionality
	 */
	WWOBJLoader2.prototype.registerCallbackCompletedLoading = function ( callbackCompletedLoading ) {
		if ( Validator.isValid( callbackCompletedLoading ) ) this.callbacks.completedLoading.push( callbackCompletedLoading );
	};

	/**
	 * Register callback function that is called once materials have been loaded. It allows to alter and return materials.
	 * @memberOf THREE.OBJLoader2.WWOBJLoader2
	 *
	 * @param {callback} callbackMaterialsLoaded Callback function for described functionality
	 */
	WWOBJLoader2.prototype.registerCallbackMaterialsLoaded = function ( callbackMaterialsLoaded ) {
		if ( Validator.isValid( callbackMaterialsLoaded ) ) this.callbacks.materialsLoaded.push( callbackMaterialsLoaded );
	};

	/**
	 * Register callback function that is called every time a mesh was loaded.
	 * Use {@link THREE.OBJLoader2.WWOBJLoader2.LoadedMeshUserOverride} for alteration instructions (geometry, material or disregard mesh).
	 * @memberOf THREE.OBJLoader2.WWOBJLoader2
	 *
	 * @param {callback} callbackMeshLoaded Callback function for described functionality
	 */
	WWOBJLoader2.prototype.registerCallbackMeshLoaded = function ( callbackMeshLoaded ) {
		if ( Validator.isValid( callbackMeshLoaded ) ) this.callbacks.meshLoaded.push( callbackMeshLoaded );
	};

	/**
	 * Register callback function that is called to report an error that prevented loading.
	 * @memberOf THREE.OBJLoader2.WWOBJLoader2
	 *
	 * @param {callback} callbackErrorWhileLoading Callback function for described functionality
	 */
	WWOBJLoader2.prototype.registerCallbackErrorWhileLoading = function ( callbackErrorWhileLoading ) {
		if ( Validator.isValid( callbackErrorWhileLoading ) ) this.callbacks.errorWhileLoading.push( callbackErrorWhileLoading );
	};

	/**
	 * Clears all registered callbacks.
	 * @memberOf THREE.OBJLoader2.WWOBJLoader2
	 */
	WWOBJLoader2.prototype.clearAllCallbacks = function () {
		this.callbacks = {
			progress: [],
			completedLoading: [],
			errorWhileLoading: [],
			materialsLoaded: [],
			meshLoaded: []
		};
	};

	/**
	 * Call requestTerminate to terminate the web worker and free local resource after execution.
	 * @memberOf THREE.OBJLoader2.WWOBJLoader2
	 *
	 * @param {boolean} requestTerminate True or false
	 */
	WWOBJLoader2.prototype.setRequestTerminate = function ( requestTerminate ) {
		this.requestTerminate = requestTerminate === true;
	};

	WWOBJLoader2.prototype._validate = function () {
		if ( this.validated ) return;
		if ( ! Validator.isValid( this.worker ) ) {

			this._buildWebWorkerCode();
			var blob = new Blob( [ this.workerCode ], { type: 'text/plain' } );
			this.worker = new Worker( window.URL.createObjectURL( blob ) );

			var scope = this;
			var scopeFunction = function ( e ) {
				scope._receiveWorkerMessage( e );
			};
			this.worker.addEventListener( 'message', scopeFunction, false );

		}

		this.sceneGraphBaseNode = null;
		this.streamMeshes = true;
		this.meshStore = [];
		this.modelName = 'none';
		this.validated = true;
		this.running = true;
		this.requestTerminate = false;

		this.fileLoader = Validator.verifyInput( this.fileLoader, new THREE.FileLoader( this.manager ) );
		this.mtlLoader = Validator.verifyInput( this.mtlLoader, new THREE.MTLLoader() );
		if ( Validator.isValid( this.crossOrigin ) ) this.mtlLoader.setCrossOrigin( this.crossOrigin );

		this.dataAvailable = false;
		this.fileObj = null;
		this.pathObj = null;
		this.fileMtl = null;
		this.texturePath = null;

		this.objAsArrayBuffer = null;
		this.mtlAsString = null;

		this.materials = [];
		var defaultMaterial = new THREE.MeshStandardMaterial( { color: 0xDCF1FF } );
		defaultMaterial.name = 'defaultMaterial';
		this.materials[ defaultMaterial.name ] = defaultMaterial;

		this.counter = 0;
	};

	/**
	 * Set all parameters for required for execution of "run".
	 * @memberOf THREE.OBJLoader2.WWOBJLoader2
	 *
	 * @param {Object} params Either {@link THREE.OBJLoader2.WWOBJLoader2.PrepDataArrayBuffer} or {@link THREE.OBJLoader2.WWOBJLoader2.PrepDataFile}
	 */
	WWOBJLoader2.prototype.prepareRun = function ( params ) {
		this._validate();
		this.dataAvailable = params.dataAvailable;
		this.modelName = params.modelName;
		console.time( 'WWOBJLoader2' );
		if ( this.dataAvailable ) {

			// fast-fail on bad type
			if ( ! ( params.objAsArrayBuffer instanceof Uint8Array ) ) {
				throw 'Provided input is not of type arraybuffer! Aborting...';
			}

			this.worker.postMessage( {
				cmd: 'init',
				debug: this.debug
			} );

			this.objAsArrayBuffer = params.objAsArrayBuffer;
			this.mtlAsString = params.mtlAsString;

		} else {

			// fast-fail on bad type
			if ( ! ( typeof( params.fileObj ) === 'string' || params.fileObj instanceof String ) ) {
				throw 'Provided file is not properly defined! Aborting...';
			}

			this.worker.postMessage( {
				cmd: 'init',
				debug: this.debug
			} );

			this.fileObj = params.fileObj;
			this.pathObj = params.pathObj;
			this.fileMtl = params.fileMtl;

		}
		this.setRequestTerminate( params.requestTerminate );
		this.pathTexture = params.pathTexture;
		this.sceneGraphBaseNode = params.sceneGraphBaseNode;
		this.streamMeshes = params.streamMeshes;
		if ( ! this.streamMeshes ) this.meshStore = [];
	};

	/**
	 * Run the loader according the preparation instruction provided in "prepareRun".
	 * @memberOf THREE.OBJLoader2.WWOBJLoader2
	 */
	WWOBJLoader2.prototype.run = function () {
		var scope = this;
		var processLoadedMaterials = function ( materialCreator ) {
			var materialCreatorMaterials = [];
			var materialNames = [];
			if ( Validator.isValid( materialCreator ) ) {

				materialCreator.preload();
				materialCreatorMaterials = materialCreator.materials;
				for ( var materialName in materialCreatorMaterials ) {

					if ( materialCreatorMaterials.hasOwnProperty( materialName ) ) {

						materialNames.push( materialName );
						scope.materials[ materialName ] = materialCreatorMaterials[ materialName ];

					}

				}

			}
			scope.worker.postMessage( {
				cmd: 'setMaterials',
				materialNames: materialNames
			} );

			var materialsFromCallback;
			var callbackMaterialsLoaded;
			for ( var index in scope.callbacks.materialsLoaded ) {

				callbackMaterialsLoaded = scope.callbacks.materialsLoaded[ index ];
				materialsFromCallback = callbackMaterialsLoaded( scope.materials );
				if ( Validator.isValid( materialsFromCallback ) ) scope.materials = materialsFromCallback;

			}
			if ( scope.dataAvailable && scope.objAsArrayBuffer ) {

				scope.worker.postMessage({
					cmd: 'run',
					objAsArrayBuffer: scope.objAsArrayBuffer
				}, [ scope.objAsArrayBuffer.buffer ] );

			} else {

				var refPercentComplete = 0;
				var percentComplete = 0;
				var onLoad = function ( objAsArrayBuffer ) {

					scope._announceProgress( 'Running web worker!' );
					scope.objAsArrayBuffer = new Uint8Array( objAsArrayBuffer );
					scope.worker.postMessage( {
						cmd: 'run',
						objAsArrayBuffer: scope.objAsArrayBuffer
					}, [ scope.objAsArrayBuffer.buffer ] );

				};

				var onProgress = function ( event ) {
					if ( ! event.lengthComputable ) return;

					percentComplete = Math.round( event.loaded / event.total * 100 );
					if ( percentComplete > refPercentComplete ) {

						refPercentComplete = percentComplete;
						var output = 'Download of "' + scope.fileObj + '": ' + percentComplete + '%';
						console.log( output );
						scope._announceProgress( output );

					}
				};

				var onError = function ( event ) {
					var output = 'Error occurred while downloading "' + scope.fileObj + '"';
					console.error( output + ': ' + event );
					scope._announceProgress( output );
					scope._finalize( 'error' );

				};

				scope.fileLoader.setPath( scope.pathObj );
				scope.fileLoader.setResponseType( 'arraybuffer' );
				scope.fileLoader.load( scope.fileObj, onLoad, onProgress, onError );
			}
			console.timeEnd( 'Loading MTL textures' );
		};

		this.mtlLoader.setPath( this.pathTexture );
		if ( this.dataAvailable ) {

			processLoadedMaterials( Validator.isValid( this.mtlAsString ) ? this.mtlLoader.parse( this.mtlAsString ) : null );

		} else {

			if ( Validator.isValid( this.fileMtl ) ) {

				var onError = function ( event ) {
					var output = 'Error occurred while downloading "' + scope.fileMtl + '"';
					console.error( output + ': ' + event );
					scope._announceProgress( output );
					scope._finalize( 'error' );
				};

				this.mtlLoader.load( this.fileMtl, processLoadedMaterials, undefined, onError );

			} else {

				processLoadedMaterials();

			}

		}
	};

	WWOBJLoader2.prototype._receiveWorkerMessage = function ( event ) {
		var payload = event.data;

		switch ( payload.cmd ) {
			case 'objData':

				this.counter++;
				var meshName = payload.meshName;

				var bufferGeometry = new THREE.BufferGeometry();
				bufferGeometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( payload.vertices ), 3 ) );
				if ( Validator.isValid( payload.normals ) ) {

					bufferGeometry.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( payload.normals ), 3 ) );

				} else {

					bufferGeometry.computeVertexNormals();

				}
				if ( Validator.isValid( payload.uvs ) ) {

					bufferGeometry.addAttribute( 'uv', new THREE.BufferAttribute( new Float32Array( payload.uvs ), 2 ) );

				}

				var materialDescriptions = payload.materialDescriptions;
				var materialDescription;
				var material;
				var materialName;
				var createMultiMaterial = payload.multiMaterial;
				var multiMaterials = [];

				var key;
				for ( key in materialDescriptions ) {

					materialDescription = materialDescriptions[ key ];
					material = this.materials[ materialDescription.name ];

					if ( materialDescription.default ) {

						material = this.materials[ 'defaultMaterial' ];

					} else if ( materialDescription.clone ) {

						materialName = material.name + '_flat';
						var materialClone = this.materials[ materialName ];
						if ( ! materialClone ) {

							materialClone = material.clone();
							materialClone.name = materialName;
							materialClone.shading = THREE.FlatShading;
							this.materials[ materialName ] = name;

						}

					} else if ( ! material ) {

						material = this.materials[ 'defaultMaterial' ];

					}
					if ( createMultiMaterial ) multiMaterials.push( material );

				}
				if ( createMultiMaterial ) {

					material = multiMaterials;
					var materialGroups = payload.materialGroups;
					var materialGroup;
					for ( key in materialGroups ) {

						materialGroup = materialGroups[ key ];
						bufferGeometry.addGroup( materialGroup.start, materialGroup.count, materialGroup.index );

					}

				}

				var callbackMeshLoaded;
				var callbackMeshLoadedResult;
				var disregardMesh = false;
				for ( var index in this.callbacks.meshLoaded ) {

					callbackMeshLoaded = this.callbacks.meshLoaded[ index ];
					callbackMeshLoadedResult = callbackMeshLoaded( meshName, bufferGeometry, material );

					if ( Validator.isValid( callbackMeshLoadedResult ) ) {

						if ( callbackMeshLoadedResult.disregardMesh ) {

							// if one callback disregards the mesh, then processing stops
							disregardMesh = true;
							break;

						}
						if ( callbackMeshLoadedResult.replaceBufferGeometry ) bufferGeometry = callbackMeshLoadedResult.bufferGeometry;
						if ( callbackMeshLoadedResult.replaceMaterial ) material = callbackMeshLoadedResult.material;

					}

				}

				if ( !disregardMesh ) {

					var mesh = new THREE.Mesh( bufferGeometry, material );
					mesh.name = meshName;

					if ( this.streamMeshes ) {

						this.sceneGraphBaseNode.add( mesh );

					} else {

						this.meshStore.push( mesh );

					}
					this._announceProgress( 'Adding mesh (' + this.counter + '):', meshName );

				} else {

					this._announceProgress( 'Removing mesh:', meshName );

				}
				break;

			case 'complete':

				if ( ! this.streamMeshes ) {

					for ( var meshStoreKey in this.meshStore ) {

						if ( this.meshStore.hasOwnProperty( meshStoreKey ) ) this.sceneGraphBaseNode.add( this.meshStore[ meshStoreKey ] );

					}

				}

				console.timeEnd( 'WWOBJLoader2' );
				if ( Validator.isValid( payload.msg ) ) {

					this._announceProgress( payload.msg );

				} else {

					this._announceProgress( '' );

				}

				this._finalize( 'complete' );
				break;

			case 'report_progress':
				this._announceProgress( '', payload.output );
				break;

			default:
				console.error( 'Received unknown command: ' + payload.cmd );
				break;

		}
	};

	WWOBJLoader2.prototype._terminate = function () {
		if ( Validator.isValid( this.worker ) ) {

			if ( this.running ) throw 'Unable to gracefully terminate worker as it is currently running!';

			this.worker.terminate();
			this.worker = null;
			this.workerCode = null;
			this._finalize( 'terminate' );

		}
		this.fileLoader = null;
		this.mtlLoader = null;
	};

	WWOBJLoader2.prototype._finalize = function ( reason, requestTerminate ) {
		this.running = false;
		var index;
		var callback;

		if ( reason === 'complete' ) {

			for ( index in this.callbacks.completedLoading ) {

				callback = this.callbacks.completedLoading[ index ];
				callback( this.modelName, this.instanceNo, this.requestTerminate );

			}

		} else if ( reason === 'error' ) {

			for ( index in this.callbacks.errorWhileLoading ) {

				callback = this.callbacks.errorWhileLoading[ index ];
				callback( this.modelName, this.instanceNo, this.requestTerminate );

			}

		}
		this.validated = false;

		this.setRequestTerminate( requestTerminate );

		if ( this.requestTerminate ) {
			this._terminate();
		}
	};

	WWOBJLoader2.prototype._announceProgress = function ( baseText, text ) {
		var output = Validator.isValid( baseText ) ? baseText: "";
		output = Validator.isValid( text ) ? output + " " + text : output;

		var callbackProgress;
		for ( var index in this.callbacks.progress ) {

			callbackProgress = this.callbacks.progress[ index ];
			callbackProgress( output );

		}

		if ( this.debug ) console.log( output );
	};

	WWOBJLoader2.prototype._buildWebWorkerCode = function ( existingWorkerCode ) {
		if ( Validator.isValid( existingWorkerCode ) ) this.workerCode = existingWorkerCode;
		if ( ! Validator.isValid( this.workerCode ) ) {

			console.time( 'buildWebWorkerCode' );
			var wwDef = (function () {

				function WWOBJLoader() {
					this.wwMeshCreator = new WWMeshCreator();
					this.parser = new Parser( this.wwMeshCreator );
					this.validated = false;
					this.cmdState = 'created';

					this.debug = false;
				}

				/**
				 * Allows to set debug mode for the parser and the meshCreatorDebug
				 *
				 * @param parserDebug
				 * @param meshCreatorDebug
				 */
				WWOBJLoader.prototype.setDebug = function ( parserDebug, meshCreatorDebug ) {
					this.parser.setDebug( parserDebug );
					this.wwMeshCreator.setDebug( meshCreatorDebug );
				};

				/**
				 * Validate status, then parse arrayBuffer, finalize and return objGroup
				 *
				 * @param arrayBuffer
				 */
				WWOBJLoader.prototype.parse = function ( arrayBuffer ) {
					console.log( 'Parsing arrayBuffer...' );
					console.time( 'parseArrayBuffer' );

					this.validate();
					this.parser.parseArrayBuffer( arrayBuffer );
					var objGroup = this._finalize();

					console.timeEnd( 'parseArrayBuffer' );

					return objGroup;
				};

				WWOBJLoader.prototype.validate = function () {
					if ( this.validated ) return;

					this.parser.validate();
					this.wwMeshCreator.validate();

					this.validated = true;
				};

				WWOBJLoader.prototype._finalize = function () {
					console.log( 'Global output object count: ' + this.wwMeshCreator.globalObjectCount );
					this.parser.finalize();
					this.wwMeshCreator.finalize();
					this.validated = false;
				};

				WWOBJLoader.prototype.init = function ( payload ) {
					this.cmdState = 'init';
					this.setDebug( payload.debug, payload.debug );
				};

				WWOBJLoader.prototype.setMaterials = function ( payload ) {
					this.cmdState = 'setMaterials';
					this.wwMeshCreator.setMaterials( payload.materialNames );
				};

				WWOBJLoader.prototype.run = function ( payload ) {
					this.cmdState = 'run';

					this.parse( payload.objAsArrayBuffer );
					console.log( 'OBJ loading complete!' );

					this.cmdState = 'complete';
					self.postMessage( {
						cmd: this.cmdState,
						msg: null
					} );
				};

				return WWOBJLoader;
			})();

			var wwMeshCreatorDef = (function () {

				function WWMeshCreator() {
					this.materials = null;
					this.debug = false;
					this.globalObjectCount = 1;
					this.validated = false;
				}

				WWMeshCreator.prototype.setMaterials = function ( materials ) {
					this.materials = Validator.verifyInput( materials, this.materials );
					this.materials = Validator.verifyInput( this.materials, { materials: [] } );
				};

				WWMeshCreator.prototype.setDebug = function ( debug ) {
					if ( debug === true || debug === false ) this.debug = debug;
				};

				WWMeshCreator.prototype.validate = function () {
					if ( this.validated ) return;

					this.setMaterials( null );
					this.setDebug( null );
					this.globalObjectCount = 1;
				};

				WWMeshCreator.prototype.finalize = function () {
					this.materials = null;
					this.validated = false;
				};

				/**
				 * RawObjectDescriptions are transformed to THREE.Mesh.
				 * It is ensured that rawObjectDescriptions only contain objects with vertices (no need to check).
				 *
				 * @param rawObjectDescriptions
				 * @param inputObjectCount
				 * @param absoluteVertexCount
				 * @param absoluteNormalCount
				 * @param absoluteUvCount
				 */
				WWMeshCreator.prototype.buildMesh = function ( rawObjectDescriptions, inputObjectCount, absoluteVertexCount, absoluteNormalCount, absoluteUvCount ) {
					if ( this.debug ) console.log( 'OBJLoader.buildMesh:\nInput object no.: ' + inputObjectCount );

					var vertexFa = new Float32Array( absoluteVertexCount );
					var normalFA = ( absoluteNormalCount > 0 ) ? new Float32Array( absoluteNormalCount ) : null;
					var uvFA = ( absoluteUvCount > 0 ) ? new Float32Array( absoluteUvCount ) : null;

					var rawObjectDescription;
					var materialDescription;
					var materialDescriptions = [];

					var createMultiMaterial = ( rawObjectDescriptions.length > 1 );
					var materialIndex = 0;
					var materialIndexMapping = [];
					var selectedMaterialIndex;
					var materialGroup;
					var materialGroups = [];

					var vertexBAOffset = 0;
					var vertexGroupOffset = 0;
					var vertexLength;
					var normalOffset = 0;
					var uvOffset = 0;

					for ( var oodIndex in rawObjectDescriptions ) {
						if ( ! rawObjectDescriptions.hasOwnProperty( oodIndex ) ) continue;
						rawObjectDescription = rawObjectDescriptions[ oodIndex ];

						materialDescription = { name: rawObjectDescription.materialName, flat: false, default: false };
						if ( this.materials[ materialDescription.name ] === null ) {

							materialDescription.default = true;
							console.warn( 'object_group "' + rawObjectDescription.objectName + '_' + rawObjectDescription.groupName + '" was defined without material! Assigning "defaultMaterial".' );

						}
						// Attach '_flat' to materialName in case flat shading is needed due to smoothingGroup 0
						if ( rawObjectDescription.smoothingGroup === 0 ) materialDescription.flat = true;

						vertexLength = rawObjectDescription.vertices.length;
						if ( createMultiMaterial ) {

							// re-use material if already used before. Reduces materials array size and eliminates duplicates

							selectedMaterialIndex = materialIndexMapping[ materialDescription.name ];
							if ( ! selectedMaterialIndex ) {

								selectedMaterialIndex = materialIndex;
								materialIndexMapping[ materialDescription.name ] = materialIndex;
								materialDescriptions.push( materialDescription );
								materialIndex++;

							}
							materialGroup = {
								start: vertexGroupOffset,
								count: vertexLength / 3,
								index: selectedMaterialIndex
							};
							materialGroups.push( materialGroup );
							vertexGroupOffset += vertexLength / 3;

						} else {

							materialDescriptions.push( materialDescription );

						}

						vertexFa.set( rawObjectDescription.vertices, vertexBAOffset );
						vertexBAOffset += vertexLength;

						if ( normalFA ) {

							normalFA.set( rawObjectDescription.normals, normalOffset );
							normalOffset += rawObjectDescription.normals.length;

						}
						if ( uvFA ) {

							uvFA.set( rawObjectDescription.uvs, uvOffset );
							uvOffset += rawObjectDescription.uvs.length;

						}
						if ( this.debug ) this.printReport( rawObjectDescription, selectedMaterialIndex );

					}

					self.postMessage( {
						cmd: 'objData',
						meshName: rawObjectDescription.objectName,
						multiMaterial: createMultiMaterial,
						materialDescriptions: materialDescriptions,
						materialGroups: materialGroups,
						vertices: vertexFa,
						normals: normalFA,
						uvs: uvFA
					}, [ vertexFa.buffer ], normalFA !== null ? [ normalFA.buffer ] : null, uvFA !== null ? [ uvFA.buffer ] : null );

					this.globalObjectCount++;
				};

				return WWMeshCreator;
			})();

			var wwObjLoaderRunnerDef = (function () {

				function WWOBJLoaderRunner() {
					self.addEventListener( 'message', this.runner, false );
				}

				WWOBJLoaderRunner.prototype.runner = function ( event ) {
					var payload = event.data;

					console.log( 'Command state before: ' + WWOBJLoaderRef.cmdState );

					switch ( payload.cmd ) {
						case 'init':

							WWOBJLoaderRef.init( payload );
							break;

						case 'setMaterials':

							WWOBJLoaderRef.setMaterials( payload );
							break;

						case 'run':

							WWOBJLoaderRef.run( payload );
							break;

						default:

							console.error( 'OBJLoader: Received unknown command: ' + payload.cmd );
							break;

					}

					console.log( 'Command state after: ' + WWOBJLoaderRef.cmdState );
				};

				return WWOBJLoaderRunner;
			})();

			var buildObject = function ( fullName, object ) {
				var objectString = fullName + ' = {\n';
				var part;
				for ( var name in object ) {

					part = object[ name ];
					if ( typeof( part ) === 'string' || part instanceof String ) {

						part = part.replace( '\n', '\\n' );
						part = part.replace( '\r', '\\r' );
						objectString += '\t' + name + ': "' + part + '",\n';

					} else if ( part instanceof Array ) {

						objectString += '\t' + name + ': [' + part + '],\n';

					} else if ( Number.isInteger( part ) ) {

						objectString += '\t' + name + ': ' + part + ',\n';

					} else if ( typeof part === 'function' ) {

						objectString += '\t' + name + ': ' + part + ',\n';

					}

				}
				objectString += '}\n\n';

				return objectString;
			};

			var buildSingelton = function ( fullName, internalName, object ) {
				var objectString = fullName + ' = (function () {\n\n';
				objectString += '\t' + object.prototype.constructor.toString() + '\n\n';

				var funcString;
				var objectPart;
				for ( var name in object.prototype ) {

					objectPart = object.prototype[ name ];
					if ( typeof objectPart === 'function' ) {

						funcString = objectPart.toString();
						objectString += '\t' + internalName + '.prototype.' + name + ' = ' + funcString + ';\n\n';

					}

				}
				objectString += '\treturn ' + internalName + ';\n';
				objectString += '})();\n\n';

				return objectString;
			};

			this.workerCode = '';
			this.workerCode += '/**\n';
			this.workerCode += '  * This code was constructed by WWOBJLoader2._buildWebWorkerCode\n';
			this.workerCode += '  */\n\n';

			// parser re-construction
			this.workerCode += THREE.OBJLoader2.prototype._buildWebWorkerCode( buildObject, buildSingelton );

			// web worker construction
			this.workerCode += buildSingelton( 'WWOBJLoader', 'WWOBJLoader', wwDef );
			this.workerCode += buildSingelton( 'WWMeshCreator', 'WWMeshCreator', wwMeshCreatorDef );
			this.workerCode += 'WWOBJLoaderRef = new WWOBJLoader();\n\n';
			this.workerCode += buildSingelton( 'WWOBJLoaderRunner', 'WWOBJLoaderRunner', wwObjLoaderRunnerDef );
			this.workerCode += 'new WWOBJLoaderRunner();\n\n';

			console.timeEnd( 'buildWebWorkerCode' );
		}

		return this.workerCode;
	};

	return WWOBJLoader2;

})();

/**
 * Instruction to configure {@link THREE.OBJLoader2.WWOBJLoader2}.prepareRun to load OBJ from given ArrayBuffer and MTL from given String.
 *
 * @param {string} modelName Overall name of the model
 * @param {Uint8Array} objAsArrayBuffer OBJ file content as ArrayBuffer
 * @param {string} pathTexture Path to texture files
 * @param {string} mtlAsString MTL file content as string
 *
 * @returns {{modelName: string, dataAvailable: boolean, objAsArrayBuffer: null, pathTexture: null, mtlAsString: null, sceneGraphBaseNode: null, streamMeshes: boolean, requestTerminate: boolean}}
 * @constructor
 */
THREE.OBJLoader2.WWOBJLoader2.PrepDataArrayBuffer = function ( modelName, objAsArrayBuffer, pathTexture, mtlAsString ) {

	var Validator = THREE.OBJLoader2.prototype._getValidator();

	return {

		/**
		 * {@link THREE.Object3D} where meshes will be attached.
		 * @memberOf THREE.OBJLoader2.WWOBJLoader2.PrepDataArrayBuffer
		 *
		 * @param {THREE.Object3D} sceneGraphBaseNode Scene graph object
		 */
		setSceneGraphBaseNode: function ( sceneGraphBaseNode ) {
			this.sceneGraphBaseNode = Validator.verifyInput( sceneGraphBaseNode, null );
		},

		/**
		 * Singles meshes are directly integrated into scene when loaded or later.
		 * @memberOf THREE.OBJLoader2.WWOBJLoader2.PrepDataArrayBuffer
		 *
		 * @param {boolean} streamMeshes=true Default is true
		 */
		setStreamMeshes: function ( streamMeshes ) {
			this.streamMeshes = streamMeshes !== false;
		},

		/**
		 * Request termination of web worker and free local resources after execution.
		 * @memberOf THREE.OBJLoader2.WWOBJLoader2.PrepDataArrayBuffer
		 *
		 * @param {boolean} requestTerminate=false Default is false
		 */
		setRequestTerminate: function ( requestTerminate ) {
			this.requestTerminate = requestTerminate === true;
		},

		/**
		 * Returns all callbacks as {@link THREE.OBJLoader2.WWOBJLoader2.PrepDataCallbacks}
		 * @memberOf THREE.OBJLoader2.WWOBJLoader2.PrepDataArrayBuffer
		 *
		 * @returns {THREE.OBJLoader2.WWOBJLoader2.PrepDataCallbacks}
		 */
		getCallbacks: function () {
			return this.callbacks;
		},
		modelName: Validator.verifyInput( modelName, 'none' ),
		dataAvailable: true,
		objAsArrayBuffer: Validator.verifyInput( objAsArrayBuffer, null ),
		pathTexture: Validator.verifyInput( pathTexture, null ),
		mtlAsString: Validator.verifyInput( mtlAsString, null ),
		sceneGraphBaseNode: null,
		streamMeshes: true,
		requestTerminate: false,
		callbacks: new THREE.OBJLoader2.WWOBJLoader2.PrepDataCallbacks()
	};
};

/**
 * Instruction to configure {@link THREE.OBJLoader2.WWOBJLoader2}.prepareRun to load OBJ and MTL from files.
 *
 * @param {string} modelName Overall name of the model
 * @param {string} pathObj Path to OBJ file
 * @param {string} fileObj OBJ file name
 * @param {string} pathTexture Path to texture files
 * @param {string} fileMtl MTL file name
 *
 * @returns {{modelName: string, dataAvailable: boolean, pathObj: null, fileObj: null, pathTexture: null, fileMtl: null, sceneGraphBaseNode: null, streamMeshes: boolean,  requestTerminate: boolean}}
 * @constructor
 */
THREE.OBJLoader2.WWOBJLoader2.PrepDataFile = function ( modelName, pathObj, fileObj, pathTexture, fileMtl ) {

	var Validator = THREE.OBJLoader2.prototype._getValidator();

	return {

		/**
		 * {@link THREE.Object3D} where meshes will be attached.
		 * @memberOf THREE.OBJLoader2.WWOBJLoader2.PrepDataFile
		 *
		 * @param {THREE.Object3D} sceneGraphBaseNode Scene graph object
		 */
		setSceneGraphBaseNode: function ( sceneGraphBaseNode ) {
			this.sceneGraphBaseNode = Validator.verifyInput( sceneGraphBaseNode, null );
		},

		/**
		 * Singles meshes are directly integrated into scene when loaded or later.
		 * @memberOf THREE.OBJLoader2.WWOBJLoader2.PrepDataFile
		 *
		 * @param {boolean} streamMeshes=true Default is true
		 */
		setStreamMeshes: function ( streamMeshes ) {
			this.streamMeshes = streamMeshes !== false;
		},

		/**
		 * Request termination of web worker and free local resources after execution.
		 * @memberOf THREE.OBJLoader2.WWOBJLoader2.PrepDataFile
		 *
		 * @param {boolean} requestTerminate=false Default is false
		 */
		setRequestTerminate: function ( requestTerminate ) {
			this.requestTerminate = requestTerminate === true;
		},

		/**
		 * Returns all callbacks as {@link THREE.OBJLoader2.WWOBJLoader2.PrepDataCallbacks}
		 * @memberOf THREE.OBJLoader2.WWOBJLoader2.PrepDataFile
		 *
		 * @returns {THREE.OBJLoader2.WWOBJLoader2.PrepDataCallbacks}
		 */
		getCallbacks: function () {
			return this.callbacks;
		},
		modelName: Validator.verifyInput( modelName, 'none' ),
		dataAvailable: false,
		pathObj: Validator.verifyInput( pathObj, null ),
		fileObj: Validator.verifyInput( fileObj, null ),
		pathTexture: Validator.verifyInput( pathTexture, null ),
		fileMtl: Validator.verifyInput( fileMtl, null ),
		sceneGraphBaseNode: null,
		streamMeshes: true,
		requestTerminate: false,
		callbacks: new THREE.OBJLoader2.WWOBJLoader2.PrepDataCallbacks()
	};
};

/**
 * Callbacks utilized by functions working with {@link THREE.OBJLoader2.WWOBJLoader2.PrepDataArrayBuffer} or {@link THREE.OBJLoader2.WWOBJLoader2.PrepDataFile}
 *
 * @returns {{registerCallbackProgress: THREE.OBJLoader2.WWOBJLoader2.PrepDataCallbacks.registerCallbackProgress, registerCallbackCompletedLoading: THREE.OBJLoader2.WWOBJLoader2.PrepDataCallbacks.registerCallbackCompletedLoading, registerCallbackMaterialsLoaded: THREE.OBJLoader2.WWOBJLoader2.PrepDataCallbacks.registerCallbackMaterialsLoaded, registerCallbackMeshLoaded: THREE.OBJLoader2.WWOBJLoader2.PrepDataCallbacks.registerCallbackMeshLoaded, registerCallbackErrorWhileLoading: THREE.OBJLoader2.WWOBJLoader2.PrepDataCallbacks.registerCallbackErrorWhileLoading, progress: null, completedLoading: null, errorWhileLoading: null, materialsLoaded: null, meshLoaded: null}}
 * @constructor
 */
THREE.OBJLoader2.WWOBJLoader2.PrepDataCallbacks = function () {

	var Validator = THREE.OBJLoader2.prototype._getValidator();

	return {
		/**
		 * Register callback function that is invoked by internal function "_announceProgress" to print feedback.
		 * @memberOf THREE.OBJLoader2.WWOBJLoader2.PrepDataCallbacks
		 *
		 * @param {callback} callbackProgress Callback function for described functionality
		 */
		registerCallbackProgress: function ( callbackProgress ) {
			if ( Validator.isValid( callbackProgress ) ) this.progress = callbackProgress;
		},

		/**
		 * Register callback function that is called once loading of the complete model is completed.
		 * @memberOf THREE.OBJLoader2.WWOBJLoader2.PrepDataCallbacks
		 *
		 * @param {callback} callbackCompletedLoading Callback function for described functionality
		 */
		registerCallbackCompletedLoading: function ( callbackCompletedLoading ) {
			if ( Validator.isValid( callbackCompletedLoading ) ) this.completedLoading = callbackCompletedLoading;
		},

		/**
		 * Register callback function that is called once materials have been loaded. It allows to alter and return materials.
		 * @memberOf THREE.OBJLoader2.WWOBJLoader2.PrepDataCallbacks
		 *
		 * @param {callback} callbackMaterialsLoaded Callback function for described functionality
		 */
		registerCallbackMaterialsLoaded: function ( callbackMaterialsLoaded ) {
			if ( Validator.isValid( callbackMaterialsLoaded ) ) this.materialsLoaded = callbackMaterialsLoaded;
		},

		/**
		 * Register callback function that is called every time a mesh was loaded.
		 * Use {@link THREE.OBJLoader2.WWOBJLoader2.LoadedMeshUserOverride} for alteration instructions (geometry, material or disregard mesh).
		 * @memberOf THREE.OBJLoader2.WWOBJLoader2.PrepDataCallbacks
		 *
		 * @param {callback} callbackMeshLoaded Callback function for described functionality
		 */
		registerCallbackMeshLoaded: function ( callbackMeshLoaded ) {
			if ( Validator.isValid( callbackMeshLoaded ) ) this.meshLoaded = callbackMeshLoaded;
		},

		/**
		 * Report if an error prevented loading.
		 * @memberOf THREE.OBJLoader2.WWOBJLoader2.PrepDataCallbacks
		 *
		 * @param {callback} callbackErrorWhileLoading Callback function for described functionality
		 */
		registerCallbackErrorWhileLoading: function ( callbackErrorWhileLoading ) {
			if ( Validator.isValid( callbackErrorWhileLoading ) ) this.errorWhileLoading = callbackErrorWhileLoading;
		},

		progress: null,
		completedLoading: null,
		errorWhileLoading: null,
		materialsLoaded: null,
		meshLoaded: null
	};
};

/**
 * Object to return by {@link THREE.OBJLoader2.WWOBJLoader2}.callbacks.meshLoaded. Used to adjust bufferGeometry or material or prevent complete loading of mesh
 *
 * @param {boolean} disregardMesh=false Tell WWOBJLoader2 to completely disregard this mesh
 * @param {THREE.BufferGeometry} bufferGeometry The {@link THREE.BufferGeometry} to be used
 * @param {THREE.Material} material The {@link THREE.Material} to be used
 *
 * @returns {{ disregardMesh: boolean, replaceBufferGeometry: boolean, bufferGeometry: THREE.BufferGeometry, replaceMaterial: boolean, material: THREE.Material}}
 * @constructor
 */
THREE.OBJLoader2.WWOBJLoader2.LoadedMeshUserOverride = function ( disregardMesh, bufferGeometry, material ) {

	var Validator = THREE.OBJLoader2.prototype._getValidator();

	return {
		disregardMesh: disregardMesh === true,
		replaceBufferGeometry: Validator.isValid( bufferGeometry ),
		bufferGeometry: Validator.verifyInput( bufferGeometry, null ),
		replaceMaterial: Validator.isValid( material ),
		material: Validator.verifyInput( material, null )
	};
};

/**
 * Orchestrate loading of multiple OBJ files/data from an instruction queue with a configurable amount of workers (1-16).
 * Workflow:
 *   prepareWorkers
 *   enqueueForRun
 *   processQueue
 *   deregister
 *
 * @class
 */
THREE.OBJLoader2.WWOBJLoader2Director = (function () {

	var Validator = THREE.OBJLoader2.prototype._getValidator();

	var MAX_WEB_WORKER = 16;
	var MAX_QUEUE_SIZE = 1024;

	function WWOBJLoader2Director() {
		this.maxQueueSize = MAX_QUEUE_SIZE ;
		this.maxWebWorkers = MAX_WEB_WORKER;
		this.crossOrigin = null;

		this.workerDescription = {
			prototypeDef: THREE.OBJLoader2.WWOBJLoader2.prototype,
			globalCallbacks: {},
			webWorkers: [],
			codeBuffer: null
		};
		this.objectsCompleted = 0;
		this.instructionQueue = [];
	}

	/**
	 * Returns the maximum length of the instruction queue.
	 * @memberOf THREE.OBJLoader2.WWOBJLoader2Director
	 *
	 * @returns {number}
	 */
	WWOBJLoader2Director.prototype.getMaxQueueSize = function () {
		return this.maxQueueSize;
	};

	/**
	 * Returns the maximum number of workers.
	 * @memberOf THREE.OBJLoader2.WWOBJLoader2Director
	 *
	 * @returns {number}
	 */
	WWOBJLoader2Director.prototype.getMaxWebWorkers = function () {
		return this.maxWebWorkers;
	};

	/**
	 * Sets the CORS string to be used.
	 * @memberOf THREE.OBJLoader2.WWOBJLoader2Director
	 *
	 * @param {string} crossOrigin CORS value
	 */
	WWOBJLoader2Director.prototype.setCrossOrigin = function ( crossOrigin ) {
		this.crossOrigin = crossOrigin;
	};

	/**
	 * Create or destroy workers according limits. Set the name and register callbacks for dynamically created web workers.
	 * @memberOf THREE.OBJLoader2.WWOBJLoader2Director
	 *
	 * @param {THREE.OBJLoader2.WWOBJLoader2.PrepDataCallbacks} globalCallbacks  Register global callbacks used by all web workers
	 * @param {number} maxQueueSize Set the maximum size of the instruction queue (1-1024)
	 * @param {number} maxWebWorkers Set the maximum amount of workers (1-16)
	 */
	WWOBJLoader2Director.prototype.prepareWorkers = function ( globalCallbacks, maxQueueSize, maxWebWorkers ) {
		if ( Validator.isValid( globalCallbacks ) ) this.workerDescription.globalCallbacks = globalCallbacks;
		this.maxQueueSize = Math.min( maxQueueSize, MAX_QUEUE_SIZE );
		this.maxWebWorkers = Math.min( maxWebWorkers, MAX_WEB_WORKER );
		this.objectsCompleted = 0;
		this.instructionQueue = [];

		var start = this.workerDescription.webWorkers.length;
		if ( start < this.maxWebWorkers ) {

			for ( i = start; i < this.maxWebWorkers; i ++ ) {

				webWorker = this._buildWebWorker();
				this.workerDescription.webWorkers[ i ] = webWorker;

			}

		} else {

			for ( var webWorker, i = start - 1; i >= this.maxWebWorkers; i-- ) {

				webWorker = this.workerDescription.webWorkers[ i ];
				webWorker.setRequestTerminate( true );

				this.workerDescription.webWorkers.pop();

			}

		}
	};

	/**
	 * Store run instructions in internal instructionQueue.
	 * @memberOf THREE.OBJLoader2.WWOBJLoader2Director
	 *
	 * @param {Object} runParams Either {@link THREE.OBJLoader2.WWOBJLoader2.PrepDataArrayBuffer} or {@link THREE.OBJLoader2.WWOBJLoader2.PrepDataFile}
	 */
	WWOBJLoader2Director.prototype.enqueueForRun = function ( runParams ) {
		if ( this.instructionQueue.length < this.maxQueueSize ) {
			this.instructionQueue.push( runParams );
		}
	};

	/**
	 * Process the instructionQueue until it is depleted.
	 * @memberOf THREE.OBJLoader2.WWOBJLoader2Director
	 */
	WWOBJLoader2Director.prototype.processQueue = function () {
		if ( this.instructionQueue.length === 0 ) return;

		var length = Math.min( this.maxWebWorkers, this.instructionQueue.length );
		for ( var i = 0; i < length; i++ ) {

			this._kickWebWorkerRun( this.workerDescription.webWorkers[ i ], this.instructionQueue[ 0 ] );
			this.instructionQueue.shift();

		}
	};

	WWOBJLoader2Director.prototype._kickWebWorkerRun = function( worker, runParams ) {
		worker.clearAllCallbacks();
		var key;
		var globalCallbacks = this.workerDescription.globalCallbacks;
		var workerCallbacks = worker.callbacks;
		var selectedGlobalCallback;
		for ( key in globalCallbacks ) {

			if ( workerCallbacks.hasOwnProperty( key ) && globalCallbacks.hasOwnProperty( key ) ) {

				selectedGlobalCallback = globalCallbacks[ key ];
				if ( Validator.isValid( selectedGlobalCallback ) ) workerCallbacks[ key ].push( selectedGlobalCallback );

			}

		}
		// register per object callbacks
		var runCallbacks = runParams.callbacks;
		if ( Validator.isValid( runCallbacks ) ) {

			for ( key in runCallbacks ) {

				if ( workerCallbacks.hasOwnProperty( key ) && runCallbacks.hasOwnProperty( key ) && Validator.isValid( runCallbacks[ key ] ) ) {

					workerCallbacks[ key ].push( runCallbacks[ key ] );

				}

			}

		}

		var scope = this;
		var directorCompletedLoading = function ( modelName, instanceNo, requestTerminate ) {
			scope.objectsCompleted++;
			if ( ! requestTerminate ) {

				var worker = scope.workerDescription.webWorkers[ instanceNo ];
				var runParams = scope.instructionQueue[ 0 ];
				if ( Validator.isValid( runParams ) ) {

					console.log( '\nAssigning next item from queue to worker (queue length: ' + scope.instructionQueue.length + ')\n\n' );
					scope._kickWebWorkerRun( worker, runParams );
					scope.instructionQueue.shift();

				}

			}
		};
		worker.registerCallbackCompletedLoading( directorCompletedLoading );

		worker.prepareRun( runParams );
		worker.run();
	};

	WWOBJLoader2Director.prototype._buildWebWorker = function () {
		var webWorker = Object.create( this.workerDescription.prototypeDef );
		webWorker._init();
		if ( Validator.isValid( this.crossOrigin ) ) webWorker.setCrossOrigin( this.crossOrigin );

		// Ensure code string is built once and then it is just passed on to every new instance
		if ( Validator.isValid( this.workerDescription.codeBuffer ) ) {

			webWorker._buildWebWorkerCode( this.workerDescription.codeBuffer );

		} else {

			this.workerDescription.codeBuffer = webWorker._buildWebWorkerCode();

		}

		webWorker.instanceNo = this.workerDescription.webWorkers.length;
		this.workerDescription.webWorkers.push( webWorker );
		return webWorker;
	};

	/**
	 * Terminate all workers.
	 * @memberOf THREE.OBJLoader2.WWOBJLoader2Director
	 */
	WWOBJLoader2Director.prototype.deregister = function () {
		console.log( 'WWOBJLoader2Director received the unregister call. Terminating all workers!' );
		for ( var i = 0, webWorker, length = this.workerDescription.webWorkers.length; i < length; i++ ) {

			webWorker = this.workerDescription.webWorkers[ i ];
			webWorker.setRequestTerminate( true );

		}
		this.workerDescription.globalCallbacks = {};
		this.workerDescription.webWorkers = [];
		this.workerDescription.codeBuffer = null;
	};

	return WWOBJLoader2Director;

})();


text:
import sys, tempfile

if sys.version_info >= (3, 0):
    from urllib.request import urlopen
    from urllib.parse import urlencode
else:
    from urllib2 import urlopen
    from urllib import urlencode

class MediaDownloader:
    def __init__(self, successClbk = None, errorClbk = None, progressCallback = None):
        self.successCallback = successClbk
        self.errorCallback = errorClbk
        self.progressCallback = progressCallback

    def download(self, url = ""):
        try:

            if not url:
                if self.url:
                    url = "https://" if self.port == 443 else "http://"
                    url = url + self.url
                    url = url + "?" + urlencode(self.params)
                    print(url)
                else:
                    raise Exception("No url specified for fetching")

            u = urlopen(url)

            path = tempfile.mkstemp()[1]
            f = open(path, "wb")
            meta = u.info()

            if sys.version_info >= (3, 0):
                fileSize = int(u.getheader("Content-Length"))
            else:
                fileSize = int(meta.getheaders("Content-Length")[0])

            fileSizeDl = 0
            blockSz = 8192
            lastEmit = 0
            while True:
                buf = u.read(blockSz)

                if not buf:
                    break

                fileSizeDl += len(buf)
                f.write(buf)
                status = (fileSizeDl * 100 / fileSize)

                if self.progressCallback and lastEmit != status:
                    self.progressCallback(int(status))
                    lastEmit = status;

            f.close()
            if self.successCallback:
                self.successCallback(path)
        except:
            print("Error occured at transfer %s"%sys.exc_info()[1])
            if self.errorCallback:
                self.errorCallback();

redpajama_set_name: RedPajamaGithub


text:
export class AshaWorkerPaymentRulesModule{
    const
}


text:
System.register([], function (exports_1, context_1) {
  "use strict";
  var __moduleName = context_1 && context_1.id;
  var CharSerializer;
  return {
    setters: [],
    execute: function () {
      /**
       * Created by sargon on 7/18/16.
       */
      CharSerializer = (function () {
        function CharSerializer() {
        }

        CharSerializer.serializeChar = function (char) {
          return JSON.stringify(char);
        };
        CharSerializer.deserializeChar = function (charStr) {
          return JSON.parse(charStr);
        };
        return CharSerializer;
      }());
      exports_1("CharSerializer", CharSerializer);
    }
  }
});
//# sourceMappingURL=charSerializer.js.map


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">

  <title>CSS Block Box Model: overconstrained horizontal box model and minimum widths</title>

The following two DIVs should be the same width (resulting in a single 4 by 2 block).


text:
from django.test import TestCase
from . import models

class PageTest(TestCase):
    def test_slug(self):
        page = models.Page()
        page.title = "Slug me"
        page.save()

        self.assertEqual(models.Page.objects.get(slug="slug-me"), page)

    def test_url(self):
        page = models.Page()
        page.slug = "slug-me"

        self.assertEqual("/pages/slug-me", page.url())


text:
<?php

namespace tests\codeception\_support;

// here you can define custom actions
// all public methods declared in helper class will be available in $I

class UnitHelper extends \Codeception\Module
{
    public function fetchTheLastModelPk($class)
    {
        return $class::find()->orderBy([reset($class::primaryKey()) => SORT_DESC])->scalar();
    }
}


text:
.bdsharebuttonbox a{border-bottom:0;width:28px;height:28px;line-height:28px;color: #fff;}
.bds_renren{background:#94b3eb;}
.bds_qzone{background:#fac33f;}
.bds_more{background:#40a57d;}
.bds_weixin{background:#7ad071;}
.bdsharebuttonbox a:hover{background-color:#7fb4ab;color: #fff;border-bottom:0;}


text:
<?php
namespace Cerad\Bundle\Legacy2012Bundle\EntityRepository;

use Doctrine\ORM\EntityRepository;

class OrgRepository extends EntityRepository
{
    // Kind of hokay but think of this as an extended EntityManager
    public function clear()        { $this->_em->clear(); }
    public function flush()        { $this->_em->flush(); }
    public function remove ($item) { $this->_em->remove ($item); }
    public function detach ($item) { $this->_em->detach ($item); }
    public function persist($item) { $this->_em->persist($item); }
    public function refresh($item) { $this->_em->refresh($item); }

    public function getDatabaseConnection() { return $this->_em->getConnection(); }
    public function getEventManager      () { return $this->_em->getEventManager(); }

}
?>


text:
@class ELGLocationTracker;
@class ELGAlertManager;
@class ELGDataStore;

@interface ELGAppAssembly : NSObject

@property (strong, nonatomic, readonly) ELGLocationTracker *locationTracker;
@property (strong, nonatomic, readonly) ELGAlertManager *alertManager;
@property (strong, nonatomic, readonly) ELGDataStore *dataStore;

- (instancetype)initWithError:(NSError **)error;

@end


text:
<?php

namespace Magento\Framework\DB;

use Magento\Framework\Api\CriteriaInterface;

/**
 * Class GenericMapper
 */
class GenericMapper extends AbstractMapper
{
    /**
     * Set initial conditions
     *
     * @return void
     */
    protected function init()
    {
        //
    }

    /**
     * Map criteria list
     *
     * @param \Magento\Framework\Api\CriteriaInterface[] $criteriaList
     * @return void
     */
    public function mapCriteriaList(array $criteriaList)
    {
        foreach ($criteriaList as $criteria) {
            /** @var CriteriaInterface $criteria */
            $mapper = $criteria->getMapperInterfaceName();
            $mapperInstance = $this->mapperFactory->create($mapper, ['select' => $this->select]);
            $this->select = $mapperInstance->map($criteria);
        }
    }

    /**
     * Map filters
     *
     * @param array $filters
     * @return void
     */
    public function mapFilters(array $filters)
    {
        $this->renderFiltersBefore();
        foreach ($filters as $filter) {
            switch ($filter['type']) {
                case 'or':
                    $condition = $this->getConnection()->quoteInto($filter['field'] . '=?', $filter['condition']);
                    $this->getSelect()->orWhere($condition);
                    break;
                case 'string':
                    $this->getSelect()->where($filter['condition']);
                    break;
                case 'public':
                    $field = $this->getMappedField($filter['field']);
                    $condition = $filter['condition'];
                    $this->getSelect()->where($this->getConditionSql($field, $condition), null, Select::TYPE_CONDITION);
                    break;
                default:
                    $condition = $this->getConnection()->quoteInto($filter['field'] . '=?', $filter['condition']);
                    $this->getSelect()->where($condition);
            }
        }
    }

    /**
     * Map order
     *
     * @param array $orders
     * @return void
     */
    public function mapOrders(array $orders)
    {
        foreach ($orders as $field => $direction) {
            $this->select->order(new \Zend_Db_Expr($field . ' ' . $direction));
        }
    }

    /**
     * Map fields
     *
     * @param array $fields
     * @throws \Zend_Db_Select_Exception
     * @return void
     * @SuppressWarnings(PHPMD.NPathComplexity)
     */
    public function mapFields(array $fields)
    {
        $columns = $this->getSelect()->getPart(\Magento\Framework\DB\Select::COLUMNS);
        $selectedUniqueNames = [];
        foreach ($fields as $fieldInfo) {
            if (is_string($fieldInfo)) {
                $fieldInfo = isset($this->map[$fieldInfo]) ? $this->map[$fieldInfo] : $fieldInfo;
            }
            list($correlationName, $field, $alias) = $fieldInfo;
            if (!is_string($alias)) {
                $alias = null;
            }
            if ($field instanceof \Zend_Db_Expr) {
                $field = $field->__toString();
            }
            $selectedUniqueName = $alias ?: $field;
            if (in_array($selectedUniqueName, $selectedUniqueNames)) {
                // ignore field since the alias is already used by another field
                continue;
            }
            $selectedUniqueNames[] = $selectedUniqueName;
            $columns[] = [$correlationName, $field, $alias];
        }
        $this->getSelect()->setPart(\Magento\Framework\DB\Select::COLUMNS, $columns);
    }

    /**
     * Map limit
     *
     * @param int $offset
     * @param int $size
     * @return void
     */
    public function mapLimit($offset, $size)
    {
        $this->select->limitPage($offset, $size);
    }

    /**
     * Map distinct flag
     *
     * @param bool $flag
     * @return void
     */
    public function mapDistinct($flag)
    {
        $this->select->distinct($flag);
    }
}


text:
copyright:
  years: 2016
lastupdated: "2017-05-03"

---

{:new_window: target="_blank"}
{:shortdesc: .shortdesc}
{:screen: .screen}
{:codeblock: .codeblock}
{:pre: .pre}

# Utilisation de {{site.data.keyword.DRA_short}} (version bêta)
{: #di_working}

{{site.data.keyword.DRA_full}} vous permet d'assurer la maintenance et d'améliorer la qualité de votre code dans
{{site.data.keyword.Bluemix_notm}} en surveillant vos déploiements pour identifier des risques avant leur mise en service.
{:shortdesc}

{{site.data.keyword.DRA_short}} collecte et analyse les résultats provenant de tests unitaires, de tests fonctionnels et d'outils de couverture de code afin de déterminer si votre code satisfait les règles prédéfinies à des stades spécifiques de votre processus de déploiement. Si votre code ne satisfait pas ou dépasse une règle, le déploiement est interrompu afin de prévenir tout risque. Vous pouvez utiliser {{site.data.keyword.DRA_short}} comme filet de sécurité pour votre environnement de distribution continue ou comme moyen d'implémenter et d'améliorer les normes qualité.

Pour plus d'informations, voir [Initiation à {{site.data.keyword.DRA_short}} (version bêta)](/docs/services/DevOpsInsights/index.html).


text:
module Casein
  class <%= class_name.pluralize %>Controller < Casein::CaseinController

    ## optional filters for defining usage according to Casein::Users access_levels
    # before_filter :needs_admin, :except => [:action1, :action2]
    # before_filter :needs_admin_or_current_user, :only => [:action1, :action2]

    def index
      @casein_page_title = '<%= plural_name.humanize.capitalize %>'
  		@<%= plural_name %> = <%= class_name %>.paginate :page => params[:page]
    end

    def show
      @casein_page_title = 'View <%= singular_name.humanize.downcase %>'
      @<%= singular_name %> = <%= class_name %>.find params[:id]
    end

    def new
      @casein_page_title = 'Add a new <%= singular_name.humanize.downcase %>'
    	@<%= singular_name %> = <%= class_name %>.new
    end

    def create
      @<%= singular_name %> = <%= class_name %>.new params[:<%= singular_name %>]

      if @<%= singular_name %>.save
        flash[:notice] = '<%= singular_name.humanize.capitalize %> created'
        redirect_to casein_<%= @plural_route %>_path
      else
        flash.now[:warning] = 'There were problems when trying to create a new <%= singular_name.humanize.downcase %>'
        render :action => :new
      end
    end

    def update
      @casein_page_title = 'Update <%= singular_name.humanize.downcase %>'

      @<%= singular_name %> = <%= class_name %>.find params[:id]

      if @<%= singular_name %>.update_attributes params[:<%= singular_name %>]
        flash[:notice] = '<%= singular_name.humanize.capitalize %> has been updated'
        redirect_to casein_<%= @plural_route %>_path
      else
        flash.now[:warning] = 'There were problems when trying to update this <%= singular_name.humanize.downcase %>'
        render :action => :show
      end
    end

    def destroy
      @<%= singular_name %> = <%= class_name %>.find params[:id]

      @<%= singular_name %>.destroy
      flash[:notice] = '<%= singular_name.humanize.capitalize %> has been deleted'
      redirect_to casein_<%= @plural_route %>_path
    end

  end
end


text:
require "helpers/integration_test_helper"
require "integration/factories/target_pools_factory"

class TestTargetPools < FogIntegrationTest
  include TestCollection

  def setup
    @subject = Fog::Compute[:google].target_pools
    @factory = TargetPoolsFactory.new(namespaced_name)
    @servers = Fog::Compute[:google].servers
  end

  # Override to include zone in get request
  def get_resource(identity)
    @subject.get(identity, TEST_ZONE)
  end

  def test_get_health
    target_pool = @factory.create
    server = @servers.get(target_pool.instances[0].split("/").last)
    server.wait_for { ready? }

    # XXX This is not partucularly elegant but if the instance doesn't respond
    # to the healthcheck at all (for example there's nothing listening) it'll
    # enter "No instance health info was found." state, during which the API
    # will return an empty health object instead of UNHEALTHY.
    # To avoid setting up a brittle environment with a live healthcheck we just
    # stop the instance so health check returns UNHEALTHY and we can test that
    # all fields are returned correctly.
    server.stop
    server.wait_for { stopped? }

    # There's no way to track the readiness of the instance resource in a target pool,
    # so wrapping in a soft retry:
    begin
      retries ||= 0
      target_pool.get_health
    rescue ::Google::Apis::ClientError
      sleep 25
      retry if (retries += 1) < 3
    end

    refute_empty(target_pool.health_checks, "Target pool should have a health check")
    assert_equal(2, target_pool.instances.count, "Target pool should have 2 instances")
    assert_equal([{ :health_state => "UNHEALTHY",
                    :instance => server.self_link }],
                 target_pool.get_health[server.self_link],
                 "Target pool should return a proper health check list")
    assert_equal({ server.self_link =>
                      [{ :health_state => "UNHEALTHY",
                         :instance => server.self_link }] },
                 target_pool.get_health(server.name),
                 "target_pool should return instance health details when an instance is specified")
  end
end


text:
<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20160817221258 extends AbstractMigration
{
    /**
     * @param Schema $schema
     */
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');
        $this->addSql('ALTER TABLE nomenclature ADD CONSTRAINT fk_nomenclature_dep_idx FOREIGN KEY (departid) REFERENCES department (id) ON UPDATE CASCADE ON DELETE CASCADE');
        $this->addSql('CREATE INDEX namenomenclature ON nomenclature (nomenclname)');

    }

    /**
     * @param Schema $schema
     */
    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE nomenclature ADD CONSTRAINT fk_nomenclature_dep_idx FOREIGN KEY (departid) REFERENCES department (id) ON UPDATE CASCADE ON DELETE CASCADE');
        $this->addSql('DROP INDEX namenomenclature ON nomenclature');
    }
}


text: export { ChartBarTarget20 as default } from "../../";


text:
package game.map;

import game.graphics.sprite.ItemSprite;
import game.graphics.sprite.Sprite;
import game.item.Item;

import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import utility.Position;
import utility.Quad;

/**
 * Map represents all data contained in
 *
 * @author Aaron Carson
 * @version Jul 25, 2015
 */
public abstract class Map
{
	public static final byte	PATH			= 0;
	public static final byte	WALL			= 1;
	public static final byte	OUT_OF_BOUNDS	= 2;

	// ************************************************************************
	// Fields
	// ************************************************************************

	protected byte[][]			cells;
	protected Quad[][]			quads;

	protected Sprite[][]	    spriteGrid;
	protected List<Sprite>		sprites;

	private String				name;

	protected int				width;
	protected int				height;
	protected int				tileSize;
	protected int				widthInPixels;
	protected int				heightInPixels;

	protected Random			random;

	// ************************************************************************
	// Constructors
	// ************************************************************************

	/**
	 * Create a new, blank Map of square tiles.
	 *
	 * @param name The name of this map.
	 * @param width The width in cells.
	 * @param height The height in cells.
	 * @param tileSize The dimension of each tile, in pixels.
	 */
	public Map(String name, int width, int height, int tileSize) {
		this.name = name;
		this.width = width;
		this.height = height;
		this.tileSize = tileSize;
		this.widthInPixels = this.width * tileSize;
		this.heightInPixels = this.height * tileSize;
		this.random = new Random();

		this.sprites = new ArrayList<Sprite>();
		this.spriteGrid = new Sprite[width][height];

		// initialize the Quads.
		this.quads = new Quad[width][height];
		double ht = tileSize / 2;
		// initialize the values.
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				Quad q = new Quad(x * tileSize + ht, y * tileSize + ht, ht, ht);
				quads[x][y] = q;
			}
		}
	}

	// ************************************************************************
	// Methods
	// ************************************************************************

	/**
	 * Adds the Sprite.  If the sprite collides, then it must occupy a unique
	 * slot in the spriteGrid.
	 * @param sprite The Sprite to add.
	 * @return True, if the Sprite was added.
	 */
	public boolean addSprite(Sprite sprite){
		int x = (int)(sprite.hitbox.x / tileSize);
		int y = (int)(sprite.hitbox.y / tileSize);
		return addSprite(sprite, x, y);
	}

	/**
	 * Adds the Sprite.  If the sprite collides, then it must occupy a unique
	 * slot in the spriteGrid.
	 * @param sprite The Sprite to add.
	 * @param x The x coordinate to insert at (for speed)
	 * @param y The y coordinate to insert at (for speed)
	 * @return True, if the Sprite was added.
	 */
	public boolean addSprite(Sprite sprite, int x, int y){
		if(sprite.collides){

			// if sprite collides, and the new slot is occupied.
			if(spriteGrid[x][y] != null){
				return false;
			}

			// the slot is open, and the sprite could be added.
			else if (sprites.add(sprite)){
				spriteGrid[x][y] = sprite;
				return true;
			}

			// the add failed.
			else{
				return false;
			}
		}

		// the sprite does not collide.
		return sprites.add(sprite);
	}

	/**
	 * Get the name of this map.
	 *
	 * @return
	 */
	public String getName() {
		return name;
	}

	/**
	 * Get the width of this Map, in tiles.
	 *
	 * @return The width in tiles.
	 */
	public int getWidth() {
		return width;
	}

	/**
	 * Get the height of this Map, in tiles.
	 *
	 * @return The height in tiles.
	 */
	public int getHeight() {
		return height;
	}

	/**
	 * Get the tileSize.
	 *
	 * @return the tile size, in pixels (width and height).
	 */
	public int getTileSize() {
		return tileSize;
	}

	/**
	 * Get the width of this Map, in pixels.
	 *
	 * @return
	 */
	public int getWidthInPixels() {
		return widthInPixels;
	}

	/**
	 * Get the Height of this Map in pixels.
	 *
	 * @return
	 */
	public int getHeightInPixels() {
		return heightInPixels;
	}

	/**
	 * Check if the given coordinate is within bounds, so x is from 0 inclusive
	 * to width exclusive, and y is from 0 inclusive and height inclusive.
	 *
	 * @param x The x coordinate to check.
	 * @param y The y coordinate to check.
	 * @return True, if the cell coordinate of (x, y) is within bounds.
	 */
	public boolean withinBounds(int x, int y) {
		return 0 <= x && x < width && 0 <= y && y < height;
	}

	/**
	 * Check if the given coordinate is passable (does a within bounds check;
	 * any coordinate outside of the Map boundaries is considered not passable)
	 *
	 * @param x The x coordinate to check.
	 * @param y The y coordinate to check.
	 * @return True, if the cell at (x, y) is passable.
	 */
	public boolean isPassable(int x, int y) {
		return withinBounds(x, y) && cells[x][y] == PATH;
	}

	/**
	 * Check if the given coordinate is occupied.
	 *
	 * @param x The x coordinate to check.
	 * @param y The y coordinate to check.
	 * @return True, if the cell at (x, y) is occupied.
	 */
	public boolean isOccupied(int x, int y) {
		return cells[x][y] == WALL || spriteGrid[x][y] != null;
	}

	/**
	 * Get the value of the cell at the given x and y coordinates.
	 *
	 * @param x The x coordinate to check.
	 * @param y The y coordinate to check.
	 * @return The byte value of the cell at (x, y).
	 */
	public byte getCell(int x, int y) {
		return withinBounds(x, y) ? cells[x][y] : OUT_OF_BOUNDS;
	}

	/**
	 * Get the cells byte[][] storing WALL/PATH data of this Map.
	 *
	 * @return The cells byte[][].
	 */
	public byte[][] getCells() {
		return cells;
	}

	public Quad[][] getQuads() {
		return quads;
	}

	/**
	 * Get a list of sprites that were added to this list.
	 * @return
	 */
	public List<Sprite> getSprites(){
		return sprites;
	}

	/**
	 * Find a randomly selected, empty position on this map.
	 *
	 * @return An empty position
	 */
	public Position getEmptyGridPosition() {
		int x, y;
		// find an empty position.
		do {
			x = random.nextInt(width);
			y = random.nextInt(height);
		} while (!isPassable(x, y));

		return new Position(x, y);
	}

	public Position getUnoccupiedGridPosition(){
		int x, y;
		// find an empty position.
		do {
			x = random.nextInt(width);
			y = random.nextInt(height);
		} while (isOccupied(x, y));

		return new Position(x, y);
	}

	/**
	 * Add The given item to the Map.  Automatically creates the ItemSprite
	 * from the Item's properties.
	 * @param item The item to add.
	 */
	public void addItem(Item item, boolean sparkle){
		Position p = getUnoccupiedGridPosition();
		int ix = p.x() * tileSize + tileSize/2;
		int iy = p.y() * tileSize + tileSize/2;

		addSprite(new ItemSprite(item, ix, iy, sparkle), p.x(), p.y());
	}

	/**
	 * Find a randomly selected, empty position on this map.
	 *
	 * @return An empty position
	 */
	public Position getEmptyAbsolutePosition() {
		Position p = getEmptyGridPosition();
		p.set(p.x() * tileSize, p.y() * tileSize);
		return p;
	}

	/**
	 * Adjust the given Quad for colliding with the Map boundaries.
	 *
	 * @param hitbox
	 */
	public void adjustForMapBoundaries(Quad hitbox) {
		// ****************************
		// adjust for any collisions.
		// ****************************
		// keep within bounds of map.
		if (hitbox.x < hitbox.halfWidth) {
			hitbox.x = hitbox.halfWidth;
			// System.out.println("out of bounds - LEFT");
		}
		else if (hitbox.x >= widthInPixels - hitbox.halfWidth) {
			hitbox.x = widthInPixels - hitbox.halfWidth;
			// System.out.println("out of bounds - RIGHT");
		}
		if (hitbox.y < hitbox.halfHeight) {
			hitbox.y = hitbox.halfHeight;
			// System.out.println("out of bounds - UP");
		}
		else if (hitbox.y >= heightInPixels - hitbox.halfHeight) {
			hitbox.y = heightInPixels - hitbox.halfHeight;
			// System.out.println("out of bounds - DOWN");
		}
	}

	/**
	 * Adjusts the given Quad
	 *
	 * @param quad The Quad to adjust for collisions on.
	 */
	public void adjustForCollisions(Quad quad) {

		// ********************
		// quadtrees:
		// ********************
		// http://gamedevelopment.tutsplus.com/tutorials/quick-tip-use-quadtrees-to-detect-likely-collisions-in-2d-space--gamedev-374

		// ********************
		// collision detection:
		// ********************
		// http://gamedevelopment.tutsplus.com/tutorials/collision-detection-with-the-separating-axis-theorem--gamedev-169
		// cast as ints
		int left = (int) quad.getLeftX();
		int right = (int) quad.getRightX();
		int top = (int) quad.getTopY();
		int bottom = (int) quad.getBottomY();

		// System.out.printf("l: %d r: %d t: %d b: %d\n", left, right, top,
		// bottom);

		// indices are guaranteed to be within the boundaries of the map.
		int ix = left /= tileSize;
		int iy = top /= tileSize;

		// check the four possible surrounding tiles.
		Quad t = quads[ix][iy];
		byte b = cells[ix][iy];
		if (b == WALL) quad.fixIfCollides(t);
		boolean checkX = ix + 1 < width;
		boolean checkY = iy + 1 < height;

		if (checkX) {
			t = quads[ix + 1][iy];
			b = cells[ix + 1][iy];
			if (b == WALL) quad.fixIfCollides(t);
		}
		if (checkY) {
			t = quads[ix][iy + 1];
			b = cells[ix][iy + 1];
			if (b == WALL) quad.fixIfCollides(t);
		}
		if (checkX && checkY) {
			t = quads[ix + 1][iy + 1];
			b = cells[ix + 1][iy + 1];
			if (b == WALL) quad.fixIfCollides(t);
		}

		//QuadTree tree = new QuadTree();
		for(Sprite s : sprites){
			//tree.insert(s);
			quad.fixIfCollides(s.hitbox);
		}
		//List<Sprite> matches = new ArrayList<>();
		//tree.getSprites(quad);
		//for(Sprite s : matches){
		//	quad.fixIfCollides(s.hitbox);
		//}

	}

	/**
	 * Create a pre-rendered background image for the entire map.
	 *
	 * @return A pre-rendered image for the entire background graphic.
	 */
	public abstract BufferedImage createBackgroundImage();

	/**
	 * Create a pre-rendered background image for the entire foreground.
	 *
	 * @return A pre-rendered image for the foreground graphic.
	 */
	public abstract BufferedImage createForegroundImage();

	/**
	 * Create a pre-rendered lighting image for the entire map.
	 *
	 * @return A pre-rendered image for the entire Map that is a lighting mask.
	 *         The alpha value of each pixel determines how light and shadow
	 *         falls; an alpha of zero will be rendered as black (not visible),
	 *         while an alpha of 255 will be the rendered the original tile
	 *         color (completely visible).
	 */
	public abstract BufferedImage createLightMaskImage();

}


text:
package io.jenkins.blueocean.rest;

import hudson.ExtensionPoint;
import io.jenkins.blueocean.Routable;

/**
 * Marks the REST API endpoints that are exposed by {@link ApiHead}
 *
 * @author Kohsuke Kawaguchi
 * @author Vivek Pandey
 */
public interface ApiRoutable extends Routable, ExtensionPoint {
    /**
     * See Action.getUrlName() for contract.
     */
    String getUrlName();
}


text:
/*********************************************************************
  Serve up a client script from within this module.

  When this script is run as a Node.js module, it will intercept the
  request handler, check whether the request is asking for a
  particular file it is responsible for.  If a matched URL is found,
  it will use the pathMap (provided by the customer code) to identify
  the file within the module that should be served up, and serves it up.

  Inspired by socket.io, with hints taken from lib/static.js and lib/manager.js
*********************************************************************/

var fs = require('fs');

function createFileSenderCB(req, res) {
	return function (err, data) {
		res.writeHead(200);
		res.end(data);
	};
}

module.exports = {
	/*
	  Set up the request handler interception, get a mapping of URL
	  requests to file names
	 */
	init: function (server, pathLookup) {
		this.pathLookup = pathLookup;
		this.server = server;
		var self = this;

		// reset listeners
		this.oldListeners = server.listeners('request').splice(0);
		server.removeAllListeners('request');

		// One request handler
		server.on('request', function (req, res) {
			self.handleRequest(req, res);
		});
	},
	handleRequest: function (req, res) {
		var data = this.checkRequest(req); // Do we handle this specially, or let the standard HTTP listeners handle it?

		if (!data) {
			for (var i = 0, l = this.oldListeners.length; i < l; i++) {
				this.oldListeners[i].call(this.server, req, res);
			}

			return;
		}
		// If we made it here, we need to send the appropriate file
		var filename = this.pathLookup[req.url];
		fs.readFile(__dirname + '/' + filename, createFileSenderCB(req, res));
	},
	checkRequest: function (req) {
		var url = req.url;
		console.log("Checking URL " + url);
		if (url in this.pathLookup) {
			return true;
		}
		return false;
	}
};


text:
#include "paddle/fluid/framework/io/crypto/cipher_utils.h"

#include <gtest/gtest.h>

#include <fstream>
#include <string>

namespace paddle {
namespace framework {

TEST(CipherUtils, load_config) {
  std::string filename("cryptotest_config_file.conf");

  std::ofstream fout(filename, std::ios::out);
  fout << "# anotation test line:"
          " must have two space along ':'."
       << std::endl;
  std::vector<std::string> key_value;
  key_value.emplace_back("key_str : ciphername");
  key_value.emplace_back("key_int : 1");
  key_value.emplace_back("key_bool : true");
  key_value.emplace_back("key_bool1 : false");
  key_value.emplace_back("key_bool2 : 0");
  for (auto& i : key_value) {
    fout << i << std::endl;
  }
  fout.close();

  auto config = CipherUtils::LoadConfig(filename);

  std::string out_str;
  EXPECT_TRUE(CipherUtils::GetValue<std::string>(config, "key_str", &out_str));
  EXPECT_EQ(out_str, std::string("ciphername"));

  int out_int;
  EXPECT_TRUE(CipherUtils::GetValue<int>(config, "key_int", &out_int));
  EXPECT_EQ(out_int, 1);

  bool out_bool;
  EXPECT_TRUE(CipherUtils::GetValue<bool>(config, "key_bool", &out_bool));
  EXPECT_EQ(out_bool, true);

  bool out_bool1;
  EXPECT_TRUE(CipherUtils::GetValue<bool>(config, "key_bool1", &out_bool1));
  EXPECT_EQ(out_bool1, false);

  bool out_bool2;
  EXPECT_TRUE(CipherUtils::GetValue<bool>(config, "key_bool2", &out_bool2));
  EXPECT_EQ(out_bool2, false);
}

TEST(CipherUtils, gen_key) {
  std::string filename("test_keyfile");
  std::string key = CipherUtils::GenKey(256);
  std::string key1 = CipherUtils::GenKeyToFile(256, filename);
  EXPECT_NE(key, key1);
  std::string key2 = CipherUtils::ReadKeyFromFile(filename);
  EXPECT_EQ(key1, key2);
  EXPECT_EQ(static_cast<int>(key.size()), 32);
}

}  // namespace framework
}  // namespace paddle


text:
'use strict'

module.exports = angular.module('logger-sample',
    [
        require('ngServerLogger').name
    ]
).controller('MainCtrl', function($scope, $log){
    $scope.error = '';
    $scope.warn = '';
    $scope.info = '';
    $scope.debug = '';
    $scope.log = '';
    $scope.thrown = '';

    $scope.logError = function(){
        $log.error($scope.error);
        $scope.error = '';
    };

    $scope.logWarn = function(){
        $log.warn($scope.warn);
        $scope.warn = '';
    }

    $scope.logInfo = function(){
        $log.info($scope.info);
        $scope.info = '';
    }

    $scope.logDebug = function(){
        $log.debug($scope.debug);
        $scope.debug = '';
    }

    $scope.logLog = function(){
        $log.log($scope.log);
        $scope.log = '';
    }

    $scope.throwError = function(){
        throw $scope.thrown;
        $scope.thrown = '';
    }
});


text:
using namespace std;

const char* ossimBandMergeTool::DESCRIPTION  =
      "Merges multiple band files into a single RGB image.";

static const std::string HISTO_STRETCH_KW = "histo_stretch";

ossimBandMergeTool::ossimBandMergeTool()
:  m_stretchProduct(false)
{
}

ossimBandMergeTool::~ossimBandMergeTool()
{
}

void ossimBandMergeTool::setUsage(ossimArgumentParser& ap)
{
   // Add options.
   ossimApplicationUsage* au = ap.getApplicationUsage();
   ossimString usageString = ap.getApplicationName();
   usageString += " bandmerge --red <red_band> --green <green_band> --blue <blue_band> [--stretch] <output-rgb-image>";
   au->setCommandLineUsage(usageString);

   // Set the command line options:
   au->setDescription(DESCRIPTION);

   // Base class has its own:
   ossimChipProcTool::setUsage(ap);

   au->addCommandLineOption("--red", "<filename> Filename of red band. ");
   au->addCommandLineOption("--green", "<filename> Filename of green band. ");
   au->addCommandLineOption("--blue", "<filename> Filename of blue band. ");
   au->addCommandLineOption("--stretch", "Optionally histogram-stretch the product image. ");
}

bool ossimBandMergeTool::initialize(ossimArgumentParser& ap)
{
   if (!ossimChipProcTool::initialize(ap))
      return false;
   if (m_helpRequested)
      return true;

   ostringstream xmsg;

   std::string ts1;
   ossimArgumentParser::ossimParameter sp1 (ts1);
   int band_count = 0;

   if ( ap.read("--red", sp1))
   {
      ostringstream key;
      key<<ossimKeywordNames::IMAGE_FILE_KW<<"0";
      m_kwl.addPair( key.str(), ts1 );
      ++band_count;
   }
   if ( ap.read("--green", sp1))
   {
      ostringstream key;
      key<<ossimKeywordNames::IMAGE_FILE_KW<<"1";
      m_kwl.addPair( key.str(), ts1 );
      ++band_count;
   }
   if ( ap.read("--blue", sp1))
   {
      ostringstream key;
      key<<ossimKeywordNames::IMAGE_FILE_KW<<"2";
      m_kwl.addPair( key.str(), ts1 );
      ++band_count;
   }
   if (band_count != 3)
   {
      ossimNotify(ossimNotifyLevel_NOTICE)<<"ossimBandMergeUtil:"<<__LINE__
            <<" Must supply three band filenames."<<endl;
      return false;
   }

   if ( ap.read("--stretch"))
   {
      m_kwl.addPair(HISTO_STRETCH_KW, string("true") );
   }

   processRemainingArgs(ap);
   return true;
}

void ossimBandMergeTool::initialize(const ossimKeywordlist& kwl)
{
   kwl.getBoolKeywordValue(m_stretchProduct, HISTO_STRETCH_KW.c_str());

   m_kwl.add( ossimKeywordNames::PROJECTION_KW, "input", false );
   ossimChipProcTool::initialize(kwl);
}

void ossimBandMergeTool::initProcessingChain()
{
   if (m_imgLayers.size() != 3)
   {
      ostringstream errMsg;
      errMsg<<"ERROR ossimBandMergeUtil:"<<__LINE__<<"  Expected 3 input layers but found "
            <<m_imgLayers.size() <<". Cannot continue. "<<ends;
      throw ossimException(errMsg.str());
   }

   ossimConnectableObject::ConnectableObjectList bandList;
   for (int band=0; band<3; band++)
   {
      ossimSingleImageChain* band_image = m_imgLayers[band].get();
      bandList.push_back(band_image);

      // If performing histo stretch, try using existing histogram files before creating new ones:
      if (m_stretchProduct)
         initHistogramStretch(band_image);
   }
   ossimRefPtr<ossimBandMergeSource> combiner = new ossimBandMergeSource(bandList);
   m_procChain->add(combiner.get());
}

void ossimBandMergeTool::initHistogramStretch(ossimSingleImageChain* image)
{
   ostringstream errMsg;

   // Check if this image already has a histogram file associated with it:
   ossimRefPtr<ossimImageHandler> handler = image->getImageHandler();
   if (!handler.valid())
   {
      errMsg<<"ERROR ossimBandMergeUtil:"<<__LINE__<<"  Bad handler returned for image chain.";
      throw ossimException(errMsg.str());
   }

   ossimRefPtr<ossimMultiResLevelHistogram> histogram = handler->getImageHistogram();
   if (!histogram.valid())
   {
      errMsg<<"ERROR ossimBandMergeUtil:"<<__LINE__<<"  Bad histogram returned from image handler.";
      throw ossimException(errMsg.str());
   }

   ossimRefPtr<ossimHistogramRemapper> histogramRemapper = new ossimHistogramRemapper();
   histogramRemapper->setEnableFlag(true);
   histogramRemapper->setStretchMode( ossimHistogramRemapper::LINEAR_AUTO_MIN_MAX );
   histogramRemapper->setHistogram(histogram);
   image->add(histogramRemapper.get());
}

bool ossimBandMergeTool::execute()
{
   return ossimChipProcTool::execute();
}

void ossimBandMergeTool::getKwlTemplate(ossimKeywordlist& kwl)
{
   ossimChipProcTool::getKwlTemplate(kwl);

   ossimString keybase (ossimKeywordNames::IMAGE_FILE_KW );
   ossimString key = keybase + "0";
   kwl.add(key.chars(), "<red-band>", true);
   key = keybase + "1";
   kwl.add(key.chars(), "<green-band>", true);
   key = keybase + "2";
   kwl.add(key.chars(), "<blue-band>", true);

   kwl.add(HISTO_STRETCH_KW.c_str(), "true|false", true);
}


text:
require 'spec_helper'

describe 'validate_augeas' do
  if Puppet.features.augeas?
    describe 'signature validation' do
      it { is_expected.not_to eq(nil) }
      it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) }
      it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) }
      it { is_expected.to run.with_params('', '', [], '', 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) }
      it { is_expected.to run.with_params('one', 'one', 'MSG to User', '4th arg').and_raise_error(NoMethodError) }
    end

    describe 'valid inputs' do
      inputs = [
        ["root:x:0:0:root:/root:/bin/bash\n", 'Passwd.lns'],
        ["proc /proc   proc    nodev,noexec,nosuid     0       0\n", 'Fstab.lns'],
      ]

      inputs.each do |input|
        it { is_expected.to run.with_params(*input) }
      end
    end

    describe 'valid inputs which fail augeas validation' do
      # The intent here is to make sure valid inputs raise exceptions when they
      # don't specify an error message to display.  This is the behvior in
      # 2.2.x and prior.
      inputs = [
        ["root:x:0:0:root\n", 'Passwd.lns'],
        ["127.0.1.1\n", 'Hosts.lns'],
      ]

      inputs.each do |input|
        it { is_expected.to run.with_params(*input).and_raise_error(Puppet::ParseError, %r{validate_augeas.*?matched less than it should}) }
      end
    end

    describe 'when specifying nice error messages' do
      # The intent here is to make sure the function returns the 4th argument
      # in the exception thrown
      inputs = [
        ["root:x:0:0:root\n", 'Passwd.lns', [], 'Failed to validate passwd content'],
        ["127.0.1.1\n", 'Hosts.lns', [], 'Wrong hosts content'],
      ]

      inputs.each do |input|
        it { is_expected.to run.with_params(*input).and_raise_error(Puppet::ParseError, %r{#{input[3]}}) }
      end
    end

    describe 'matching additional tests' do
      inputs = [
        ["root:x:0:0:root:/root:/bin/bash\n", 'Passwd.lns', ['$file/foobar']],
        ["root:x:0:0:root:/root:/bin/bash\n", 'Passwd.lns', ['$file/root/shell[.="/bin/sh"]', 'foobar']],
      ]

      inputs.each do |input|
        it { is_expected.to run.with_params(*input) }
      end
    end

    describe 'failing additional tests' do
      inputs = [
        ["foobar:x:0:0:root:/root:/bin/bash\n", 'Passwd.lns', ['$file/foobar']],
        ["root:x:0:0:root:/root:/bin/sh\n", 'Passwd.lns', ['$file/root/shell[.="/bin/sh"]', 'foobar']],
      ]

      inputs.each do |input|
        it { is_expected.to run.with_params(*input).and_raise_error(Puppet::ParseError, %r{testing path}) }
      end
    end
  else
    skip 'ruby-augeas not installed'
  end
end


text:
<?php

namespace backend\models;

use Yii;

/**
 * This is the model class for table "emails".
 *
 * @property integer $id
 * @property string $recever_name
 * @property string $recever_email
 * @property string $subject
 * @property string $content
 * @property string $attachment
 */
class Emails extends \yii\db\ActiveRecord{
	/**
	 * @inheritdoc
	 */
	public static function tableName(){
		return 'emails';
	}

	/**
	 * @inheritdoc
	 */
	public function rules(){
		return [
			[['id', 'recever_name', 'recever_email', 'subject', 'content', 'attachment'], 'required'],
			[['id'], 'integer'],
			[['content'], 'string'],
			[['recever_name'], 'string', 'max' => 50],
			[['recever_email'], 'string', 'max' => 200],
			[['subject', 'attachment'], 'string', 'max' => 255]
		];
	}

	/**
	 * @inheritdoc
	 */
	public function attributeLabels(){
		return [
			'id'			=> Yii::t('email', 'ID'),
			'recever_name'	=> Yii::t('email', 'Recever Name'),
			'recever_email'	=> Yii::t('email', 'Recever Email'),
			'subject'		=> Yii::t('email', 'Subject'),
			'content'		=> Yii::t('email', 'Content'),
			'attachment'	=> Yii::t('email', 'Attachment'),
		];
	}
}