text:
var MeshPainter = {
	enabled: false,
	name: "MeshPainter",

	collision_pos: vec3.create(),
	last_collision_pos: null,
	_mouse_over_the_mesh: false,

	show_wireframe: false,
	wireframe_color: vec4.fromValues(1,1,1,1),
	outside_rotates: true,

	current_texture: null,
	settings: {
		channel: "color",
		uvs: "0",
		tex_size: 512,
		tex_format: "GL.RGB",
		bg_color: vec4.fromValues(0,0,0,1),
	},

	brush: {
		type: "brush",
		color: vec3.fromValues(1,1,1),
		alpha: 1,
		opacity: 1,
		size: 1,
		channels: [1,1,1,1],
		spread: 0,
		texture: null,
		blending: false
	},

	pending_sprites: [],
	pending_sprites3D: [],

	init: function()
	{
		LiteGUI.menubar.add("Actions/Paint mesh", { callback: function() {
			MeshPainter.showPaintingDialog();
		}});

		this.uniforms = {
			u_model: mat4.create(),
			u_vp: mat4.create(),
			u_brushpos: vec3.create(),
			u_brushpos2: vec3.create(),
			u_brushsize: 1.0,
			u_brushcolor: vec4.create(),
			u_brushtype: vec4.create(),
			u_brushtexture: 0,
			u_erasing: 0
		}

		LEvent.bind( LS.GlobalScene, "clear", function(){
			MeshPainter.setPaintedNode(null);
		});
	},

	setPaintedNode: function(node)
	{
		this.painted_node = node;
		if(!node) return;

		this.collision_mesh = node.getMesh( true );
		this.painted_mesh = node.getMesh();

		if(!this.collision_mesh)
			return;

		if(!this.collision_mesh.octree)
			this.collision_mesh.octree = new Octree( this.collision_mesh );

		this.updateChannel( this.settings.channel );
	},

	getPaintedNode: function()
	{
		return this.painted_node;
	},

	showPaintingDialog: function()
	{
		if(this.dialog)
			this.dialog.close();

		var dialog = new LiteGUI.Dialog( { title:"Mesh Painter", parent:"#visor", close: true, minimize: true, width: 300, height: 440, scroll: false, draggable: true});
		dialog.show('fade');
		dialog.setPosition(100,100);
		this.dialog = dialog;

		var widgets = new LiteGUI.Inspector( { name_width: "50%" });
		widgets.onchange = function()
		{
			RenderModule.requestFrame();
		}

		dialog.add( widgets );

		this.inspect( widgets, dialog, on_refresh );

		function on_refresh()
		{
			widgets.addSeparator();
			widgets.addButton("", "Close" , { callback: function (value) {
				dialog.close();
			}});
			dialog.adjustSize();
		}
	},

	inspect: function( widgets, dialog, on_refresh )
	{
		widgets = widgets || InterfaceModule.inspector_widget.inspector;

		inner_update();

		function inner_update()
		{
			widgets.clear();

			widgets.addTitle("Node");

			widgets.addButton("Select node","Paint this node" , { callback: function (value) {
				var node = SelectionModule.getSelectedNode();
				if(!node)
				{
					LiteGUI.alert("No node selected");
					return;
				}
				MeshPainter.setPaintedNode( node );
				inner_update();
			}});

			if(!MeshPainter.painted_node)
				return;

			/*
			if(!MeshPainter.painted_node)
			{
				widgets.addButton("", "Close" , { callback: function (value) {
					dialog.close();
				}});

				dialog.adjustSize();
				return;
			}
			*/

			var node = MeshPainter.painted_node;
			var material = node.getMaterial();

			//create material
			if(!material)
			{
				var selected_material_class = LS.MaterialClasses["StandardMaterial"];
				widgets.addInfo(null,"Material not found in object");
				widgets.addCombo("MaterialClasses", selected_material_class, { values: LS.MaterialClasses, callback: function(material_class) {
					selected_material_class = material_class;
				}});

				widgets.addButton("No material", "Create Material", function(){
					var mat = new selected_material_class();
					node.material = mat;
					inner_update();
				});
				return;
			}

			widgets.addButton("Update mesh","Update" , { callback: function (value) {
				if(!Scene.selected_node)
				{
					LiteGUI.alert("No node selected");
					return;
				}
				MeshPainter.setPaintedNode( MeshPainter.painted_node );
				inner_update();
			}});

			//get valid texture channels
			var channels = material.getTextureChannels();
			if( channels.indexOf( MeshPainter.settings.channel ) == -1 )
				MeshPainter.settings.channel = channels[0];

			widgets.addString("Node name", MeshPainter.painted_node.name );

			widgets.addTitle("Target");

			widgets.addInfo("Current", MeshPainter.settings.channel );
			widgets.addCombo("Channel", MeshPainter.settings.channel, { values: channels, callback: function(v) {
				MeshPainter.updateChannel(v);
				inner_update();
			}});

			var channel_sampler = material.getTextureSampler( MeshPainter.settings.channel );
			var texture = material.getTexture( MeshPainter.settings.channel );
			if(!channel_sampler || !texture)
			{
				widgets.addInfo(null, "No "+MeshPainter.settings.channel+" texture found, create one?" );
				var tex_name = "texture_" + (Math.random() * 1000).toFixed();
				//widgets.addTitle("New texture");
				widgets.addString("Texture name", tex_name, { callback: function (value) { tex_name = value }});
				widgets.widgets_per_row = 2;
				widgets.addCombo("Size", MeshPainter.settings.tex_size, { values:[64,128,256,512,1024,2048,4096], callback: function (value) { MeshPainter.settings.tex_size = value }});
				widgets.addCombo("Format", MeshPainter.settings.tex_format, { values:["GL.RGB","GL.RGBA"], callback: function (value) { MeshPainter.settings.tex_format = value }});
				widgets.widgets_per_row = 1;
				widgets.addColor("Bg Color", MeshPainter.settings.bg_color, { callback: function (value) { MeshPainter.settings.bg_color.set(value) }});
				widgets.addButton("","Create texture" , { callback: function (value) {
					MeshPainter.createTexture( node, MeshPainter.settings.channel );
					inner_update();
				}});
				return;
			}
			else
			{
				var format_str = "?";
				switch( texture.format )
				{
					case GL.RGBA: format_str = "GL.RGBA"; break;
					case GL.RGB: format_str = "GL.RGB"; break;
				}

				widgets.addInfo("Texture", "Size: " + texture.width + "x" + texture.height + " Format: " + format_str );
				widgets.widgets_per_row = 2;
				widgets.addButton(null,"Clone" , { callback: function (value) {
					MeshPainter.cloneTextureInChannel();
					inner_update();
				}});

				widgets.addButton(null,"Remove" , { callback: function (value) {
					material.setTexture( MeshPainter.settings.channel, null );
					inner_update();
				}});
				widgets.widgets_per_row = 1;
			}

			/*
			widgets.addCombo("Texture coords", MeshPainter.settings.uvs, { values: Material.TEXTURE_COORDINATES, callback: function(v) {
				MeshPainter.settings.uvs = v;
			}});
			*/

			//Brush info
			widgets.addTitle("Brush");
			widgets.addCombo("Type", MeshPainter.brush.type, { name_width: 80, values: ["brush","pencil","eraser","set_alpha"], callback: function(v) {
				MeshPainter.brush.type = v;
			}});
			widgets.addSlider("Size", MeshPainter.brush.size, { name_width: 80, min:0.01, max:10, step: 0.01, callback: function(v) {
				MeshPainter.brush.size = v;
			}});
			//widgets.addNumber("Spread", MeshPainter.brush.spread, { min:0.1, step: 0.1, callback: function(v) { MeshPainter.brush.spread = v; }});
			widgets.widgets_per_row = 2;
			var widget_color = widgets.addColor("Color", MeshPainter.brush.color, { callback: function (value) { vec3.copy( MeshPainter.brush.color, value ); }});
			widgets.addSlider("Alpha", MeshPainter.brush.alpha, { min:0.01, max: 1, callback: function(v) {
				MeshPainter.brush.alpha = v;
			}});
			widgets.widgets_per_row = 1;
			widgets.addSlider("Opacity", MeshPainter.brush.opacity, { name_width: 80, min:0.01, max: 1, callback: function(v) {
				MeshPainter.brush.opacity = v;
			}});
			widgets.addCheckbox("Blending", MeshPainter.brush.blending, { callback: function(v) { MeshPainter.brush.blending = v; }});

			widgets.widgets_per_row = 4;
			widgets.addInfo( "Mask", null, { width: 130 } );
			widgets.addCheckbox( null, MeshPainter.brush.channels[0], { label: "R", width: 40, callback: function (value) { MeshPainter.brush.channels[0] = value?1:0; }});
			widgets.addCheckbox( null, MeshPainter.brush.channels[1], { label: "G", width: 40, callback: function (value) { MeshPainter.brush.channels[1] = value?1:0; }});
			widgets.addCheckbox( null, MeshPainter.brush.channels[2], { label: "B", width: 40, callback: function (value) { MeshPainter.brush.channels[2] = value?1:0; }});
			widgets.addCheckbox( null, MeshPainter.brush.channels[3], { label: "A", width: 40, callback: function (value) { MeshPainter.brush.channels[3] = value?1:0; }});
			widgets.widgets_per_row = 1;

			widgets.addButton("Special color","Flat Normal", { callback: function (value) {
				widget_color.setValue( [0.5,0.5,1.0] );
				//vec3.copy( MeshPainter.brushcolor, [0.5,0.5,1.0] );
			}});

			widgets.addTitle("Actions");
			widgets.widgets_per_row = 2;
			var fill_color = [0,0,0];
			widgets.addColor("Fill Color",fill_color, { callback: function(v){ fill_color = v; }});
			widgets.addButton(null,"Fill", { callback: function(v){
				if(!MeshPainter.current_texture)
					return;
				MeshPainter.current_texture.fill(fill_color);
				LS.GlobalScene.requestFrame();
			}});
			widgets.widgets_per_row = 1;
			widgets.addButton(null,"Download", { callback: function(v){
				var filename = LS.RM.getBasename( MeshPainter.current_texture.filename ) + ".png";
				LiteGUI.downloadFile( filename, MeshPainter.current_texture.toBlob(true) )
			}});

			widgets.widgets_per_row = 2;
			widgets.addCheckbox("Wireframe", MeshPainter.show_wireframe, { callback: function(v){ MeshPainter.show_wireframe = v; }});
			widgets.addColor("Color",MeshPainter.wireframe_color, { callback: function(v){ MeshPainter.wireframe_color.set(v); }});
			widgets.widgets_per_row = 1;
			widgets.addCheckbox("Clicking outside rotates", MeshPainter.outside_rotates, { callback: function(v){ MeshPainter.outside_rotates = v; }});

			if(on_refresh)
				on_refresh();

		}//inner update
	},

	cloneTextureInChannel: function()
	{
		if(!MeshPainter.getPaintedNode())
			return;

		var node = MeshPainter.getPaintedNode();

		var material = node.getMaterial();
		if(!material)
			return;
		var current_texture = material.getTexture( MeshPainter.settings.channel );
		if( !current_texture )
			return;

		var tex = new GL.Texture.fromTexture( current_texture, { minFilter: gl.LINEAR });
		var ext = current_texture.filename.substring( current_texture.filename.lastIndexOf(".") );
		var pos = current_texture.filename.lastIndexOf("/");
		var name = current_texture.filename;
		if(pos != -1)
			name = current_texture.filename.substring( pos+1 );
		tex.filename = name.replace(ext, "_copy_" + (Math.random() * 1000).toFixed(0) + "_.png");
		LS.ResourcesManager.registerResource( tex.filename, tex );
		material.setTexture( MeshPainter.settings.channel, tex );
		this.updateChannel();
	},

	updateChannel: function(channel)
	{
		this.settings.channel = channel;

		var node = MeshPainter.getPaintedNode();
		if(!node)
			return;

		var mat = node.getMaterial();
		if(!mat)
			return;

		var sampler = mat.getTextureSampler( channel );
		if(sampler)
			sampler.minFilter = GL.LINEAR;

		this.current_texture = mat.getTexture( channel );
		if(!this.current_texture)
			return;

		//disable mipmaps
		var texture = this.current_texture;
		texture.bind();
		gl.texParameteri(texture.texture_type, gl.TEXTURE_MIN_FILTER, gl.LINEAR );
		texture.unbind();

		//mat.textures[channel + "_uvs"] = uvs || "0";
		EditorModule.refreshAttributes();
	},

	createTexture: function( node, channel, name )
	{
		channel = channel || "color";

		var tex_size = this.settings.tex_size || 512;
		var format = eval( this.settings.tex_format ) || GL.RGB;

		this.current_texture = new GL.Texture(tex_size,tex_size, { format: format, magFilter: gl.LINEAR, minFilter: gl.LINEAR_MIPMAP_LINEAR });
		var tex_name = name || "texture_" + (Math.random() * 1000).toFixed();
		tex_name = tex_name + ".png"; //used for storing later
		this.current_texture.filename = tex_name;
		this.current_texture.bind();
		gl.generateMipmap(this.current_texture.texture_type);
		gl.texParameteri(this.current_texture.texture_type, gl.TEXTURE_MIN_FILTER, gl.LINEAR );
		this.current_texture.unbind();

		LS.ResourcesManager.registerResource( tex_name, this.current_texture);

		var mat = node.getMaterial();
		if(!mat)
		{
			mat = new LS.StandardMaterial();
			node.material = mat;
		}

		mat.setTexture( channel, tex_name);
		var bg_color = this.settings.bg_color || [1,1,1,1];
		this.current_texture.fill( bg_color, true );

		RenderModule.requestFrame();
		EditorModule.inspect( node );
	},

	//*********************
	testRay: function(ray)
	{
		if(!this.painted_node || !this.collision_mesh || !this.collision_mesh.octree)
			return null;

		var node = this.painted_node;

		//compute ray
		var model = node.transform.getGlobalMatrix();
		var inv = mat4.invert( mat4.create(), model );
		mat4.multiplyVec3(ray.origin, inv, ray.origin );
		mat4.rotateVec3(ray.direction, inv, ray.direction );
		vec3.normalize(ray.direction, ray.direction);

		//test hit
		var hit = this.collision_mesh.octree.testRay( ray.origin, ray.direction, 0.0, 10000 );
		if(hit)
		{
			mat4.multiplyVec3(hit.pos, model, hit.pos);
			return hit;
		}
		return null;
	},

	getCamera: function()
	{
		return RenderModule.under_camera || RenderModule.camera;
	},

	addSprite3D: function( pos, normal, use_line )
	{
		var sprite = {
			type: this.brush.type,
			pos: pos,
			normal: normal,
			color: vec3.clone( this.brush.color ),
			alpha: this.brush.alpha,
			opacity: this.brush.opacity,
			size: this.brush.size
		};

		/*
		if(use_line)
		{
			if(this.last_collision_pos != null)
			{
				var d = pos.subtract( this.last_collision_pos ).length();
				if( d > 10 )
					sprite.pos2 = this.last_collision_pos;
			}
			this.last_collision_pos = vec3.create(pos);
		}
		*/

		this.pending_sprites3D.push( sprite );
	},

	drawSprites3D: function()
	{
		if(this.pending_sprites3D.length == 0)
			return;

		gl.enable(gl.BLEND);
		gl.disable(gl.DEPTH_TEST);
		gl.disable(gl.CULL_FACE);

		if(this.brush.blending)
			gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.SRC_ALPHA, gl.DST_ALPHA );
		else
			gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.SRC_ALPHA, gl.DST_ALPHA );
		gl.blendEquation( gl.FUNC_ADD, gl.MAX );
		gl.blendColor( 0,0,0,0 );

		gl.colorMask( MeshPainter.brush.channels[0], MeshPainter.brush.channels[1], MeshPainter.brush.channels[2], MeshPainter.brush.channels[3]);

		var camera = this.getCamera();

		LS.Renderer.enableCamera( camera, null, true );
		var mesh = this.painted_mesh;
		var uniforms = MeshPainter.uniforms;

		var shader_point = this._shader;
		if(!shader_point)
			shader_point = this._shader_point = new GL.Shader( MeshPainter._paint_vertex_shader, MeshPainter._paint_pixel_shader); //,{"USE_PAINT_LINE":""});

		var shader_line = this._shader_line;
		if(!shader_line)
			shader_line = this._shader_line = new GL.Shader( MeshPainter._paint_vertex_shader, MeshPainter._paint_pixel_shader,{"USE_PAINT_LINE":""});

		var shader = null;
		var model = this.getPaintedNode().transform.getGlobalMatrix();

		for(var i = 0; i < this.pending_sprites3D.length; ++i)
		{
			var sprite = this.pending_sprites3D[i];

			uniforms.u_model.set( model );
			uniforms.u_brushpos.set( sprite.pos );
			if(sprite.pos2)
				uniforms.u_brushpos2.set( sprite.pos2 );
			uniforms.u_brushsize = sprite.size;
			uniforms.u_brushcolor.set( sprite.color );

			if( sprite.type == "eraser" )
			{
				gl.blendColor( 0,0,0,0 ); //desired alpha result
				gl.blendFunc( GL.CONSTANT_COLOR, GL.ONE_MINUS_SRC_ALPHA );
				gl.colorMask( false,false,false,true );
				uniforms.u_brushcolor[3] = sprite.opacity; //how much to apply the effect
			}
			else if( sprite.type == "set_alpha" )
			{
				gl.blendColor( 0,0,0, sprite.alpha ); //desired alpha result
				gl.blendFunc( GL.CONSTANT_COLOR, GL.ONE_MINUS_SRC_ALPHA );
				gl.colorMask( false,false,false,true );
				uniforms.u_brushcolor[3] = sprite.opacity; //how much to apply the effect
			}
			else //brush
			{
				uniforms.u_brushcolor[3] = sprite.opacity;
				gl.colorMask( MeshPainter.brush.channels[0], MeshPainter.brush.channels[1], MeshPainter.brush.channels[2], MeshPainter.brush.channels[3]);
			}

			if(sprite.pos2)
				shader = shader_line;
			else
				shader = shader_point;

			shader.uniforms(uniforms);
			shader.draw( mesh );
		}

		this.pending_sprites3D.length = 0;

		//restore state
		gl.disable(gl.BLEND);
		gl.blendFunc( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA );
		gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ZERO );
		gl.blendEquation( gl.FUNC_ADD, gl.FUNC_ADD );
		gl.colorMask(1,1,1,1);
		gl.blendColor( 0,0,0,0 );
	},
};

MeshPainter._paint_vertex_shader = "\n\
	precision highp float;\n\
	\n\
	attribute vec3 a_vertex;\n\
	attribute vec2 a_coord;\n\
	\n\
	uniform mat4 u_model;\n\
	varying vec3 v_pos;\n\
	\n\
	void main() {\n\
		v_pos = (u_model * vec4(a_vertex,1.0)).xyz;\n\
		gl_Position = vec4(a_coord * 2.0 - 1.0, 0.0, 1.0);\n\
	}\n\
	";

MeshPainter._paint_pixel_shader = "\n\
	precision highp float;\n\
	\n\
	varying vec3 v_pos;\n\
	uniform vec3 u_brushpos;\n\
	#ifdef USE_PAINT_LINE\n\
		uniform vec3 u_brushpos2;\n\
		\n\
		float distToLine(vec3 P, vec3 A, vec3 B)\n\
		{\n\
			float dist_A = length(P-A);\n\
			float dist_B = length(P-B);\n\
			float dist_line = length( cross( P-A, P-B ) ) / length(B-A);\n\
			return min(dist_line, min(dist_A, dist_B) );\n\
		}\n\
	#endif\n\
	\n\
	uniform float u_brushsize;\n\
	uniform vec4 u_brushcolor;\n\
	uniform vec4 u_brushtype;\n\
	void main() {\n\
	\n\
		#ifdef USE_PAINT_LINE\n\
			float dist = distToLine(v_pos, u_brushpos, u_brushpos2);\n\
		#else\n\
			vec3 v = v_pos - u_brushpos;\n\
			if( abs(v.x) > u_brushsize || abs(v.y) > u_brushsize)\n\
				discard;\n\
			\n\
			float dist = length(v);\n\
			if( dist > u_brushsize )\n\
				discard;\n\
		#endif\n\
		\n\
		vec4 color = u_brushcolor;\n\
		if(u_brushtype.x == 1.0)\n\
			color.a *= 1.0 - (dist / u_brushsize);\n\
		gl_FragColor = color;\n\
	}\n\
";

MeshPainter._brush_vertex_shader = "\n\
	precision highp float;\n\
	\n\
	attribute vec3 a_vertex;\n\
	\n\
	uniform mat4 u_model;\n\
	uniform mat4 u_vp;\n\
	varying vec3 v_pos;\n\
	\n\
	void main() {\n\
		v_pos = (u_model * vec4(a_vertex,1.0)).xyz;\n\
		gl_Position = u_vp * vec4(v_pos,1.0);\n\
	}\n\
	";

MeshPainter._brush_pixel_shader = "\n\
	precision highp float;\n\
	\n\
	varying vec3 v_pos;\n\
	uniform vec3 u_brushpos;\n\
	uniform float u_brushsize;\n\
	uniform vec4 u_brushcolor;\n\
	uniform vec4 u_brushtype;\n\
	void main() {\n\
		vec3 v = v_pos - u_brushpos;\n\
		if( abs(v.x) > u_brushsize || abs(v.y) > u_brushsize)\n\
			discard;\n\
		\n\
		float dist = length(v);\n\
		if( dist > u_brushsize )\n\
			discard;\n\
		\n\
		vec4 color = u_brushcolor;\n\
		if(u_brushtype.x == 1.0)\n\
			color.a *= 1.0 - (dist / u_brushsize);\n\
		gl_FragColor = color;\n\
	}\n\
";

CORE.registerModule( MeshPainter );

var meshPainterTool = {
	name: "painter",
	description: "Paint the mesh",
	section: "modify",
	icon: "media/icons/mini-icon-brush.png",

	onEnable: function()
	{
		if(!MeshPainter.sphere_mesh)
			MeshPainter.sphere_mesh = GL.Mesh.sphere({long:16,lat:16});

		//disable
		if(MeshPainter.current_texture)
		{
			var texture = MeshPainter.current_texture;
			texture.bind();
			gl.texParameteri(texture.texture_type, gl.TEXTURE_MIN_FILTER, gl.LINEAR );
			texture.unbind();
		}
	},

	onDisable: function()
	{
		if(MeshPainter.current_texture)
		{
			var texture = MeshPainter.current_texture;
			texture.bind();
			gl.texParameteri(texture.texture_type, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR );
			gl.generateMipmap(texture.texture_type);
			texture.unbind();
		}
	},

	onClick: function()
	{
		//MeshPainter.showPaintingDialog();
		MeshPainter.inspect();
	},

	render: function()
	{
		if(!RenderModule.frame_updated || !MeshPainter.current_texture)
			return;

		var camera = MeshPainter.getCamera();

		//LS.Draw.setViewProjectionMatrix( Renderer._view_matrix, Renderer._projection_matrix, Renderer._viewprojection_matrix );
		LS.Draw.setCamera( camera );
		var uniforms = MeshPainter.uniforms;

		MeshPainter.uniforms.u_vp.set( camera._viewprojection_matrix );

		gl.disable( gl.BLEND );
		gl.enable( gl.DEPTH_TEST );

		if( MeshPainter.show_wireframe )
		{
			gl.depthFunc( gl.LEQUAL );
			LS.Draw.setColor( MeshPainter.wireframe_color );
			if(!MeshPainter.painted_mesh.getIndexBuffer("wireframe"))
				MeshPainter.painted_mesh.computeWireframe();
			LS.Draw.renderMesh( MeshPainter.painted_mesh, gl.LINES, LS.Draw.shader, "wireframe" );
			gl.depthFunc( gl.LESS );
		}

		if(MeshPainter.sphere_mesh && MeshPainter._mouse_over_the_mesh)
		{
			var shader_brush = this._shader_brush;
			if(!shader_brush)
				shader_brush = this._shader_brush = new GL.Shader( MeshPainter._brush_vertex_shader, MeshPainter._brush_pixel_shader);

			var painted_node = MeshPainter.getPaintedNode();
			if(!painted_node || !painted_node.transform)
				return;

			var model = painted_node.transform.getGlobalMatrix();

			gl.enable( gl.BLEND );
			gl.depthFunc( gl.LEQUAL );
			gl.blendFunc( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA );

			uniforms.u_model.set( model );
			uniforms.u_brushpos.set( MeshPainter.collision_pos );
			uniforms.u_brushsize = MeshPainter.brush.size;
			uniforms.u_brushcolor.set( MeshPainter.brush.color );
			uniforms.u_brushcolor[3] = MeshPainter.brush.alpha * 3.0;
			if( MeshPainter.brush.type == "pencil")
				uniforms.u_brushtype[0] = 0;
			else if( MeshPainter.brush.type == "brush")
				uniforms.u_brushtype[0] = 1;
			LS.Draw.push();
			LS.Draw.setMatrix( model );
			shader_brush.uniforms( uniforms );
			LS.Draw.renderMesh( MeshPainter.painted_mesh, gl.TRIANGLES, shader_brush );
			LS.Draw.pop();

			gl.depthFunc( gl.LESS );

			if(1) //render brush sphere
			{
				LS.Draw.setColor( MeshPainter.brush.color );
				LS.Draw.setAlpha(0.1);
				LS.Draw.push();
				LS.Draw.translate( MeshPainter.collision_pos );
				LS.Draw.scale( [MeshPainter.brush.size, MeshPainter.brush.size, MeshPainter.brush.size] );
				LS.Draw.renderMesh( MeshPainter.sphere_mesh, gl.TRIANGLES );
				LS.Draw.pop();
			}
			gl.disable( gl.BLEND );
		}

		if( MeshPainter.pending_sprites.length > 0 || MeshPainter.pending_sprites3D.length > 0 )
		{
			MeshPainter.current_texture.drawTo(function(tex) {
				//texturePainter.drawSprites();
				MeshPainter.drawSprites3D();
				//texturePainter.drawUnwrap();
			});
		}
	},

	mousedown: function(e)
	{
		if(e.button != 0)
			return;

		var node = MeshPainter.getPaintedNode();
		if(!node)
			return;

		var camera = MeshPainter.getCamera();

		MeshPainter.painting = false;
		if(node)
		{
			camera.updateMatrices();
			var ray = camera.getRayInPixel( e.canvasx, e.canvasy );
			var hit = MeshPainter.testRay(ray);
			if( MeshPainter.painted_mesh )
			{
				if( hit || MeshPainter.outside_rotates == false || e.ctrlKey )
					MeshPainter.painting = true;
				if( hit )
					MeshPainter.addSprite3D( hit.pos, hit.normal );
			}
		}
		RenderModule.requestFrame();
	},

	mousemove: function(e)
	{
		var node = MeshPainter.getPaintedNode();
		if(!node)
			return;

		var camera = MeshPainter.getCamera();
		camera.updateMatrices();
		var node = MeshPainter.painted_node;

		var ray = camera.getRayInPixel( e.canvasx, e.canvasy );
		var hit = MeshPainter.testRay(ray);
		if(hit) {
			MeshPainter._mouse_over_the_mesh = true;
			vec3.copy(MeshPainter.collision_pos, hit.pos ); //used for cursor sphere
		}
		else
			MeshPainter._mouse_over_the_mesh = false;

		RenderModule.requestFrame();

		if(e.button == 0 && e.dragging && MeshPainter.painting)
		{
			if(node && MeshPainter.painted_mesh)
			{
				if(hit)
				{
					MeshPainter.addSprite3D( hit.pos, hit.normal );
				}
			}
			return true;
		}
		else if(e.dragging)
		{
			cameraTool.onCameraDrag(e);
		}
	},

	mouseup: function(e)
	{
		MeshPainter.painting = false;
	},

	mousewheel: function(e)
	{
		if(!e.shiftKey)
			return;

		//console.log(e);
		if(e.wheelDelta > 0)
			MeshPainter.brush.size *= 1.2;
		else
			MeshPainter.brush.size *= 0.8;

		RenderModule.requestFrame();
		e.stopPropagation();
		return true;
	},

	inspect: function( widgets, dialog )
	{
		return MeshPainter.inspect( widgets, dialog );
	}
};

ToolsModule.registerTool( meshPainterTool );


text:
<button type="button" class="close" aria-label="Close" data-ng-click="editchanl.dismissModal()">
    ×
</button>

             - {{editchanl.modalData.formatName }}

    <form name="editShareForm" class="edit-channel-wrapper">

Mars Resources by Channel

                Total spend 2015A ($m)
                <input type="text"
                class="form-control"
                name="Total_Spend"
                data-ng-change="editchanl.validate(editchanl.format.Mars_Channel_Total_Spent__c,'Total_Spend')"
                data-ng-model="editchanl.format.Mars_Channel_Total_Spent__c" />

The sum of below values should not exceed total spend.

Please enter a valid number

                Trade spend 2015A ($m)
                <input type="text"
                class="form-control"
                name="Trade_Spend"
                data-ng-change="editchanl.validate(editchanl.format.Mars_Trade_Spend__c,'Trade_Spend')"
                data-ng-model="editchanl.format.Mars_Trade_Spend__c">

Please enter a valid number

                Consumer Promotion Spend 2015A ($m)
                <input type="text"
                class="form-control"
                name="Promotion_Spend"
                data-ng-change="editchanl.validate(editchanl.format.Mars_Customer_Promotion_Spend__c,'Promotion_Spend')"
                data-ng-model="editchanl.format.Mars_Customer_Promotion_Spend__c">

Please enter a valid number

                D&E 2015A ($m)
                <input type="text"
                class="form-control"
                name="DE_Spend"
                data-ng-change="editchanl.validate(editchanl.format.Mars_DandE__c,'DE_Spend')"
                data-ng-model="editchanl.format.Mars_DandE__c">

Please enter a valid number

                Overhead 2015A ($m)
                <input type="text" class="form-control"
                name="OverHead_Spend"
                data-ng-change="editchanl.validate(editchanl.format.Mars_Overhead__c,'OverHead_Spend')"
                data-ng-model="editchanl.format.Mars_Overhead__c">

Please enter a valid number

            Reset
            Save

    </form>

redpajama_set_name: RedPajamaGithub


text:
export class AnimatableSpriteWrapperEvent {
    public static ANIMATION_COMPLETE:string = "ANIMATION_COMPLETE";
}


text:
<?php
defined('C5_EXECUTE') or die("Access Denied.");
Loader::model('stack/list');
$sl = new StackList();
$sl->filterByUserAdded();
$stacks = $sl->get();

//$btl = $a->getAddBlockTypes($c, $ap );
$ci = Loader::helper('concrete/urls');
$ch = Loader::helper('concrete/interface');
$form = Loader::helper('form');
?>

		<form onsubmit="return ccmStackSearchFormCheckResults()">

		<?php echo $form->text('ccmStackSearch', array('tabindex' => 1, 'autocomplete' => 'off', 'style' => 'margin-left: 8px; width: 168px'))?>
		</form>

	<?php if (count($stacks) > 0) { ?>

		<?php foreach($stacks as $s) {
			$as = Area::get($s, STACKS_AREA_NAME);
			$asp = new Permissions($as);
			if ($asp->canRead() && $ap->canAddStackToArea($s)) {
			?>

				<a onclick="ccmStackSearchResetKeys()" dialog-on-destroy="ccmStackSearchMapKeys()" class="dialog-launch ccm-block-type-inner" dialog-on-close="ccm_blockWindowAfterClose()" dialog-append-buttons="true" dialog-modal="false" dialog-width="620" dialog-height="400" dialog-title="<?php echo $s->getCollectionName()?> <?php echo t('Contents')?>" href="<?php echo REL_DIR_FILES_TOOLS_REQUIRED?>/edit_area_popup.php?atask=add_stack_contents&cID=<?php echo $c->getCollectionID()?>&stackID=<?php echo $s->getCollectionID()?>&arHandle=<?php echo Loader::helper('text')->entities($a->getAreaHandle())?>"><?php echo $s->getCollectionName()?>

			<?php } ?>

		<?php } ?>

		<?php
	} else { ?>

<?php echo t('No stacks can be added to this area.')?>

	<?php } ?>


text:
package model

import (
	"log"
	"strings"
	"time"

	"github.com/hprose/hprose-golang/io"
	"github.com/jinzhu/gorm"
	// for db SQL
	_ "github.com/jinzhu/gorm/dialects/mysql"
	_ "github.com/jinzhu/gorm/dialects/postgres"
	_ "github.com/jinzhu/gorm/dialects/sqlite"
	"github.com/miaolz123/samaritan/config"
)

var (
	// DB Database
	DB     *gorm.DB
	dbType = config.String("dbtype")
	dbURL  = config.String("dburl")
)

func init() {
	io.Register((*User)(nil), "User", "json")
	io.Register((*Exchange)(nil), "Exchange", "json")
	io.Register((*Algorithm)(nil), "Algorithm", "json")
	io.Register((*Trader)(nil), "Trader", "json")
	io.Register((*Log)(nil), "Log", "json")
	var err error
	DB, err = gorm.Open(strings.ToLower(dbType), dbURL)
	if err != nil {
		log.Printf("Connect to %v database error: %v\n", dbType, err)
		dbType = "sqlite3"
		dbURL = "custom/data.db"
		DB, err = gorm.Open(dbType, dbURL)
		if err != nil {
			log.Fatalln("Connect to database error:", err)
		}
	}
	DB.AutoMigrate(&User{}, &Exchange{}, &Algorithm{}, &TraderExchange{}, &Trader{}, &Log{})
	users := []User{}
	DB.Find(&users)
	if len(users) == 0 {
		admin := User{
			Username: "admin",
			Password: "admin",
			Level:    99,
		}
		if err := DB.Create(&admin).Error; err != nil {
			log.Fatalln("Create admin error:", err)
		}
	}
	DB.LogMode(false)
	go ping()
}

func ping() {
	for {
		if err := DB.Exec("SELECT 1").Error; err != nil {
			log.Println("Database ping error:", err)
			if DB, err = gorm.Open(strings.ToLower(dbType), dbURL); err != nil {
				log.Println("Retry connect to database error:", err)
			}
		}
		time.Sleep(time.Minute)
	}
}

// NewOrm ...
func NewOrm() (*gorm.DB, error) {
	return gorm.Open(strings.ToLower(dbType), dbURL)
}


text:
var MockServer = require('mockserver');

module.exports = {
  setUp: function(callback) {
    this.client = require('../../nightwatch.js').init();
    callback();
  },

  testMaximizeCommand: function(test) {
    var client = this.client.api;

    MockServer.addMock({
      'url': '/wd/hub/session/1352110219202/current/maximize',
      'response': JSON.stringify({
        sessionId: '1352110219202',
        status: 0
      })
    });

    client.maximizeWindow(function callback(result) {
      test.deepEqual(result, {});
      test.done();
    });
  },

  tearDown: function(callback) {
    this.client = null;
    callback();
  }
};


text:
//@@author A0147996E
package seedu.address.ui;

import javafx.fxml.FXML;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Region;
import javafx.stage.Stage;
import seedu.address.commons.core.Config;
import seedu.address.commons.core.GuiSettings;
import seedu.address.commons.events.ui.ExitAppRequestEvent;
import seedu.address.commons.util.FxViewUtil;
import seedu.address.logic.Logic;
import seedu.address.model.UserPrefs;

/**
 * The Main Window. Provides the basic application layout containing
 * a menu bar and space where other JavaFX elements can be placed.
 */
public class MainWindow extends UiPart<Region> {

    private static final String ICON = "/images/address_book_32.png";
    private static final String FXML = "MainWindow.fxml";
    private static final int MIN_HEIGHT = 600;
    private static final int MIN_WIDTH = 800;

    private Stage primaryStage;
    private Logic logic;

    // Independent Ui parts residing in this Ui container
    private TagListPanel tagListPanel;
    private TaskListPanel taskListPanel;
    private Config config;

    @FXML
    private AnchorPane commandBoxPlaceholder;

    @FXML
    private AnchorPane tagListPanelPlaceholder;

    @FXML
    private AnchorPane taskListPanelPlaceholder;

    @FXML
    private AnchorPane resultDisplayPlaceholder;

    @FXML
    private AnchorPane statusbarPlaceholder;

    public static MainWindow mainWindow;

    public static MainWindow getInstance() {
        assert mainWindow != null;
        return mainWindow;
    }

    private MainWindow(Stage primaryStage, Config config, UserPrefs prefs, Logic logic) {
        super(FXML);

        // Set dependencies
        this.primaryStage = primaryStage;
        this.logic = logic;
        this.config = config;

        // Configure the UI
        setTitle(config.getAppTitle());
        setIcon(ICON);
        setWindowMinSize();
        setWindowDefaultSize(prefs);
        Scene scene = new Scene(getRoot());
        primaryStage.setScene(scene);
    }

    public static void initializeMainWindow(Stage primaryStage, Config config, UserPrefs prefs, Logic logic) {
        mainWindow = new MainWindow(primaryStage, config, prefs, logic);
    }

    public Stage getPrimaryStage() {
        return primaryStage;
    }

    public void fillInnerParts() throws NullPointerException {
        tagListPanel = new TagListPanel(getTagListPlaceholder(), logic.getFilteredTagList());
        taskListPanel = new TaskListPanel(getTaskListPlaceholder(), logic.getFilteredTaskList());
        new ResultDisplay(getResultDisplayPlaceholder());
        new StatusBarFooter(getStatusbarPlaceholder(), config.getTaskManagerFilePath());
        new CommandBox(getCommandBoxPlaceholder(), logic);
    }

    private AnchorPane getCommandBoxPlaceholder() {
        return commandBoxPlaceholder;
    }

    private AnchorPane getStatusbarPlaceholder() {
        return statusbarPlaceholder;
    }

    private AnchorPane getResultDisplayPlaceholder() {
        return resultDisplayPlaceholder;
    }

    private AnchorPane getTaskListPlaceholder() {
        return taskListPanelPlaceholder;
    }

    private AnchorPane getTagListPlaceholder() {
        return tagListPanelPlaceholder;
    }
    public void hide() {
        primaryStage.hide();
    }

    private void setTitle(String appTitle) {
        primaryStage.setTitle(appTitle);
    }

    /**
     * Sets the given image as the icon of the main window.
     * @param iconSource e.g. {@code "/images/help_icon.png"}
     */
    private void setIcon(String iconSource) {
        FxViewUtil.setStageIcon(primaryStage, iconSource);
    }

    /**
     * Sets the default size based on user preferences.
     */
    private void setWindowDefaultSize(UserPrefs prefs) {
        primaryStage.setHeight(prefs.getGuiSettings().getWindowHeight());
        primaryStage.setWidth(prefs.getGuiSettings().getWindowWidth());
        if (prefs.getGuiSettings().getWindowCoordinates() != null) {
            primaryStage.setX(prefs.getGuiSettings().getWindowCoordinates().getX());
            primaryStage.setY(prefs.getGuiSettings().getWindowCoordinates().getY());
        }
    }

    private void setWindowMinSize() {
        primaryStage.setMinHeight(MIN_HEIGHT);
        primaryStage.setMinWidth(MIN_WIDTH);
    }

    /**
     * Returns the current size and the position of the main Window.
     */
    public GuiSettings getCurrentGuiSetting() {
        return new GuiSettings(primaryStage.getWidth(), primaryStage.getHeight(),
                (int) primaryStage.getX(), (int) primaryStage.getY());
    }

    public void show() {
        primaryStage.show();
    }

    @FXML
    private void handleExit() {
        raise(new ExitAppRequestEvent());
    }

    public TaskListPanel getTaskListPanel() {
        return taskListPanel;
    }

    public TagListPanel getTagListPanel() {
        return tagListPanel;
    }
}


text:
package org.forge.text.syntax.encoder;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.forge.text.syntax.Theme;
import org.forge.text.syntax.TokenType;
import org.junit.Assert;

public class AssertEncoder extends DebugEncoder {

   public AssertEncoder(OutputStream out, Theme theme, Map<String, Object> options) {
      super(out, theme, options);
      textTokens.clear();
   }

   @Override
   public void textToken(String text, TokenType type) {
      textTokens.add(new TokenPair(text, type));
      super.textToken(text, type);
   }

   private static List<TokenPair> textTokens = new ArrayList<TokenPair>();

   private static class TokenPair {
      private String text;
      private TokenType type;

      public TokenPair(String text, TokenType type) {
         this.text = text;
         this.type= type;
      }

      @Override
      public String toString() {
         return "[text=" + text + ", type=" + type + "]";
      }
   }

   public static void assertTextToken(TokenType type, String... texts) {
      for(String text : texts) {
         boolean found = false;
         List<TokenPair> textMatches = new ArrayList<TokenPair>();
         for(TokenPair pair : textTokens) {
            if(pair.text.equals(text)) {
               textMatches.add(pair);
               if(pair.type == type) {
                  found = true;
                  break;
               }
            }
         }
         if(!found) {
            Assert.fail("Expected [" + text + "] of type [" + type + "]: Found matches: " + textMatches);
         }
      }
   }

   public static void dump() {
      System.out.println(textTokens);
   }
}


text:
class OrangeTree
  attr_reader :age, :height

  def initialize
    @age = 1
    @height = 3
    @oranges = []
  end

  # Ages the tree one year
  def age!
    @age += 1
    @height += 3
    if @age >=6 && @age <=60
      until @oranges.length >= rand(1..20)
        @oranges << Orange.new(rand(1..5))
      end
    end
  end

  def dead?
    @age >= 60 ? true  : false
  end

  # # Returns +true+ if there are any oranges on the tree, +false+ otherwise
  def any_oranges?
    if @oranges.length > 0
      return true
    end
  end

  # # Returns an Orange if there are any
  # # Raises a NoOrangesError otherwise
  def pick_an_orange!
    raise NoOrangesError, "This tree has no oranges" unless self.any_oranges?
    @oranges.pop
  end

end

class Orange
  attr_reader :diameter
  # Initializes a new Orange with diameter +diameter+
  def initialize(diameter)
    @diameter = diameter
  end
end

tree_test = OrangeTree.new()


text:
<?php

namespace fm\erpBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * ordenesfabricacionRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ordenesfabricacionRepository extends EntityRepository
{
}


text:
'    limitations under the License.
'    See the License for the specific language governing permissions and
'    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
'    distributed under the License is distributed on an "AS IS" BASIS,
'    Unless required by applicable law or agreed to in writing, software
'
'      http://www.apache.org/licenses/LICENSE-2.0
'
'    You may obtain a copy of the License at
'    you may not use this file except in compliance with the License.
'    Licensed under the Apache License, Version 2.0 (the "License");
'
'  Copyright © 2010-2014 Telerik EAD
'  JustMock Lite

Imports System.Text
Imports Microsoft.VisualStudio.TestTools.UnitTesting

Namespace JustMock.NonElevatedExamples.BasicUsage.Mock_CallOriginal
    ''' <summary>
    ''' The CallOriginal method marks a mocked method/property call that should execute the original method/property implementation.
    ''' See http://www.telerik.com/help/justmock/basic-usage-mock-call-original.html for full documentation of the feature.
    ''' </summary>
    <TestClass> _
    Public Class Mock_CallOriginal_Tests
        <TestMethod> _
        Public Sub ReturnSum_CallOriginal_ReturnsExpectedSum()
            ' ARRANGE
            ' Creating a mock instance of the "Log" class.
            Dim log = Mock.Create(Of Log)()

            ' Arranging when log.ReturnSum() is called with any integers as arguments it should execute its original implementation.
            Mock.Arrange(Function() log.ReturnSum(Arg.AnyInt, Arg.AnyInt)).CallOriginal()

            ' ACT - Calling log.ReturnSum with 1 and 2 as arguments.
            Dim actual = log.ReturnSum(1, 2)

            ' We should expect 3 as a return value
            Dim expected As Integer = 3

            ' ASSERT - We are asserting that the expected and the actual values are equal.
            Assert.AreEqual(expected, actual)
        End Sub

        <TestMethod> _
        <ExpectedException(GetType(Exception))> _
        Public Sub Info_CallOriginal_ThrowException()
            ' ARRANGE
            ' Creating a mock instance of the "Log" class.
            Dim log = Mock.Create(Of Log)()

            ' Arranging when log.Info() is called with any string as an argument it should execute its original implementation.
            Mock.Arrange(Sub() log.Info(Arg.IsAny(Of String)())).CallOriginal()

            ' ACT
            log.Info("test")

            ' ASSERT - We are asserting with the [ExpectedException(typeof(Exception))] test attribute.
        End Sub
    End Class

#Region "SUT"
    Public Class Log
        Public Overridable Function ReturnSum(firstInt As Integer, secondInt As Integer) As Integer
            Return firstInt + secondInt
        End Function

        Public Overridable Sub Info(message As String)
            Throw New Exception(message)
        End Sub
    End Class
#End Region
End Namespace


text:
import collections
import errno
import json
import logging
import math
import os
import pathlib
import pickle
import random
import re
import string
import subprocess
import sys
from time import strftime, gmtime

import numpy as np
import yaml

logger = logging.getLogger(__name__)
logger.setLevel(logging.NOTSET)  # capture everything
logger.disabled = True

def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError as exc:  # Python >2.5
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else:
            raise

class OrderedDefaultdict(collections.OrderedDict):
    """ A defaultdict with OrderedDict as its base class. """

    def __init__(self, default_factory=None, *args, **kwargs):
        if not (default_factory is None
                or isinstance(default_factory, collections.Callable)):
            raise TypeError('first argument must be callable or None')
        super(OrderedDefaultdict, self).__init__(*args, **kwargs)
        self.default_factory = default_factory  # called by __missing__()

    def __missing__(self, key):
        if self.default_factory is None:
            raise KeyError(key, )
        self[key] = value = self.default_factory()
        return value

    def __reduce__(self):  # optional, for pickle support
        args = (self.default_factory,) if self.default_factory else tuple()
        return self.__class__, args, None, None, self.iteritems()

    def __repr__(self):  # optional
        return '%s(%r, %r)' % (self.__class__.__name__, self.default_factory,
                               list(self.iteritems()))

def delete_dramsim_log(path=pathlib.Path('.')):
    files = path.glob('dramsim.*.log')
    for f in files:
        f.unlink()

def setup_logging(module_name, logger):
    # logging setup
    def logfilename():
        """ Construct a unique log file name from: date + 16 char random. """
        timeline = strftime("%Y-%m-%d--%H-%M-%S", gmtime())
        randname = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(16))
        return module_name + "-" + timeline + "-" + randname + ".log"

    # log to file
    full_log_filename = logfilename()
    fileHandler = logging.FileHandler(full_log_filename)
    # formatting for log to file
    # TODO: filehandler should be handler 0 (firesim_topology_with_passes expects this
    # to get the filename) - handle this more appropriately later
    logFormatter = logging.Formatter("%(asctime)s [%(funcName)-12.12s] [%(levelname)-5.5s]  %(message)s")
    fileHandler.setFormatter(logFormatter)
    fileHandler.setLevel(logging.NOTSET)  # log everything to file
    logger.addHandler(fileHandler)

    # log to stdout, without special formatting
    consoleHandler = logging.StreamHandler(stream=sys.stdout)
    consoleHandler.setLevel(logging.DEBUG)  # show only INFO and greater in console
    logger.addHandler(consoleHandler)

def dict_append_val(d, k, v):
    if k in d.keys():
        d[k].append(v)
    else:
        d[k] = [v]

def gen_makefile(x_size, y_size):
    makefile_str = """EXT_DRAMSIM2_PATH = ../DRAMSim2
LIBS = -ldramsim

DEBUG_LEVEL ?= 1

USER_FLAGS += -DDISABLE_PACER -DDEBUG_LEVEL=$(DEBUG_LEVEL) -std=c++11 -I$(EXT_DRAMSIM2_PATH) -L$(EXT_DRAMSIM2_PATH) $(LIBS) -DNOC_X={} -DNOC_Y={}
include ../unittests_Makefile
""".format(x_size, y_size)

    with open("Makefile", "w") as f:
        f.write(makefile_str)

def compile_sim():
    # subprocess.check_call(['make', 'clean'],\
    #        cwd=os.getcwd())
    orig_sim_test = pathlib.Path('sim_test')
    if orig_sim_test.exists():
        orig_sim_test.unlink()
    try:
        out = subprocess.check_output(['make'], \
                                      stderr=subprocess.PIPE, cwd=os.getcwd())

        logger.info('compile_sim> make')
    except subprocess.CalledProcessError as grepexc:
        # print "error code", grepexc.returncode, grepexc.output
        if grepexc.returncode == 2:
            pass
            # logger.error(err)

def run_sim(prefix, stdout=None, stderr=None, timeout=None, exe='sim_test', nb=False):
    print("./{} {}".format(exe, prefix))
    try:
        exe = str(exe)
        if nb:
            p = subprocess.check_call(['./' + exe, str(prefix)], \
                                      stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False, cwd=os.getcwd(),
                                      timeout=timeout)
        else:
            p = subprocess.check_call(['./' + exe, str(prefix)], \
                                      stdout=stdout, stderr=stderr, cwd=os.getcwd(), timeout=timeout)
        logger.info('run_sim> ./' + exe + ' ' + str(prefix))
        return True
    except:
        return False

def run_timeloop(arch, prob, mapp, cwd=os.getcwd(), stdout=None, stderr=None):
    try:
        p = subprocess.check_call(['timeloop-model', str(arch), str(prob), str(mapp)], \
                                  cwd=cwd, stdout=stdout, stderr=stderr)
        logger.info('run_timeloop> timeloop-model {} {} {}'.format(arch, prob, mapp))
        return True
    except:
        return False

def run_timeloop_mapper(arch, prob, mapspace, cwd=os.getcwd(), stdout=None, stderr=None):
    try:
        arch_path = pathlib.Path('timeloop_configs/arch/simba_large.yaml').resolve()
        mapspace_path = pathlib.Path('timeloop_configs/mapspace/mapspace_io.yaml').resolve()
        p = subprocess.check_call(['timeloop-mapper', arch_path, mapspace_path, str(prob), ], \
                                  cwd=cwd, stdout=stdout, stderr=stderr)
        logger.info('run_timeloop> timeloop-mapper {} {} {}'.format(arch, mapspace, prob))
        return True
    except:
        return False

def run_timeloop_mapper_optimal(arch, prob, mapspace, cwd=os.getcwd(), stdout=None, stderr=None):
    try:
        arch_path = pathlib.Path('timeloop_configs/arch/simba_large.yaml').resolve()
        mapspace_path = pathlib.Path('timeloop_configs/mapspace/mapspace_io_optimal.yaml').resolve()
        p = subprocess.check_call(['timeloop-mapper', arch_path, mapspace_path, str(prob), ], \
                                  cwd=cwd, stdout=stdout, stderr=stderr)
        logger.info('run_timeloop> timeloop-mapper {} {} {}'.format(arch, mapspace, prob))
        return True
    except:
        return False

def run_timeloop_mapper_linear(arch, prob, mapspace, cwd=os.getcwd(), stdout=None, stderr=None):
    try:
        print("Running LINEAR PRUNING")
        arch_path = pathlib.Path('timeloop_configs/arch/simba_large.yaml').resolve()
        mapspace_path = pathlib.Path('timeloop_configs/mapspace/mapspace_io_linear.yaml').resolve()
        p = subprocess.check_call(['timeloop-mapper', arch_path, mapspace_path, str(prob), ], \
                                  cwd=cwd, stdout=stdout, stderr=stderr)
        logger.info('run_timeloop> timeloop-mapper {} {} {}'.format(arch, mapspace, prob))
        return True
    except:
        return False

def run_timeloop_mapper_hybrid(arch, prob, mapspace, cwd=os.getcwd(), stdout=None, stderr=None):
    try:
        print("Running HYBRID Random Index + Linear Pruning")
        arch_path = pathlib.Path('timeloop_configs/arch/simba_large.yaml').resolve()
        mapspace_path = pathlib.Path('timeloop_configs/mapspace/mapspace_io_hybrid.yaml').resolve()
        p = subprocess.check_call(['timeloop-mapper', arch_path, mapspace_path, str(prob), ], \
                                  cwd=cwd, stdout=stdout, stderr=stderr)
        logger.info('run_timeloop> timeloop-mapper {} {} {}'.format(arch, mapspace, prob))
        return True
    except:
        return False

def store_json(json_path, data, indent=None):
    with open(json_path, "w") as f:
        json.dump(data, f, indent=indent)

def parse_json(json_path):
    with open(json_path) as f:
        data = json.load(f)
    return data

def parse_yaml(yaml_path):
    with open(yaml_path, 'r') as f:
        data = yaml.full_load(f)
    return data

def store_yaml(yaml_path, data):
    with open(yaml_path, 'w') as f:
        yaml.dump(data, f)

def parse_pickle(pickle_path):
    with open(pickle_path, 'rb') as f:
        data = pickle.load(f)
    return data

def store_pickle(pickle_path, data):
    with open(pickle_path, 'wb') as f:
        pickle.dump(data, f)

# Return prime values from small to large
def get_prime_factors(value):
    factors = []

    # Print the number of two's that divide n
    while (value % 2 == 0):
        factors.append(2)
        value = value // 2

    # value must be odd at this point
    # so a skip of 2 ( i = i + 2) cavalue be used
    for i in range(3, int(math.sqrt(value)) + 1, 2):

        # while i divides value , print i ad divide value
        while (value % i == 0):
            factors.append(i)
            value = value // i

            # Condition if value is a prime
    # number greater than 2
    if value > 2:
        factors.append(value)
    if len(factors) == 0:
        factors.append(1)

    return factors

# remove factor from prime factors
# prob_factors is passed by ref
def update_prime_factors(prob_factors, prob_idx, factor):
    logger.debug("prob_factors {}".format(prob_factors))
    rm_idx = []
    orig_factor = factor
    # print(prob_factors)
    for i, val in enumerate(prob_factors[prob_idx]):
        if factor % val == 0:
            rm_idx.append(i)
            factor = factor // val
        if factor == 1:
            break

    vals = []
    rm_idx.reverse()
    for i in rm_idx:
        vals.append(prob_factors[prob_idx].pop(i))

    if len(prob_factors[prob_idx]) == 0:
        prob_factors[prob_idx] = [1]
    pop_val = 1
    # print(prob_factors)
    logger.debug("updated_prob_factors {}".format(prob_factors))
    for i in vals:
        pop_val = pop_val * i
    assert (pop_val == orig_factor)

# shrink the space
def shrink_factor_space(prob_factors):
    # val get rid of factor of 1
    for prob_idx, _ in enumerate(prob_factors):
        if len(prob_factors[prob_idx]) == 1:
            if prob_factors[prob_idx][0] == 1:
                prob_factors[prob_idx] = []

def compose_prob(file_path, prob_dict):
    input_dict = {}
    input_dict["problem"] = prob_dict
    input_dict['problem']['shape'] = 'cnn-layer'
    input_dict['problem']['Wstride'] = 1
    input_dict['problem']['Hstride'] = 1
    input_dict['problem']['Wdilation'] = 1
    input_dict['problem']['Hdilation'] = 1
    store_yaml(file_path, input_dict)

def get_perm_arr_from_val(val, perm_arr_tup, prob_levels):
    order_idx = np.unravel_index(val, perm_arr_tup)
    perm_idx = list(range(prob_levels))
    perm_arr = [-1] * len(perm_arr_tup)
    # idx is the idx into [0,1,2,3..,6]
    for i, idx in enumerate(order_idx):
        perm_arr[i] = perm_idx[idx]
        del perm_idx[idx]
    return perm_arr

# input perm_arr [0, 3, 5, 6, 2, 4, 1] -> order_idx
# order_idx -> val 333
def get_val_from_perm_arr(self, perm_arr, perm_arr_tup, prob_levels):
    assert (len(perm_arr) == len(perm_arr_tup))
    order_idx = [0] * len(perm_arr)
    perm_idx = list(range(prob_levels))
    for i, idx in enumerate(perm_arr):
        for j, val in enumerate(perm_idx):
            if val == idx:
                order_idx[i] = j
                del perm_idx[j]
                break
    val = np.ravel_multi_index(tuple(order_idx), perm_arr_tup)
    return val

def to_config_str_key(configs):
    configs_arr = [str(v) for v in configs]
    configs_str = "_".join(configs_arr)
    return configs_str

def get_correlation(a, b):
    a = np.array(a)
    b = np.array(b)
    cor = np.corrcoef(a, b)[0, 1]
    return cor

def get_cor_stats(status_dicts):
    arr = []
    for d in status_dicts:
        # baseline
        l_arr = [d['cycle_results'][0]]
        l_arr.append(d['cycle_results'][1])
        l_arr.append(d['cycle_results'][2])
        l_arr.append(d['cycle_results'][4])
        l_arr.append(d['cycle_results'][5])
        l_arr.append(d['cost']['Total'])
        l_arr.append(d['hop_cost'][0] + d['hop_cost'][1])
        l_arr.append(d['hop_cost'][0])
        l_arr.append(d['hop_cost'][1])
        l_arr.append((d['utilized_capacity'][1] + d['utilized_capacity'][2] + d['utilized_capacity'][3]))
        l_arr.append((d['utilized_capacity'][1] + d['utilized_capacity'][2] + d['utilized_capacity'][3] +
                      d['utilized_capacity'][4]))

        l_arr.append((d['utilized_capacity'][1] * d['utilized_capacity'][2] * d['utilized_capacity'][3]) ** (1 / 128))
        l_arr.append((d['utilized_capacity'][1] * d['utilized_capacity'][2] * d['utilized_capacity'][3] *
                      d['utilized_capacity'][4]) ** (1 / 128))
        l_arr.append((np.log2(1 + d['utilized_capacity'][1]) + np.log2(1 + d['utilized_capacity'][2]) + np.log2(
            1 + d['utilized_capacity'][3])))
        l_arr.append((np.log2(1 + d['utilized_capacity'][1]) + np.log2(1 + d['utilized_capacity'][2]) + np.log2(
            1 + d['utilized_capacity'][3]) + np.log2(1 + d['utilized_capacity'][4])))

        arr.append(l_arr)
    arr_np = np.array(arr).T

    cors = []
    for i in range(1, len(l_arr)):
        cor = get_correlation(arr_np[0, :], arr_np[i, :])
        cors.append(cor)

    print(arr_np[-3, :])
    x_label = "Total_Cycles"
    print(f"{x_label}-Unicast_Cycles: {cors[0]}")
    print(f"{x_label}-Multicast_Cycles: {cors[1]}")
    print(f"{x_label}-DRAM_READ_Cycles: {cors[2]}")
    print(f"{x_label}-DRAM_WRITE_Cycles: {cors[3]}")
    print(f"{x_label}-Cost: {cors[4]}")
    print(f"{x_label}-Total_Hops: {cors[5]}")
    print(f"{x_label}-Unicast_Hops: {cors[6]}")
    print(f"{x_label}-Multicast_Hops: {cors[7]}")
    print(f"{x_label}-BufSumGBEx: {cors[8]}")
    print(f"{x_label}-BufSumGBIn: {cors[9]}")
    print(f"{x_label}-BufProdGBEx ** (1/128): {cors[10]}")
    print(f"{x_label}-BufProdGBIn ** (1/128): {cors[11]}")
    print(f"{x_label}-BufProdGBEx log): {cors[12]}")
    print(f"{x_label}-BufProdGBIn log: {cors[13]}")

    return cors

def get_invalid_samples(temp_file):
    total_invalid = 0
    with open(temp_file, 'r') as f:
        lines = f.readlines()
    for line in lines:
        m = re.match(r".*MATCHLIB_TOTAL: (.*), MATCHLIB_VALID.*", line)
        if m:
            # print(m)
            invalid = m.group(1)
            total_invalid += int(invalid)
    return total_invalid

def get_runtime(summary_out):
    runtime_dict = {}

    with open(summary_out, 'r') as f:
        lines = f.readlines()
    key = None
    for line in lines:
        m = re.match(r".*simba_(.*)\/(.*)$", line)
        if m:
            key = m.group(2)
        else:
            m = re.match(r"Elasped time for .*find solution with .* is: (.*)$", line)
            if m:
                runtime_dict[key] = float(m.group(1))
    return runtime_dict

def update_arch(arch_dict, mem_entries, out_path):
    for i, mem in enumerate(arch_dict['arch']['storage']):
        # DRAM has no entries
        if i < len(arch_dict['arch']['storage']) - 1:
            arch_dict['arch']['storage'][i]['entries'] = mem_entries[i]
    store_yaml(out_path, arch_dict)


text:
package com.lchtime.safetyexpress.views;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Xfermode;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * Created by user on 2017/4/14.
 */

public abstract class MaskedImage extends ImageView {
    private static final Xfermode MASK_XFERMODE;
    private Bitmap mask;
    private Paint paint;

    public MaskedImage(Context paramContext) {
        super(paramContext);
    }

    public MaskedImage(Context paramContext, AttributeSet paramAttributeSet) {
        super(paramContext, paramAttributeSet);
    }

    public MaskedImage(Context paramContext, AttributeSet paramAttributeSet, int paramInt) {
        super(paramContext, paramAttributeSet, paramInt);
    }

    public abstract Bitmap createMask();

    protected void onDraw(Canvas paramCanvas) {
        Drawable localDrawable = this.getDrawable();
        if(localDrawable != null) {
            try {
                if(this.paint == null) {
                    Paint localException = new Paint();
                    this.paint = localException;
                    this.paint.setFilterBitmap(false);
                    Paint localStringBuilder1 = this.paint;
                    Xfermode i = MASK_XFERMODE;
                    localStringBuilder1.setXfermode(i);
                }

                float localException1 = this.getWidth() >= this.getHeight()?(float)this.getHeight():(float)this.getWidth();
                float localStringBuilder2 = (float)this.getHeight();
                int i1 = paramCanvas.saveLayer(0.0F, 0.0F, localException1, localException1, (Paint)null, 31);
                int j = this.getWidth() >= this.getHeight()?this.getHeight():this.getWidth();
                int k = this.getHeight();
                localDrawable.setBounds(0, 0, j, j);
                localDrawable.draw(paramCanvas);
                Bitmap localBitmap2;
                if(this.mask == null || this.mask.isRecycled()) {
                    localBitmap2 = this.createMask();
                    this.mask = localBitmap2;
                }

                localBitmap2 = this.mask;
                Paint localPaint3 = this.paint;
                paramCanvas.drawBitmap(localBitmap2, 0.0F, 0.0F, localPaint3);
                paramCanvas.restoreToCount(i1);
            } catch (Exception var10) {
                StringBuilder localStringBuilder = (new StringBuilder()).append("Attempting to draw with recycled bitmap. View ID = ");
                System.out.println("localStringBuilder==" + localStringBuilder);
            }
        }
    }

    static {
        PorterDuff.Mode localMode = PorterDuff.Mode.DST_IN;
        MASK_XFERMODE = new PorterDuffXfermode(localMode);
    }
}


text:
//
//  Copyright 2013, Xamarin Inc.
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
//

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

namespace Xamarin.Auth
{
	public static class WebUtilities
	{
		public static string FormEncode (this IDictionary<string, string> inputs)
		{
			if (inputs == null)
				throw new ArgumentNullException ("inputs");

			var sb = new StringBuilder ();
			var head = "";
			foreach (var p in inputs) {
				sb.Append (head);
				sb.Append (EncodeString (p.Key));
				sb.Append ("=");
				sb.Append (EncodeString (p.Value));
				head = "&";
			}
			return sb.ToString ();
		}

		/// <summary>
		/// Encodes a string according to: http://www.ietf.org/rfc/rfc3986.txt
		/// </summary>
		/// <returns>
		/// The encoded string.
		/// </returns>
		/// <param name='unencoded'>
		/// The string to encode.
		/// </param>
		public static string EncodeString (string unencoded)
		{
			if (unencoded == null)
				throw new ArgumentNullException ("unencoded");

			var utf8 = Encoding.UTF8.GetBytes (unencoded);
			var sb = new StringBuilder ();

			for (var i = 0; i < utf8.Length; i++) {
				var v = utf8[i];
				if ((0x41 <= v && v <= 0x5A) || (0x61 <= v && v <= 0x7A) || (0x30 <= v && v <= 0x39) ||
				    v == 0x2D || v == 0x2E || v == 0x5F || v == 0x7E) {
					sb.Append ((char)v);
				} else {
					sb.AppendFormat (CultureInfo.InvariantCulture, "%{0:X2}", v);
				}
			}

			return sb.ToString ();
		}
	}
}