text:
/**
 * @author jbouny / https://github.com/fft-ocean
 */

var DEMO =
{
	ms_Renderer : null,
	ms_Camera : null,
	ms_Scene : null,
	ms_Controls : null,
	ms_Ocean : null,
	ms_Environment : "night",
	ms_Raining : false,

	ms_Commands : {
		states : {
			up : false,
			right : false,
			down : false,
			left : false
		},
		movements : {
			speed : 0.0,
			angle : 0.0
		}
	},

	Initialize : function () {

		this.ms_Renderer = new THREE.WebGLRenderer();
		this.ms_Renderer.context.getExtension( 'OES_texture_float' );
		this.ms_Renderer.context.getExtension( 'OES_texture_float_linear' );
		this.ms_Renderer.setClearColor( 0x000000 );

		document.body.appendChild( this.ms_Renderer.domElement );

		this.ms_Scene = new THREE.Scene();

		this.ms_GroupShip = new THREE.Object3D();
		this.ms_BlackPearlShip = new THREE.Object3D();
		this.ms_Scene.add( this.ms_GroupShip );
		this.ms_GroupShip.add( this.ms_BlackPearlShip );

		this.ms_Camera = new THREE.PerspectiveCamera( 55.0, WINDOW.ms_Width / WINDOW.ms_Height, 0.5, 1000000 );
		this.ms_Camera.position.set( 0, 350, 800 );
		this.ms_Camera.lookAt( new THREE.Vector3() );
		this.ms_BlackPearlShip.add( this.ms_Camera );

		// Initialize Orbit control
		this.ms_Controls = new THREE.OrbitControls( this.ms_Camera, this.ms_Renderer.domElement );
		this.ms_Controls.userPan = false;
		this.ms_Controls.target.set( 0, 100.0, 0 );
		this.ms_Controls.noKeys = true;
		this.ms_Controls.userPanSpeed = 0;
		this.ms_Controls.minDistance = 0;
		this.ms_Controls.maxDistance = 20000.0;
		this.ms_Controls.minPolarAngle = 0;
		this.ms_Controls.maxPolarAngle = Math.PI * 0.75;

    this.InitializeSound();
		this.InitializeLoader();
		this.InitializeScene();

		this.InitGui();
		this.InitCommands();

	},

  InitializeSound : function InitializeSound() {

    var initSound = function initSound( url ) {

      if ( window.HTMLAudioElement ) {

        var sound = new Audio('');

        if ( sound.canPlayType( 'audio/mp3' ) ) {

          var sound = new Audio( url );

          sound.addEventListener( 'ended', function() {
            this.currentTime = 0;
            this.play();
          }, false );

          return sound;

        }

      }

    };

    this.ms_soundWaves = initSound( 'sound/waves.mp3' );
    this.ms_soundRain = initSound( 'sound/rain.mp3' );

    this.ms_soundWaves.play();

  },

  InitializeLoader : function InitializeLoader() {

    this.ms_Loader = new THREE.LoadingManager();

    var log = function( message, type, timeout ) {
      console.log( message );
      messg( message, type, timeout );
    }

    var delay = 1500;
    this.ms_Loader.onProgress = function( item, loaded, total ) {
      log( 'Loaded ' + loaded + '/' + total + ':' + item, 'info', delay );
    };
    this.ms_Loader.onLoad = function () {
      log( 'Loaded.', 'success', delay );
    };
    this.ms_Loader.onError = function () {
      log( 'Loading error.', 'error', delay );
    };

    this.ms_ImageLoader = new THREE.ImageLoader( this.ms_Loader );

  },

	InitializeScene : function InitializeScene() {

		// Add light
		this.ms_MainDirectionalLight = new THREE.DirectionalLight( 0xffffff, 1.5 );
		this.ms_MainDirectionalLight.position.set( -0.2, 0.5, 1 );
		this.ms_Scene.add( this.ms_MainDirectionalLight );

		// Add Black Pearl
		var loader = new THREE.OBJMTLLoader( this.ms_Loader );
		this.ms_BlackPearl = null;
		loader.load( 'models/BlackPearl/BlackPearl.obj', 'models/BlackPearl/BlackPearl.mtl', function ( object ) {
			object.position.y = 20.0;
			if( object.children ) {
				for( child in object.children ) {
					object.children[child].material.side = THREE.DoubleSide;
				}
			}

			DEMO.ms_BlackPearlShip.add( object );
			DEMO.ms_BlackPearl = object;
		} );

		// Add rain
		{
			var size = 128;
      var rainTexture = new THREE.Texture();
      rainTexture.generateMipmaps = false;
      rainTexture.magFilter = THREE.LinearFilter;
      rainTexture.minFilter = THREE.LinearFilter;
      this.ms_ImageLoader.load( 'img/water-drop.png', function ( image ) {
          rainTexture.image = image;
          rainTexture.needsUpdate = true;
      } );

      var rainShader = THREE.ShaderLib['rain'];

			var rainMaterial = new THREE.ShaderMaterial({
        fragmentShader: rainShader.fragmentShader,
        vertexShader: rainShader.vertexShader,
        uniforms: rainShader.uniforms,
				transparent: true,
				depthWrite: false
			});
      rainMaterial.uniforms.texture.value = rainTexture;

			this.ms_RainGeometry = new THREE.Geometry();
			for ( i = 0; i < 100; i++ )
			{
				var vertex = new THREE.Vector3();
				vertex.x = Math.random() * 2.0 * size - size;
				vertex.y = Math.random() * 2.0 * size - size;
				vertex.z = Math.random() * size - size * 0.5;
				this.ms_RainGeometry.vertices.push( vertex );
			}
			this.ms_Rain = new THREE.PointCloud( this.ms_RainGeometry, rainMaterial );
			this.ms_Camera.add( this.ms_Rain );
			this.ms_Rain.position.setZ( - size * 0.75 ) ;
		}

		// Initialize Clouds
		this.ms_CloudShader = new CloudShader( this.ms_Renderer );
		this.ms_CloudShader.cloudMesh.scale.multiplyScalar( 4.0 );
		this.ms_Scene.add( this.ms_CloudShader.cloudMesh );

		// Initialize Ocean
		var gsize = 512;
		var res = 512;
		var gres = 256;
		var origx = -gsize / 2;
		var origz = -gsize / 2;
		this.ms_Ocean = new THREE.Ocean( this.ms_Renderer, this.ms_Camera, this.ms_Scene,
		{
			INITIAL_SIZE : 200.0,
			INITIAL_WIND : [ 10.0, 10.0 ],
			INITIAL_CHOPPINESS : 3.6,
			CLEAR_COLOR : [ 1.0, 1.0, 1.0, 0.0 ],
			SUN_DIRECTION : this.ms_MainDirectionalLight.position.clone(),
			OCEAN_COLOR: new THREE.Vector3( 0.35, 0.4, 0.45 ),
			SKY_COLOR: new THREE.Vector3( 10.0, 13.0, 15.0 ),
			EXPOSURE : 0.15,
			GEOMETRY_RESOLUTION: gres,
			GEOMETRY_SIZE : gsize,
			RESOLUTION : res
		} );

		this.LoadSkyBox();
		this.LoadMountains();
	},

	InitGui : function InitGui() {

		// Initialize UI
		var gui = new dat.GUI();
		dat.GUI.toggleHide();

		gui.add( this.ms_Ocean, "size", 10, 2000 ).onChange( function( v ) {
			this.object.size = v;
			this.object.changed = true;
		} );
		gui.add( this.ms_Ocean.materialSpectrum.uniforms.u_choppiness, "value", 0.1, 8 ).name( "choppiness" );
		gui.add( this.ms_Ocean, "windX", -50, 50 ).onChange( function ( v ) {
			this.object.windX = v;
			this.object.changed = true;
		} );
		gui.add( this.ms_Ocean, "windY", -50, 50 ).onChange( function ( v ) {
			this.object.windY = v;
			this.object.changed = true;
		} );
		gui.add( this.ms_Ocean, "exposure", 0.0, 0.5 ).onChange( function ( v ) {
			this.object.exposure = v;
			this.object.changed = true;
		} );
		gui.add( DEMO.ms_Ocean.materialOcean, "wireframe" );

		var demo = this;

		$( '#env-selector > ul > li[key="' + this.ms_Environment + '"]' ).addClass( 'selected' );
		$( '#env-selector > ul > li' ).click( function() {
			demo.UpdateEnvironment( $( this ).attr('key') );

			$( '#env-selector > ul > li' ).removeClass( 'selected' );
			$( this ).addClass( 'selected' );
		} ).each( function() {
      $( this ).html( '' + $( this ).html() + '' );
    } ) ;

	},

	InitCommands : function InitCommands() {

		var LEFT = 37,
			UP = 38,
			RIGHT = 39,
			DOWN = 40;

		var keyHandler = function keyHandler( action ) {
			return function( event ) {
				var key = event.which;
				if( key >= LEFT && key <= DOWN ) {
					switch( key ) {
						case UP : DEMO.ms_Commands.states.up = action ; break ;
						case RIGHT : DEMO.ms_Commands.states.right = action ; break ;
						case DOWN : DEMO.ms_Commands.states.down = action ; break ;
						case LEFT : DEMO.ms_Commands.states.left = action ; break ;
					}
				}
			}
		}

		$( document ).keydown( keyHandler( true ) );
		$( document ).keyup( keyHandler( false ) );

	},

	LoadMountains : function LoadSkyBox() {

		var demo = this;

    var mountainTexture = new THREE.Texture();
    mountainTexture.generateMipmaps = false;
    mountainTexture.magFilter = THREE.LinearFilter;
    mountainTexture.minFilter = THREE.LinearFilter;
    this.ms_ImageLoader.load( 'img/mountains.png', function ( image ) {
        mountainTexture.image = image;
        mountainTexture.needsUpdate = true;
    } );

		var mountainsMaterial = new THREE.MeshBasicMaterial( {
			map: mountainTexture,
			transparent: true,
			side: THREE.BackSide,
			depthWrite: false
		} );

		var addMountain = function addMountain( size ) {

			var moutains = new THREE.Mesh(
				new THREE.CylinderGeometry( size, size, 35000, 32, 1, true ),
				mountainsMaterial
			);
			moutains.position.y = 10000;
			demo.ms_Scene.add( moutains );

		} ;

		// Add twice with different size in order to avoid some artifacts on the reflection
		addMountain( 120000 );
		addMountain( 150000 );

		// Add a black cylinder to hide the skybox under the water
		var cylinder = new THREE.Mesh(
			new THREE.CylinderGeometry( 150000, 150000, 150000, 32, 1, true ),
			new THREE.MeshBasicMaterial( { color: "0xffffff", side: THREE.BackSide } )
		);
		cylinder.position.y = -80000;
		demo.ms_Scene.add( cylinder );

	},

	LoadSkyBox : function LoadSkyBox() {

		var cubeShader = THREE.ShaderLib['cube'];

		var skyBoxMaterial = new THREE.ShaderMaterial( {
			fragmentShader: cubeShader.fragmentShader,
			vertexShader: cubeShader.vertexShader,
			uniforms: cubeShader.uniforms,
			side: THREE.BackSide
		} );

		this.ms_SkyBox = new THREE.Mesh(
			new THREE.BoxGeometry( 450000, 450000, 450000 ),
			skyBoxMaterial
		);

		this.ms_Scene.add( this.ms_SkyBox );

    // https://stackoverflow.com/questions/3552944/how-to-get-the-anchor-from-the-url-using-jquery
    var url = window.location.href, idx = url.indexOf("#");
    var anchor = idx != -1 ? url.substring(idx+1) : null;
    var environmentParameter = anchor;

    if( environmentParameter !== null ) {
      this.ms_Environment = environmentParameter;
    }

		this.UpdateEnvironment( this.ms_Environment );

	},

	UpdateEnvironment : function UpdateEnvironment( key ) {

		var textureName = '';
		var textureExt = ".jpg";
		var directionalLightPosition = null;
		var directionalLightColor = null;
		var raining = false;

		switch( key ) {
			case 'night':
				textureName = 'grimmnight';
				directionalLightPosition = new THREE.Vector3( -0.3, 0.3, 1 );
				directionalLightColor = new THREE.Color( 1, 1, 1 );
				raining = true;
				break;
			case 'morning':
				textureName = 'clouds';
				directionalLightPosition = new THREE.Vector3( -1, 0.5, 0.8 );
				directionalLightColor = new THREE.Color( 1, 0.95, 0.8 );
				break;
			case 'day':
				textureName = 'sky';
				directionalLightPosition = new THREE.Vector3( -0.5, 0.5, -0.6 );
				directionalLightColor = new THREE.Color( 1, 0.95, 0.9 );
				break;
			case 'cloudy':
				textureName = 'miramar';
				directionalLightPosition = new THREE.Vector3( 0.3, 1.0, 0.5 );
				directionalLightColor = new THREE.Color( 0.9, 0.95, 1 );
				raining = true;
				break;
			case 'sunset':
				textureName = 'sunset';
				directionalLightPosition = new THREE.Vector3( -0.7, 0.2, -1 );
				directionalLightColor = new THREE.Color( 1, 0.8, 0.5 );
				break;
			case 'interstellar':
				textureName = 'interstellar';
				directionalLightPosition = new THREE.Vector3( -0.7, 1.0, -0.4 );
				directionalLightColor = new THREE.Color( 0.8, 1.0, 0.95 );
				break;
			case 'apocalypse':
				textureName = 'violent_days';
				directionalLightPosition = new THREE.Vector3( 1, 0.3, 1 );
				directionalLightColor = new THREE.Color( 1, 0.85, 0.3 );
				break;
			default:
				return;
		};

		this.ms_Environment = key;
		this.ms_Raining = raining;
		this.ms_MainDirectionalLight.position.copy( directionalLightPosition );
		this.ms_MainDirectionalLight.color.copy( directionalLightColor );
		this.ms_Ocean.materialOcean.uniforms.u_sunDirection.value.copy( this.ms_MainDirectionalLight.position );
    if ( raining ) {
      this.ms_soundRain.play();
    }
    else {
      this.ms_soundRain.pause();
    }

    var sources = [
			'img/' + textureName + '_west' + textureExt,
			'img/' + textureName + '_east' + textureExt,
			'img/' + textureName + '_up' + textureExt,
			'img/' + textureName + '_down' + textureExt,
			'img/' + textureName + '_south' + textureExt,
			'img/' + textureName + '_north' + textureExt
		];
    var images = [];

    var cubeMap = new THREE.CubeTexture( images );
    cubeMap.flipY = false;

    var imageLoader = this.ms_ImageLoader;
    var loaded = 0;
    var loadTexture = function ( i ) {
      imageLoader.load( sources[ i ], function ( image ) {
        cubeMap.images[ i ] = image;
        loaded ++;
        if ( loaded === 6 ) {
          cubeMap.needsUpdate = true;
        }
      } );

    }

    for ( var i = 0, il = sources.length; i < il; ++ i ) {
      loadTexture( i );
    }

		cubeMap.format = THREE.RGBFormat;
    cubeMap.generateMipmaps = false;
    cubeMap.magFilter = THREE.LinearFilter;
    cubeMap.minFilter = THREE.LinearFilter;

		this.ms_SkyBox.material.uniforms['tCube'].value = cubeMap;
	},

	Display : function () {

		this.ms_Renderer.render( this.ms_Scene, this.ms_Camera );

	},

	Update : function () {

		// Update camera position
		if( this.ms_Camera.position.y < 0.0 ) {
			this.ms_Camera.position.y = 2.0;
		}

		// Update black ship displacements
		this.UpdateCommands();
		this.ms_GroupShip.rotation.y += this.ms_Commands.movements.angle;
		this.ms_BlackPearlShip.rotation.z = -this.ms_Commands.movements.angle * 10.0;
		this.ms_BlackPearlShip.rotation.x = this.ms_Commands.movements.speed * 0.1;
		var shipDisplacement = (new THREE.Vector3(0, 0, -1)).applyEuler(this.ms_GroupShip.rotation).multiplyScalar( 10.0 * this.ms_Commands.movements.speed );
		this.ms_GroupShip.position.add( shipDisplacement );

		var currentTime = new Date().getTime();
		this.ms_Ocean.deltaTime = ( currentTime - lastTime ) / 1000 || 0.0;
		lastTime = currentTime;

		// Update black ship movements
		if( this.ms_BlackPearl !== null )
		{
			var animationRatio = 1.0 + this.ms_Commands.movements.speed * 1.0;
			this.ms_BlackPearl.rotation.y = Math.cos( currentTime * 0.0008 ) * 0.05 - 0.025;
			this.ms_BlackPearl.rotation.x = Math.sin( currentTime * 0.001154 + 0.78 ) * 0.1 + 0.05;
		}

		// Update rain
		if( this.ms_Raining ) {
			var seed = 1;
			var fastRandom = function fastRandom() {
				// https://stackoverflow.com/questions/521295/javascript-random-seeds
				var x = Math.sin( seed++ ) * 10000;
				return x - Math.floor( x );
			}
			for( i in this.ms_RainGeometry.vertices )
			{
				var speed = 4.0;
				this.ms_RainGeometry.vertices[i].y -= fastRandom() * speed + speed;
				if( this.ms_RainGeometry.vertices[i].y < -50 )
					this.ms_RainGeometry.vertices[i].y = 50;
			}
			this.ms_Rain.rotation.set( -this.ms_Camera.rotation.x, -this.ms_Camera.rotation.y, -this.ms_Camera.rotation.z, "ZYX" );
			this.ms_RainGeometry.verticesNeedUpdate = true;
		}

		// Render ocean reflection
		this.ms_Camera.remove( this.ms_Rain );
		this.ms_Ocean.render();
		if( this.ms_Raining )
			this.ms_Camera.add( this.ms_Rain );

		// Updade clouds
		this.ms_CloudShader.update();

		// Update ocean data
		this.ms_Ocean.update();

		this.ms_Controls.update();
		this.Display();

	},

	UpdateCommands : function UpdateCommands() {

		var states = this.ms_Commands.states;

		// Update speed
		var targetSpeed = 0.0;
		if( states.up ) {
			targetSpeed = 1.0;
		}
		else if( states.down ) {
			targetSpeed = -0.5;
		}
		var curSpeed = this.ms_Commands.movements.speed ;
		this.ms_Commands.movements.speed = curSpeed + ( targetSpeed - curSpeed ) * 0.02;

		// Update angle
		var targetAngle = 0.0;
		if( states.left ) {
			targetAngle = Math.PI * 0.005;
		}
		else if( states.right ) {
			targetAngle = -Math.PI * 0.005;
		}
    if( states.down ) {
      targetAngle *= -1.0;
    }

		var curAngle = this.ms_Commands.movements.angle ;
		this.ms_Commands.movements.angle = curAngle + ( targetAngle - curAngle ) * 0.02;

	},

	Resize : function ( inWidth, inHeight ) {

		this.ms_Camera.aspect = inWidth / inHeight;
		this.ms_Camera.updateProjectionMatrix();
		this.ms_Renderer.setSize( inWidth, inHeight );
		this.Display();

	}
};


text:
typedef struct Font Font;

typedef int CharacterWidthFontFunction(const Font *font,int c);
typedef int StringWidthFontFunction(const Font *font,const void *str);
typedef void DrawCharacterFontFunction(Bitmap *bitmap,const Font *font,int x,int y,Pixel col,int c);
typedef void DrawStringFontFunction(Bitmap *bitmap,const Font *font,int x,int y,Pixel col,const void *str);
typedef void CompositeCharacterFontFunction(Bitmap *bitmap,const Font *font,int x,int y,Pixel col,CompositionMode comp,int c);
typedef void CompositeStringFontFunction(Bitmap *bitmap,const Font *font,int x,int y,Pixel col,CompositionMode comp,const void *str);

struct Font
{
	int height;

	CharacterWidthFontFunction *charwidthfunc;
	StringWidthFontFunction *stringwidthfunc;
	DrawCharacterFontFunction *drawcharfunc;
	DrawStringFontFunction *drawstringfunc;
	CompositeCharacterFontFunction *compcharfunc;
	CompositeStringFontFunction *compstringfunc;
};

static inline int HeightOfFont(const Font *font)
{
	return font->height;
}

static inline int WidthOfCharacter(const Font *font,int c)
{
	return font->charwidthfunc(font,c);
}

static inline int WidthOfString(const Font *font,const void *str)
{
	return font->stringwidthfunc(font,str);
}

static inline void DrawCharacter(Bitmap *bitmap,const Font *font,int x,int y,Pixel col,int c)
{
	font->drawcharfunc(bitmap,font,x,y,col,c);
}

static inline void DrawString(Bitmap *bitmap,const Font *font,int x,int y,Pixel col,const void *str)
{
	font->drawstringfunc(bitmap,font,x,y,col,str);
}

static inline void CompositeCharacter(Bitmap *bitmap,const Font *font,int x,int y,Pixel col,CompositionMode comp,int c)
{
	font->compcharfunc(bitmap,font,x,y,col,comp,c);
}

static inline void CompositeString(Bitmap *bitmap,const Font *font,int x,int y,Pixel col,CompositionMode comp,const void *str)
{
	font->compstringfunc(bitmap,font,x,y,col,comp,str);
}

static inline void DrawStringToTheLeftOf(Bitmap *bitmap,const Font *font,
int x,int y,Pixel col,const void *str)
{
	int stringwidth=WidthOfString(font,str);
	DrawString(bitmap,font,x-stringwidth+1,y,col,str);
}

static inline void DrawStringCenteredInRectangle(Bitmap *bitmap,const Font *font,
int x,int y,int w,int h,Pixel col,const void *str)
{
	int stringwidth=WidthOfString(font,str);
	int stringheight=HeightOfFont(font);
	DrawString(bitmap,font,x+(w-stringwidth)/2,y+(h-stringheight)/2,col,str);
}

static inline void CompositeStringToTheLeftOf(Bitmap *bitmap,const Font *font,
int x,int y,Pixel col,CompositionMode comp,const void *str)
{
	int stringwidth=WidthOfString(font,str);
	CompositeString(bitmap,font,x-stringwidth+1,y,col,comp,str);
}

static inline void CompositeStringCenteredInRectangle(Bitmap *bitmap,const Font *font,
int x,int y,int w,int h,Pixel col,CompositionMode comp,const void *str)
{
	int stringwidth=WidthOfString(font,str);
	int stringheight=HeightOfFont(font);
	CompositeString(bitmap,font,x+(w-stringwidth)/2,y+(h-stringheight)/2,col,comp,str);
}

int WidthOfSimpleString(const Font *font,const void *str);
void DrawSimpleString(Bitmap *bitmap,const Font *font,int x,int y,Pixel col,const void *str);
void CompositeSimpleString(Bitmap *bitmap,const Font *font,int x,int y,Pixel col,CompositionMode comp,const void *str);

#endif

redpajama_set_name: RedPajamaGithub


text:
/**
 * @constructor
 */
WebInspector.WorkspaceController = function(workspace)
{
    this._workspace = workspace;
    WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.InspectedURLChanged, this._inspectedURLChanged, this);
    window.addEventListener("focus", this._windowFocused.bind(this), false);
}

WebInspector.WorkspaceController.prototype = {
    /**
     * @param {WebInspector.Event} event
     */
    _inspectedURLChanged: function(event)
    {
        WebInspector.Revision.filterOutStaleRevisions();
    },

    /**
     * @param {Event} event
     */
    _windowFocused: function(event)
    {
        if (this._fileSystemRefreshTimeout)
            return;
        this._fileSystemRefreshTimeout = setTimeout(refreshFileSystems.bind(this), 1000);

        function refreshFileSystems()
        {
            delete this._fileSystemRefreshTimeout;
            var projects = this._workspace.projects();
            for (var i = 0; i < projects.length; ++i)
                projects[i].refresh("/");
        }
    }
}

/**
 * @type {?WebInspector.WorkspaceController}
 */
WebInspector.workspaceController = null;


text:
using System.Globalization;
using GeoJSON.Net.CoordinateReferenceSystem;
using GeoJSON.Net.Geometry;
using NUnit.Framework;
using Newtonsoft.Json;

namespace GeoJSON.Net.Tests
{
    [TestFixture]
    public class SerializationTests
    {
        [Test]
        public void Should_serialize_Enumeration_to_simplified_json()
        {
            var point = new Point(new GeographicPosition(1, 2))
                {
                    CRS = new NamedCRS(26912.ToString(CultureInfo.InvariantCulture))
                };

            Assert.That(point.Type, Is.EqualTo(GeoJSONObjectType.Point));

            var json = JsonConvert.SerializeObject(point);
            Assert.AreEqual(
                @"{""coordinates"":[2.0,1.0],""bbox"":null,""type"":""Point"",""crs"":{""type"":""Name"",""properties"":{""name"":""26912""}}}",
                json);
        }
    }
}


text:
__author__ = 'ggdhines'
import matplotlib
matplotlib.use('WXAgg')
import aggregation_api
import cv2
import numpy as np
import matplotlib.pyplot as plt
from aggregation_api import AggregationAPI
from sklearn.cluster import KMeans
import matplotlib.cbook as cbook

jungle = AggregationAPI(153,"development")
# jungle.__migrate__()
# jungle.__aggregate__()

postgres_cursor = jungle.postgres_session.cursor()
postgres_cursor.execute("select subject_ids,annotations from classifications where project_id = 153")

markings = {}

for subject_ids,annotations in postgres_cursor.fetchall():

    if subject_ids == []:
        continue
    s = subject_ids[0]
    for task in annotations:
        if task["task"] == "T2":
            try:
                m = task["value"][0]["points"]
                if s not in markings:
                    markings[s] = [m]
                else:
                    markings[s].append(m)
            except (KeyError,IndexError) as e:
                pass

for subject_id,points in markings.items():
    fname = jungle.__image_setup__(subject_id)

    image_file = cbook.get_sample_data(fname)
    image = plt.imread(image_file)

    fig, ax1 = plt.subplots(1, 1)
    ax1.imshow(image)

    all_points = []
    for a in points:
        for b in a:
            all_points.append((b["x"],b["y"]))

    if len(all_points) < 6:
        plt.close()
        continue

    kmeans = KMeans(init='k-means++', n_clusters=6, n_init=10)
    all_points = np.asarray(all_points)
    kmeans.fit(all_points)

    labels = kmeans.labels_

    unique_labels = set(labels)
    colors = plt.cm.Spectral(np.linspace(0, 1, len(unique_labels)))
    for k, col in zip(unique_labels, colors):
        class_member_mask = (labels == k)

        xy = all_points[class_member_mask]
        plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=col,markeredgecolor='k', markersize=14)

    plt.show()

assert False

def analyze(f_name,display=False):
    image = cv2.imread(f_name)
    gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    # image2 = cv2.threshold(image,127,255,cv2.THRESH_BINARY)

    # cv2.imwrite("/home/ggdhines/jungle.jpeg",gray_image)

    # print gray_image.ravel()
    ix = np.in1d(gray_image.ravel(),range(175)).reshape(gray_image.shape)
    x,y = np.where(ix)

    if display:
        plt.plot(y,x,".")
        plt.ylim((gray_image.shape[0],0))
        plt.show()

    n, bins, patches = plt.hist(y,range(min(y),max(y)+1))
    med = np.median(n)

    peaks = [i for i,count in enumerate(n) if count > 2*med]
    buckets = [[peaks[0]]]

    for j,p in list(enumerate(peaks))[1:]:
        if (p-1) != (peaks[j-1]):
            buckets.append([p])
        else:
            buckets[-1].append(p)

    bucket_items = list(enumerate(buckets))
    bucket_items.sort(key = lambda x:len(x[1]),reverse=True)

    a = bucket_items[0][0]
    b = bucket_items[1][0]

    vert = []
    for x,p in bucket_items:
        if (a <= x <= b) or (b <= x <= a):
            vert.extend(p)

    print vert
    print min(vert)
    print max(vert)

    if display:
        plt.plot((min(y),max(y)+1),(2*med,2*med))
        plt.show()

        n, bins, patches = plt.hist(x,range(min(x),max(x)+1))
        med = np.median(n)

        plt.plot((min(x),max(x)+1),(2*med,2*med))
        plt.plot((min(x),max(x)+1),(1*med,1*med),color="red")
        plt.xlim((0,max(x)+1))
        plt.show()

if __name__ == "__main__":
    project = aggregation_api.AggregationAPI(153,"development")
    f_name = project.__image_setup__(1125393)
    print f_name
    analyze(f_name,display=True)


text:
/*
 * Main author: Yann Sagon <yann.sagon@unige.ch>
 */
import java.io.*;
import java.util.*;
public class Cavity2d {
   public static void main(String[] args) throws FileNotFoundException{

      // load all the needed libraries and initialize Palabos
      jlabos.JlabosBase base = jlabos.JlabosBase.getSingletonObject();

      // parse a parameter file in yaml format
      jlabos.Param param = new jlabos.Param("param.yml");

      // Dimensions of the system in lattice units.
      int lx = param.getIntValue(Arrays.asList("geometry", "lx"));
      int ly = param.getIntValue(Arrays.asList("geometry", "ly"));
      int nx = lx+1;
      int ny = ly+1;

      // Discrete space step (ly is the reference length).
      double dx = 1./lx;
      // Maximum velocity in lattice units.
      double uMax = param.getDblValue(Arrays.asList("simulation", "uMax"));
      // Reynolds number (wrt ly)
      double Re   = param.getDblValue(Arrays.asList("simulation", "Re"));
      double nu = uMax*ly / Re;  // Viscosity in lattice units.
      double tau = 3*nu+0.5;     // Relaxation time.
      // Maximum number of iterations.
      int maxIter = param.getIntValue(Arrays.asList("iteration", "maxIter"));
      // Intervals at which some statistics is printed.
      int statIter = param.getIntValue(Arrays.asList("iteration", "statIter"));

      // filename for writing output (without ext)
      String fName = param.getStrValue(Arrays.asList("general", "files", "out"));

      jlabos.Utils.pout("dx : " + dx);
      jlabos.Utils.pout("nu : " + nu);
      jlabos.Utils.pout("tau : " + tau);

      // Allocate memory for the block-lattice, and assign the dynamics.

      jlabos.Box2D domain = new jlabos.Box2D(0, lx, 0, ly);

      jlabos.MultiBlockLattice2D lattice = new jlabos.MultiBlockLattice2D(domain, jlabos.Descriptor.D2Q9, new jlabos.BGK(1./tau));

      jlabos.Utils.pout(jlabos.MultiBlockUtils.info(lattice));

      jlabos.OuterBoxBC.setVelocityCondition(lattice, domain);

      lattice.setBoundaryVelocity(new double[] {0.,0.}, domain);

      // Top lid has constant in-plane velocity.
      lattice.setBoundaryVelocity(new double[] {uMax,0.}, new jlabos.Box2D(1, nx-2, ny-1, ny-1));

      lattice.initializeAtEquilibrium(1., new double[] {0.0,0.}, domain);

      java.util.Vector<jlabos.MultiNTensorField2DDouble> snapshot = new java.util.Vector<jlabos.MultiNTensorField2DDouble>();

      long startTime = System.currentTimeMillis()/1000;
      for(int i=0;i<maxIter+1; i++){
         if (i%statIter==0 && i>0){

            // Compute a velocity snapshot of the system, and keep it safe.
            snapshot.add(lattice.velocityNorm(domain));

            // Apply a reduction operation to compute the average kinetic energy.
            jlabos.Utils.pout("Average energy : " + lattice.averageEnergy());

            // Use Java's timer to compute the efficiency of the computations.
            long elapsed = System.currentTimeMillis()/1000-startTime;
            double Msups = i*nx*ny / elapsed / 1e6;
            jlabos.Utils.pout("Efficiency: " + Msups + " Mega site updates per second.");
         }
         // This is the real computation: evolving through a collision-streaming cycle.
         lattice.collideAndStream();
      }

      jlabos.Utils.pout("Plotting results");
      int index = 0;
      for(jlabos.MultiNTensorField2DDouble item : snapshot){
         jlabos.Utils.saveAsJpg(item, fName + index, 800);
         // write as svg if needed (large files!)
         //jlabos.Utils.saveAsSvg(item, "res" + index, 800);
         // write as text file if needed (to be used with octave for example)
         item.writeToFile(new String(fName + index++ + ".txt"));
      }

   }

}


text:
package blogger

import (
	"log"
	"os"
	"strings"
	"time"
)

type bLogger struct {
	*log.Logger
}

type Log struct {
	command string
	message string
	level   string
}

var (
	bl = bLogger{log.New(os.Stdout, "bob ", 0)}
)

func (l Log) Command(command string) Log {
	l.command = command
	return l
}

func (l Log) Message(message ...string) Log {
	l.message = strings.Join(message, " ")
	return l
}

func Error() Log {
	return Log{level: "error"}
}

func Info() Log {
	return Log{level: "info"}
}

func Warn() Log {
	return Log{level: "warn"}
}

func (l Log) Log() {
	out := "[" + time.Now().Format("15:04:05") + "] "
	if l.command != "" {
		out += l.command + " "
	}
	out += l.message
	bl.Print(out)
}

func FormattedMessage(message string) string {
	return "'" + message + "'"
}


text:
namespace tracing {

// static
TracedProcessImpl* TracedProcessImpl::GetInstance() {
  static base::NoDestructor<TracedProcessImpl> traced_process;
  return traced_process.get();
}

TracedProcessImpl::TracedProcessImpl() {
  DETACH_FROM_SEQUENCE(sequence_checker_);
}

TracedProcessImpl::~TracedProcessImpl() = default;

void TracedProcessImpl::ResetTracedProcessReceiver() {
  if (task_runner_ && !task_runner_->RunsTasksInCurrentSequence()) {
    task_runner_->PostTask(
        FROM_HERE,
        base::BindOnce(&TracedProcessImpl::ResetTracedProcessReceiver,
                       base::Unretained(this)));
    return;
  }

  receiver_.reset();
}

void TracedProcessImpl::OnTracedProcessRequest(
    mojo::PendingReceiver<mojom::TracedProcess> receiver) {
  if (task_runner_ && !task_runner_->RunsTasksInCurrentSequence()) {
    task_runner_->PostTask(
        FROM_HERE, base::BindOnce(&TracedProcessImpl::OnTracedProcessRequest,
                                  base::Unretained(this), std::move(receiver)));
    return;
  }

  // We only need one binding per process. If a new binding request is made,
  // ignore it.
  if (receiver_.is_bound())
    return;

  receiver_.Bind(std::move(receiver));
}

mojo::Remote<mojom::SystemTracingService>&
TracedProcessImpl::system_tracing_service() {
  // |system_tracing_service_| can only be used on the Perfetto task runner.
  auto task_runner =
      PerfettoTracedProcess::GetTaskRunner()->GetOrCreateTaskRunner();
  DCHECK(task_runner && task_runner->RunsTasksInCurrentSequence());
  return system_tracing_service_;
}

void TracedProcessImpl::EnableSystemTracingService(
    mojo::PendingRemote<mojom::SystemTracingService> remote) {
  auto task_runner =
      PerfettoTracedProcess::GetTaskRunner()->GetOrCreateTaskRunner();
  if (!task_runner->RunsTasksInCurrentSequence()) {
    // |system_tracing_service_| is bound on the Perfetto task runner.
    task_runner->PostTask(
        FROM_HERE,
        base::BindOnce(&TracedProcessImpl::EnableSystemTracingService,
                       base::Unretained(this), std::move(remote)));
    return;
  }

  system_tracing_service_.Bind(std::move(remote), nullptr);
}

// SetTaskRunner must be called before we start receiving
// any OnTracedProcessRequest calls.
void TracedProcessImpl::SetTaskRunner(
    scoped_refptr<base::SequencedTaskRunner> task_runner) {
  DCHECK(!receiver_.is_bound());
  DCHECK(!task_runner_);
  task_runner_ = task_runner;
}

void TracedProcessImpl::RegisterAgent(BaseAgent* agent) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  base::AutoLock lock(agents_lock_);
  agents_.insert(agent);
}

void TracedProcessImpl::UnregisterAgent(BaseAgent* agent) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  base::AutoLock lock(agents_lock_);
  agents_.erase(agent);
}

void TracedProcessImpl::ConnectToTracingService(
    mojom::ConnectToTracingRequestPtr request,
    ConnectToTracingServiceCallback callback) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  // Acknowledge this message so the tracing service knows it was dispatched in
  // this process.
  std::move(callback).Run();

  // Tracing requires a running ThreadPool; disable tracing
  // for processes without it.
  if (!base::ThreadPoolInstance::Get()) {
    return;
  }

  // Ensure the TraceEventAgent has been created.
  TraceEventAgent::GetInstance();

  PerfettoTracedProcess::Get()->ConnectProducer(
      std::move(request->perfetto_service));
}

void TracedProcessImpl::GetCategories(std::set<std::string>* category_set) {
  base::AutoLock lock(agents_lock_);
  for (auto* agent : agents_) {
    agent->GetCategories(category_set);
  }
}

}  // namespace tracing


text:
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->

## format

An Object containing nested boolean values representing the available input and output formats/methods.

### Examples

```javascript
console.log(sharp.format);
```

Returns **[Object][1]**

## interpolators

An Object containing the available interpolators and their proper values

Type: [string][2]

### nearest

[Nearest neighbour interpolation][3]. Suitable for image enlargement only.

### bilinear

[Bilinear interpolation][4]. Faster than bicubic but with less smooth results.

### bicubic

[Bicubic interpolation][5] (the default).

### locallyBoundedBicubic

[LBB interpolation][6]. Prevents some "[acutance][7]" but typically reduces performance by a factor of 2.

### nohalo

[Nohalo interpolation][8]. Prevents acutance but typically reduces performance by a factor of 3.

### vertexSplitQuadraticBasisSpline

[VSQBS interpolation][9]. Prevents "staircasing" when enlarging.

## versions

An Object containing the version numbers of libvips and its dependencies.

### Examples

```javascript
console.log(sharp.versions);
```

## vendor

An Object containing the platform and architecture
of the current and installed vendored binaries.

### Examples

```javascript
console.log(sharp.vendor);
```

## cache

Gets or, when options are provided, sets the limits of *libvips'* operation cache.
Existing entries in the cache will be trimmed after any change in limits.
This method always returns cache statistics,
useful for determining how much working memory is required for a particular task.

### Parameters

*   `options` **([Object][1] | [boolean][10])** Object with the following attributes, or boolean where true uses default cache settings and false removes all caching (optional, default `true`)

    *   `options.memory` **[number][11]** is the maximum memory in MB to use for this cache (optional, default `50`)
    *   `options.files` **[number][11]** is the maximum number of files to hold open (optional, default `20`)
    *   `options.items` **[number][11]** is the maximum number of operations to cache (optional, default `100`)

### Examples

```javascript
const stats = sharp.cache();
```

```javascript
sharp.cache( { items: 200 } );
sharp.cache( { files: 0 } );
sharp.cache(false);
```

Returns **[Object][1]**

## concurrency

Gets or, when a concurrency is provided, sets
the maximum number of threads *libvips* should use to process *each image*.
These are from a thread pool managed by glib,
which helps avoid the overhead of creating new threads.

This method always returns the current concurrency.

The default value is the number of CPU cores,
except when using glibc-based Linux without jemalloc,
where the default is `1` to help reduce memory fragmentation.

A value of `0` will reset this to the number of CPU cores.

Some image format libraries spawn additional threads,
e.g. libaom manages its own 4 threads when encoding AVIF images,
and these are independent of the value set here.

The maximum number of images that sharp can process in parallel
is controlled by libuv's `UV_THREADPOOL_SIZE` environment variable,
which defaults to 4.

[https://nodejs.org/api/cli.html#uv\_threadpool\_sizesize][12]

For example, by default, a machine with 8 CPU cores will process
4 images in parallel and use up to 8 threads per image,
so there will be up to 32 concurrent threads.

### Parameters

*   `concurrency` **[number][11]?**

### Examples

```javascript
const threads = sharp.concurrency(); // 4
sharp.concurrency(2); // 2
sharp.concurrency(0); // 4
```

Returns **[number][11]** concurrency

## queue

An EventEmitter that emits a `change` event when a task is either:

*   queued, waiting for *libuv* to provide a worker thread
*   complete

### Examples

```javascript
sharp.queue.on('change', function(queueLength) {
  console.log('Queue contains ' + queueLength + ' task(s)');
});
```

## counters

Provides access to internal task counters.

*   queue is the number of tasks this module has queued waiting for *libuv* to provide a worker thread from its pool.
*   process is the number of resize tasks currently being processed.

### Examples

```javascript
const counters = sharp.counters(); // { queue: 2, process: 4 }
```

Returns **[Object][1]**

## simd

Get and set use of SIMD vector unit instructions.
Requires libvips to have been compiled with liborc support.

Improves the performance of `resize`, `blur` and `sharpen` operations
by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON.

### Parameters

*   `simd` **[boolean][10]**  (optional, default `true`)

### Examples

```javascript
const simd = sharp.simd();
// simd is `true` if the runtime use of liborc is currently enabled
```

```javascript
const simd = sharp.simd(false);
// prevent libvips from using liborc at runtime
```

Returns **[boolean][10]**

[1]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object

[2]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String

[3]: http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation

[4]: http://en.wikipedia.org/wiki/Bilinear_interpolation

[5]: http://en.wikipedia.org/wiki/Bicubic_interpolation

[6]: https://github.com/libvips/libvips/blob/master/libvips/resample/lbb.cpp#L100

[7]: http://en.wikipedia.org/wiki/Acutance

[8]: http://eprints.soton.ac.uk/268086/

[9]: https://github.com/libvips/libvips/blob/master/libvips/resample/vsqbs.cpp#L48

[10]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Boolean

[11]: https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number

[12]: https://nodejs.org/api/cli.html#uv_threadpool_sizesize


text:
@interface NSArray (PSKit)

- (id)firstObject;
- (id)randomObject;

@end


text:
0.7.3 - 2014-04-04
  - die loudly if there's a problem with the meteor process. Thanks @mitar

0.7.1 - 2014-01-02
  - fixed issue with smart.lock being written incorrectly

0.7.0 - 2013-12-20
  - fixed acceptance tests to work with latest meteor
  - use single package publication for package installs, should be much quicker
  - added a package search tool
  - log package installs to atmosphere

0.6.16 - 2013-11-3
  - smarter searching for package.js, thanks @childdude
  - added `mrt remove`

0.6.15 - 2013-10-20
  - don't write to .meteor/packages, thanks @mitar

0.6.14 - 2013-10-2
  - added --build-dev-bundle option

0.6.13 - 2013-09-13
  - deal with gitignore issue, thanks @philcockfield

0.6.12 - 2013-09-4
  - deal with .build directorys, thanks @mitar

0.6.11 - 2013-08-16
  - minor fix to postinstall script, thanks @veell

0.6.10 - 2013-08-10
  - fixed problem with homedir containing spaces.

0.6.9 - 2013-08-2
  - added `link-package` command

0.6.8 - 2013-07-22
  - added `create-package` command
  - updated prompt dependency

0.6.7 - 2013-07-4
  - switched back to port 443

0.6.4 - 2013-06-17
  - added --verbose argument.

0.6.3 - 2013-06-13
  - Default to port 80

0.6.2 - 2013-06-13
  - Commented out completion postinstall stuff.

0.6.1 - 2013-06-11
  - Error message if default meteor isn't installed and we try to use it.

0.6.0 - 2013-06-07
  - use Meteor's `packages/` directory

0.5.0 - 2013-03-18
  - upgrade to ddp version pre1 package.

0.4.8
  - fixed problem with local sources that form a dep diamond (#93)


text:
<?php
/**
 * @package wpml-core
 * @subpackage wpml-core
 */
interface TranslationProxy_Project_Interface {
	public function send_to_translation( $file, $title, $cms_id, $url, $source_language, $target_language, $word_count, $translator_id = 0, $note = '', $is_update = 0 );

	public function translator_contact_iframe_url( $translator_id );

	public function test_affiliation( $key, $id );

	public static function test_xmlrpc( $url );

	public static function generate_service_index( $service );

	public function create_batch_job($source_language, $target_languages);

	public function select_translator_iframe_url( $source_language, $target_language );

	public function send_to_translation_batch_mode( $file, $title, $cms_id, $url, $source_language, $target_language, $word_count, $translator_id = 0, $note = '', $is_update = 0 );

	public function commit_batch_job();

	public function update_job( $job_id, $url = null, $state = 'delivered' );

	public function canceled_jobs();

	public function create( $url, $name, $description, $blog_id = 1, $delivery = 'xmlrpc', $affiliate_id = '', $affiliate_key = '', $dummy = false );

	public function custom_text( $location, $locale = "en" );

	public function fetch_translation( $job_id );

	public function pending_jobs();

	public function get_batch_job_id();

	public function jobs();

	public function set_delivery_method( $method );
}


text:
require File.dirname(__FILE__) + '/../spec_helper.rb'

describe "def_matcher" do

  before do
    @obj = Object.new
  end

  it "defines method" do
    def_matcher :method_ do |given, matcher, args|
    end
    self.should respond_to(:method_)
  end

  it "object responds to matches" do
    def_matcher :method_ do |given, matcher, args|
    end
    method_.should respond_to(:matches?)
  end

  it "fail positive" do
    def_matcher :matcher do |given, matcher, args|
      false
    end
    lambda {1.should matcher}.should raise_error
  end

  it "pass positive" do
    def_matcher :matcher do |given, matcher, args|
      true
    end
    1.should matcher
  end

  it "fail negative" do
    def_matcher :matcher do |given, matcher, args|
      true
    end
    lambda {1.should_not matcher}.should raise_error
  end

  it "pass negative" do
    def_matcher :matcher do |given, matcher, args|
      false
    end
    1.should_not matcher
  end

  it "takes arguments" do
    def_matcher :matcher do |given, matcher, args|
      $args = args
      true
    end
    @obj.should matcher(1,2,3)
    $args.should eql([1,2,3])
  end

  it "received method" do
    def_matcher :matcher do |given, matcher, args|
      $msgs = matcher.msgs
      true
    end
    @obj.should matcher.method1
    $msgs[0].name.should eql(:method1)
  end

  it "received method takes args" do
    def_matcher :matcher do |given, matcher, args|
      $msgs = matcher.msgs
      true
    end
    @obj.should matcher.method1(1,2,3)
    $msgs[0].args.should eql([1,2,3])
  end

  it "received method takes block" do
    def_matcher :matcher do |given, matcher, args|
      $msgs = matcher.msgs
      true
    end
    @obj.should matcher.method1 { "Hello, World!"}
    $msgs[0].block.call.should eql("Hello, World!")
  end

  it "received method chained" do
    def_matcher :matcher do |given, matcher, args|
      $msgs = matcher.msgs
      true
    end
    @obj.should matcher.method1(1,2,3) { "Hello, World!"}.
      method2(4,5,6) { "Hello chained messages" }

    $msgs[0].name.should eql(:method1)
    $msgs[1].name.should eql(:method2)
    $msgs[0].args.should eql([1,2,3])
    $msgs[1].args.should eql([4,5,6])
    $msgs[0].block.call.should eql("Hello, World!")
    $msgs[1].block.call.should eql("Hello chained messages")
  end
end


text:
<!--//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright 2012 Freshplanet (http://freshplanet.com | opensource@freshplanet.com)
//
//  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.
//
//////////////////////////////////////////////////////////////////////////////////////-->

<extension xmlns="http://ns.adobe.com/air/extension/3.1">
  <id>com.freshplanet.ane.AirMultiPeerConnectivity</id>
  <versionNumber>1.0</versionNumber>
  <platforms>
    <platform name="iPhone-ARM">
            <applicationDeployment>
                <nativeLibrary>libAirMultiPeerConnectivity.a</nativeLibrary>
                <initializer>AirMultiPeerConnectivityExtInitializer</initializer>
                <finalizer>AirMultiPeerConnectivityExtFinalizer</finalizer>
            </applicationDeployment>
    </platform>

    <platform name="Android-ARM">
        <applicationDeployment/>
    </platform>

    <platform name="default">
        <applicationDeployment/>
    </platform>
  </platforms>
</extension>


text:
package org.math.plot.plotObjects;

import java.awt.*;

import org.math.plot.render.*;

/**
 * BSD License
 *
 * @author Yann RICHET
 */
public interface Plotable {
    // TODO two modes for drawing : plot() and niceplot()
    public void plot(AbstractDrawer draw);

    public void setVisible(boolean v);

    public boolean getVisible();

    public void setColor(Color c);

    public Color getColor();

}


text:
<!DOCTYPE html>
<title>ok</title>
<script>
window.onmessage = function(e) {
    var id = e.data.id;
    try {
        self.caches;
        window.parent.postMessage({id: id, result: 'allowed'}, '*');
    } catch (e) {
        window.parent.postMessage({id: id, result: 'denied', name: e.name, message: e.message}, '*');
    }
};
</script>


text:
// can converts all the `require` paths in the
// project from being local to being pointed
// at node_module names and vice versa.

/*global process*/
var fs = require('fs');
var getPackages = require('../lib/get-packages');
var which = process.argv.slice(2)[0];

var map = {
    remoteRegEx: /require\(\'amp-/g,
    localRegEx: /require\(\'\.\.\//g,
    remoteString: 'require(\'amp-',
    localString: 'require(\'../'
};

getPackages().forEach(function (pack) {
    if (which === 'remote') {
        pack.code = pack.code.replace(map.localRegEx, map.remoteString);
        pack.test = pack.test.replace(map.localRegEx, map.remoteString);
    } else if (which === 'local') {
        pack.code = pack.code.replace(map.remoteRegEx, map.localString);
        pack.test = pack.test.replace(map.remoteRegEx, map.localString);
    }
    var path = pack.folder + '/' + pack.fileName;

    fs.writeFileSync(path, pack.code);
    fs.writeFileSync(pack.folder + '/test.js', pack.test);
});


text:
import lejos.nxt.*;

/*
  Lab 5: Orienteering
  Author: Aleksi Sapon (260581670)
  Date: Wednesday October 15 2014
 */
public class Lab5 {
	public static void main(String[] args) throws Exception {
		// allows you to force program end by holding the escape button
		startShitHappensThread();
		// setup the odometer, navigation, display, and ultrasonic sensor
		Odometer odo = new Odometer();
		odo.start();
		Navigation navig = new Navigation(odo);
		navig.start();
		UltrasonicSensor us = new UltrasonicSensor(SensorPort.S2);
		// wait for a button press before starting
		Button.waitForAnyPress();
		// perform the orienteering
		Orienteer orienteer = new Orienteer(odo, navig, us, Orienteer.OrienteerType.STOCHASTIC);
		orienteer.doOrienteering();
		// Notify that orienteering succeeded (returned)
		Sound.playNote(Sound.FLUTE, 220, 250);
		// Wait for another press before moving to file position
		Button.waitForAnyPress();
		// Move to the top corner and face north
		orienteer.moveTo(3, 3, Orienteer.Direction.NORTH);
		// Wait for another press before exiting
		Button.waitForAnyPress();
		System.exit(0);
	}

	// Starts a thread which polls the state of the escape button every second
	// and exits the JVM if it's being held down
	private static void startShitHappensThread() {
		new Thread() {
			public void run() {
				while (true) {
					if (Button.ESCAPE.isDown()) {
						System.exit(0);
					}
					try {
						Thread.sleep(1000);
					} catch (InterruptedException ex) {
						// ignore
					}
				}
			}
		}.start();
	}
}


text:
""" Manage configuration file parsing """
import logging
import os
import sys
from ConfigParser import SafeConfigParser, NoOptionError, NoSectionError

if sys.platform in ['win32', 'cygwin']:
    import ntpath as ospath
else:
    import os.path as ospath

from cumulus_ds.exceptions import ConfigurationException

LOGGER = logging.getLogger(__name__)

# Initial configuration object
CONF = {
    'general': {},
    'environments': {},
    'stacks': {},
    'bundles': {}
}

# Options per section
# [(option, required)]
GENERAL_OPTIONS = [
    ('log-level', False),
    ('include', False)
]
STACK_OPTIONS = [
    ('template', True),
    ('disable-rollback', True),
    ('parameters', False),
    ('timeout-in-minutes', False),
    ('tags', False)
]
BUNDLE_OPTIONS = [
    ('paths', True),
    ('path-rewrites', False),
    ('pre-bundle-hook', False),
    ('post-bundle-hook', False),
    ('pre-built-bundle', False)
]
ENV_OPTIONS = [
    ('access-key-id', True),
    ('secret-access-key', True),
    ('bucket', False),
    ('region', True),
    ('stacks', True),
    ('bundles', True),
    ('version', False),
    ('pre-deploy-hook', False),
    ('post-deploy-hook', False),
    ('stack-name-prefix', False),
    ('stack-name-suffix', False)
]

def configure(args):
    """ Populate the objects

    :type args: Namespace
    :param args: Parsed arguments from argparse
    :type config_file: str or None
    :param config_file: Configuration file to read from
    """
    # Add custom configuration file path
    config_files = []
    if args.config:
        for config in args.config:
            config = ospath.expanduser(config)
            if ospath.exists(config):
                config_files.append(config)
                LOGGER.info('Added "{}" to config file list'.format(config))
                continue
            LOGGER.warning('Configuration file {} not found.'.format(config))
    else:
        if sys.platform in ['win32', 'cygwin']:
            config_files.append('C:\\cumulus.conf')
            config_files.append(ospath.expanduser('~\\.cumulus.conf'))
            config_files.append('{}\\cumulus.conf'.format(os.curdir))
        else:
            config_files.append('/etc/cumulus.conf')
            config_files.append(ospath.expanduser('~/.cumulus.conf'))
            config_files.append('{}/cumulus.conf'.format(os.curdir))

    # Get the include option from the general section
    config_files = __get_include_files(config_files) + config_files

    # Read config file
    conf_file_found = False
    for conf_file in config_files:
        if ospath.exists(conf_file):
            conf_file_found = True
            LOGGER.info('Reading configuration from {}'.format(conf_file))
    if not conf_file_found:
        raise ConfigurationException(
            'No configuration file found. Looked for {}'.format(
                ', '.join(config_files)))

    config = SafeConfigParser()
    config.read(config_files)

    try:
        _populate_general(args, config)
        _populate_environments(args, config)
        _populate_stacks(args, config)
        _populate_bundles(args, config)
    except ConfigurationException:
        raise

    return CONF

def __get_include_files(config_files):
    """ Read the 'include' option in the 'general' section

    This will return a list of include files

    :type config_files: str
    :param config_files: List of configuration files to include
    :returns: list -- List of include config files
    """
    config = SafeConfigParser()
    config.read(config_files)

    try:
        return [
            ospath.expanduser(c.strip())
            for c in config.get('general', 'include').split(',')
        ]
    except NoOptionError:
        return []
    except NoSectionError:
        return []
    return []

def _populate_environments(args, config):
    """ Populate the environments config object

    :type args: Namespace
    :param args: Parsed arguments from argparse
    :type config: ConfigParser.read
    :param config: Config parser config object
    """
    section = 'environment: {}'.format(args.environment)
    environment = args.environment
    if not section in config.sections():
        raise ConfigurationException(
            'No configuration found for environment {}'.format(environment))

    CONF['environments'][environment] = {}

    for option, required in ENV_OPTIONS:
        try:
            if option == 'bundles':
                bundles = []
                for item in config.get(section, option).split(','):
                    bundles.append(item.strip())
                CONF['environments'][environment][option] = bundles
            elif option == 'stacks':
                stacks = []
                for item in config.get(section, option).split(','):
                    item = item.strip()

                    # If --stacks has been used,
                    # do only add those stacks
                    if args.stacks and item not in args.stacks:
                        continue

                    stacks.append('{}-{}'.format(
                        args.environment, item))
                CONF['environments'][environment][option] = stacks
            elif option == 'version':
                if args.version:
                    CONF['environments'][environment][option] = args.version
                else:
                    CONF['environments'][environment][option] = config.get(
                        section, option)
            else:
                CONF['environments'][environment][option] = \
                    config.get(section, option)
        except NoOptionError:
            if required:
                raise ConfigurationException(
                    'Missing required option {}'.format(option))

def _populate_general(args, config):
    """ Populate the general config object

    :type args: Namespace
    :param args: Parsed arguments from argparse
    :type config: ConfigParser.read
    :param config: Config parser config object
    """
    section = 'general'
    if not section in config.sections():
        return None

    for option, required in GENERAL_OPTIONS:
        try:
            if option == 'log-level':
                log_level = config.get(section, option).upper()

                if log_level not in ['DEBUG', 'INFO', 'WARNING', 'ERROR']:
                    LOGGER.warning(
                        (
                            'Invalid log level "{}". Using default log level.'
                        ).format(log_level))
                    log_level = 'DEBUG'

                CONF['general'][option] = log_level
            elif option == 'include':
                # The include option is read earlier
                continue
            else:
                CONF['general'][option] = config.get(section, option)
        except NoOptionError:
            if required:
                raise ConfigurationException(
                    'Missing required option {}'.format(option))

def _populate_stacks(args, config):
    """ Populate the stacks config object

    :type args: Namespace
    :param args: Parsed arguments from argparse
    :type config: ConfigParser.read
    :param config: Config parser config object
    """
    for section in config.sections():
        if section.startswith('stack: '):
            stack = section.split(': ', 1)[1]

            # If --stacks has been used, do only add those stacks
            if args.stacks and stack not in args.stacks:
                continue

            stack = '{}-{}'.format(args.environment, stack)

            # Only add stacks that belong to the current environment
            if stack not in CONF['environments'][args.environment]['stacks']:
                continue

            # Prepend a stack name prefix
            if 'stack-name-prefix' in CONF['environments'][args.environment]:
                stack = '{}-{}'.format(
                    CONF['environments'][args.environment]['stack-name-prefix'],
                    stack)

            # Append a stack name suffix
            if 'stack-name-suffix' in CONF['environments'][args.environment]:
                stack = '{}-{}'.format(
                    stack,
                    CONF['environments'][args.environment]['stack-name-suffix'])

            CONF['stacks'][stack] = {}

            for option, required in STACK_OPTIONS:
                try:
                    if option == 'disable-rollback':
                        CONF['stacks'][stack][option] = config.getboolean(
                            section, option)
                    elif option == 'template':
                        CONF['stacks'][stack][option] = ospath.expanduser(
                            config.get(section, option))
                    elif option == 'parameters':
                        try:
                            raw_parameters = config.get(section, option)\
                                .split('\n')
                            if not raw_parameters[0]:
                                raw_parameters.pop(0)

                            parameters = []
                            for parameter in raw_parameters:
                                key, value = parameter.split('=', 1)
                                parameters.append((key.strip(), value.strip()))
                            CONF['stacks'][stack][option] = parameters
                        except ValueError:
                            raise ConfigurationException(
                                'Error parsing parameters for stack {}'.format(
                                    stack))
                    elif option == 'tags':
                        try:
                            raw_tags = config.get(section, option)\
                                .split('\n')
                            if not raw_tags[0]:
                                raw_tags.pop(0)

                            tags = {}
                            for tag in raw_tags:
                                key, value = tag.split('=', 1)
                                tags[key.strip()] = value.strip()
                            CONF['stacks'][stack][option] = tags
                        except ValueError:
                            raise ConfigurationException(
                                'Error parsing tags for stack {}'.format(
                                    stack))
                    elif option == 'timeout-in-minutes':
                        CONF['stacks'][stack][option] = config.getint(
                            section, option)
                    else:
                        CONF['stacks'][stack][option] = config.get(
                            section, option)
                except NoOptionError:
                    if required:
                        raise ConfigurationException(
                            'Missing required option {}'.format(
                                option))

                    if option == 'timeout-in-minutes':
                        CONF['stacks'][stack][option] = 0

            # Add command line parameters
            try:
                if args.parameters:
                    if not 'parameters' in CONF['stacks'][stack]:
                        CONF['stacks'][stack]['parameters'] = []

                    for raw_parameter in args.parameters.split(','):
                        stack_name, keyvalue = raw_parameter.split(':')
                        key, value = keyvalue.split('=', 1)
                        if stack_name == stack:
                            CONF['stacks'][stack]['parameters'].append(
                                (key, value))
            except ValueError:
                raise ConfigurationException('Error parsing --parameters')

def _populate_bundles(args, config):
    """ Populate the bundles config object

    :type args: Namespace
    :param args: Parsed arguments from argparse
    :type config: ConfigParser.read
    :param config: Config parser config object
    """
    for section in config.sections():
        if section.startswith('bundle: '):
            bundle = section.split(': ')[1]
            CONF['bundles'][bundle] = {}

            for option, required in BUNDLE_OPTIONS:
                try:
                    if option == 'paths':
                        lines = config.get(section, option).strip().split('\n')
                        paths = []
                        for path in lines:
                            paths.append(ospath.expanduser(path.strip()))
                        CONF['bundles'][bundle]['paths'] = paths
                    elif option == 'path-rewrites':
                        CONF['bundles'][bundle]['path-rewrites'] = []
                        lines = config.get(section, option).strip().split('\n')

                        for line in lines:
                            try:
                                target, destination = line.split('->', 1)
                            except ValueError:
                                raise ConfigurationException(
                                    'Invalid path-rewrites for '
                                    'bundle {}'.format(bundle))

                            # Clean the target and destination from initial /
                            if target[0] == '/':
                                target = target[1:]
                            if destination[0] == '/':
                                destination = destination[1:]

                            CONF['bundles'][bundle]['path-rewrites'].append({
                                'target': target.strip(),
                                'destination': destination.strip()
                            })

                    else:
                        CONF['bundles'][bundle][option] = config.get(
                            section, option)
                except NoOptionError:
                    if (option == 'paths' and
                            config.has_option(section, 'pre-built-bundle')):
                        continue

                    if required:
                        raise ConfigurationException(
                            'Missing required option {}'.format(option))


text:
package hardware::sensors::akcp::snmp::mode::sensors;

use base qw(centreon::plugins::templates::hardware);

use strict;
use warnings;

sub set_system {
    my ($self, %options) = @_;

    $self->{regexp_threshold_numeric_check_section_option} = '^(temperature|humidity)$';

    $self->{cb_hook2} = 'snmp_execute';

    $self->{thresholds} = {
        default1 => [
            ['noStatus', 'OK'],
            ['normal', 'OK'],
            ['highWarning', 'WARNING'],
            ['highCritical', 'CRITICAL'],
            ['lowWarning', 'WARNING'],
            ['lowCritical', 'CRITICAL'],
            ['sensorError', 'CRITICAL'],
            ['relayOn', 'OK'],
            ['relayOff', 'OK']
        ],
        default2 => [
            ['noStatus', 'OK'],
            ['normal', 'OK'],
            ['critical', 'CRITICAL'],
            ['sensorError', 'CRITICAL']
        ]
    };

    $self->{components_path} = 'hardware::sensors::akcp::snmp::mode::components';
    $self->{components_module} = ['temperature', 'humidity', 'switch', 'serial', 'water'];
}

sub snmp_execute {
    my ($self, %options) = @_;

    $self->{snmp} = $options{snmp};
    $self->{results} = $self->{snmp}->get_multiple_table(oids => $self->{request});
}

sub new {
    my ($class, %options) = @_;
    my $self = $class->SUPER::new(package => __PACKAGE__, %options, no_absent => 1);
    bless $self, $class;

    $options{options}->add_options(arguments => {});

    return $self;
}

1;

__END__

=head1 MODE

Check sensors.

=over 8

=item B<--component>

Which component to check (Default: '.*').
Can be: 'temperature', 'humidity', 'switch', 'serial', 'water'.

=item B<--filter>

Exclude some parts (comma seperated list) (Example: --filter=temperature --filter=humidity)
Can also exclude specific instance: --filter=fan,1

=item B<--no-component>

Return an error if no compenents are checked.
If total (with skipped) is 0. (Default: 'critical' returns).

=item B<--threshold-overload>

Set to overload default threshold values (syntax: section,[instance,]status,regexp)
It used before default thresholds (order stays).
Example: --threshold-overload='temperature,CRITICAL,^(?!(normal)$)'

=item B<--warning>

Set warning threshold for 'temperature', 'humidity' (syntax: type,regexp,threshold)
Example: --warning='temperature,.*,30'

=item B<--critical>

Set critical threshold for 'temperature', 'humidity' (syntax: type,regexp,threshold)
Example: --warning='temperature,.*,50'

=back

=cut


text:
_jarvis() {
  COMPREPLY=()
  local word="${COMP_WORDS[COMP_CWORD]}"

  if [ "$COMP_CWORD" -eq 1 ]; then
    COMPREPLY=( $(compgen -W "$(jarvis commands)" -- "$word") )
  else
    local command="${COMP_WORDS[1]}"
    local completions="$(jarvis completions "$command")"
    COMPREPLY=( $(compgen -W "$completions" -- "$word") )
  fi
}

complete -F _jarvis jarvis


text:
CREATE TABLE ${tableName} (
  id int
);

THIS IS NOT VALID SQL;
THIS MIGRATION SHOULD FAIL;


text:
/* eslint-disable */
/* eslint-disable prettier/prettier */
import React from 'react'

type ResourceProps = {
  id: string,
  name?: string,
  payload?: any,
}

type Option = {
  value: string,
  label: string,
  children?: React.ReactNode,
  hint: string,
}

export type CommonProps = {
  field: (props: any) => any,
  id?: string,
  resultToOptions?: (result: any) => {label: string, value: string | number}[],
  interceptOption?: (option: Option) => Option,
}

export type TaskPropsMixin = {
  taskName: string,
  id: string,
}

export type ResourcePropsMixin = {
  resource: (props: ResourceProps) => any,
}

export type Props = CommonProps & (TaskPropsMixin | ResourcePropsMixin)

export type ResourceOptionsField = (props: Props) => JSX.Element


text:
layout: default
---

## Who am I
...

## What is this
...

## Contact and stuff
...


text:
module SoupCMS
  module Common
    module Controller

      class BaseController

        def initialize(context)
          @context = context
        end

        attr_reader :context

        def execute
          raise 'Implement method execute'
        end

      end

    end
  end
end


text:
import os, datetime
import pstats
from cProfile import Profile

import generator

stats_dir = "profiling"
stats_filename = 'profile_%s.pstat' % datetime.datetime.now().isoformat()
stats_path = os.path.join(stats_dir, stats_filename)

if not os.path.exists(stats_dir):
    os.makedirs(stats_dir)

def profile(func, stats_path):
    profiler = Profile()
    try:
        profiler.runcall(func)
    except KeyboardInterrupt:
        profiler.dump_stats(stats_path)
        s = pstats.Stats(stats_path)
        s.strip_dirs().sort_stats("time").print_stats(30)
        raise

profile(generator.main, stats_path)


text:
package com.google.fleetengine.auth.sample;

import com.google.fleetengine.auth.sample.validation.DeliveryServiceStub;
import google.maps.fleetengine.delivery.v1.CreateDeliveryVehicleRequest;
import google.maps.fleetengine.delivery.v1.CreateTaskRequest;
import google.maps.fleetengine.delivery.v1.DeliveryServiceClient;
import google.maps.fleetengine.delivery.v1.DeliveryVehicle;
import google.maps.fleetengine.delivery.v1.GetDeliveryVehicleRequest;
import google.maps.fleetengine.delivery.v1.GetTaskRequest;
import google.maps.fleetengine.delivery.v1.SearchTasksRequest;
import google.maps.fleetengine.delivery.v1.Task;
import google.maps.fleetengine.delivery.v1.UpdateTaskRequest;

public class DeliveryServiceStubClient implements DeliveryServiceStub {

  private final DeliveryServiceClient client;

  /** Constructor. */
  public DeliveryServiceStubClient(DeliveryServiceClient client) {
    this.client = client;
  }

  @Override
  public Task createTask(CreateTaskRequest createTaskRequest) {
    return client.createTask(createTaskRequest);
  }

  @Override
  public Task getTask(GetTaskRequest getTaskRequest) {
    return client.getTask(getTaskRequest);
  }

  @Override
  public void searchTasks(SearchTasksRequest searchTripRequest) {
    client.searchTasks(searchTripRequest);
  }

  @Override
  public Task updateTask(UpdateTaskRequest updateTaskRequest) {
    return client.updateTask(updateTaskRequest);
  }

  @Override
  public DeliveryVehicle createDeliveryVehicle(
      CreateDeliveryVehicleRequest createDeliveryVehicleRequest) {
    return client.createDeliveryVehicle(createDeliveryVehicleRequest);
  }

  @Override
  public DeliveryVehicle getDeliveryVehicle(GetDeliveryVehicleRequest getDeliveryVehicleRequest) {
    return client.getDeliveryVehicle(getDeliveryVehicleRequest);
  }
}


text:
.. _ExpressionDistribution:

========================
Expression distributions
========================

Summary
=======

Expression distributions should be similar for samples from similar
tissues etc. Stark differences between samples from similar RNA
samples should raise concern.

Typically you will see a bimodal distribution of expression values
with a spike at ~0 log2TPM representing non- expressed or very lowly
expressed transcripts, and an approroximately normal distribution with
mean > 0 log2 TPM for expressed genes

Results
=======

.. report:: RnaseqqcReport.imagesTracker
   :render: gallery-plot
   :glob: sailfish.dir/plots.dir/expression_distribution_*.png

   Distibution of expression values per sample, coloured by factor levels

Aims
----

Comparing the distribution of expression levels between samples can
highlight anomalous samples that might need excluding from downstream analysis.

Inputs
------

A table of expression values in transcripts per million (TPM) for each
transcript and samples generated by Sailfish and stored as
"transcript_quantification" in the pipeline database.

Outputs
-------

A density plot showing the distribution of transcript expression
values (log2TPM). Each line represents a different sample.

How the results are generated
-----------------------------

1. Sample_ID, transcript_ID and TPM are extracted from the
   "transcript_quantification" table in the pipeline database and
   entered into a dataframe
2. TPM values are log transformed, log2(TPM_count + 0.1)
3. A density plot is produced using the geom_density function from
   ggplot2

What you should expect
----------------------

Typically you will see a bimodal distribution of expression values
with a spike at ~0 log2TPM representing non- expressed or very lowly
expressed transcripts, and an approroximately normal distribution with
mean > 0 log2 TPM for expressed genes

Examples
--------

  * Good example
  * Bad example
  * Links to other examples and the reasons that lie behind them

The good

.. report:: GoodExample.Tracker
   :render: myRenderer
   :transform: myTransform
   :options: myAesthetics

The bad

.. report:: BadExample.Tracker
   :render: myRenderer
   :transform: myTransform
   :options: myAesthetics

More bad examples `<http://myBadData.html >`

Commentary
  This will take the form of some active comments.  This will require the report to
  be published so that it is hosted on the CGAT server/ comments on the DISQUS server.


text:
package org.zstack.compute.vm;

import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.cloudbus.CloudBusCallBack;
import org.zstack.core.componentloader.PluginRegistry;
import org.zstack.core.workflow.Flow;
import org.zstack.core.workflow.FlowTrigger;
import org.zstack.header.host.HostConstant;
import org.zstack.header.message.MessageReply;
import org.zstack.header.vm.*;
import org.zstack.utils.Utils;
import org.zstack.utils.logging.CLogger;

import java.util.List;
import java.util.Map;
@Configurable(preConstruction = true, autowire = Autowire.BY_TYPE)
public class VmStartOnHypervisorFlow implements Flow {
    private static CLogger logger = Utils.getLogger(VmStartOnHypervisorFlow.class);

    @Autowired
    private CloudBus bus;
    @Autowired
    private PluginRegistry pluginRgty;

    private List<VmBeforeStartOnHypervisorExtensionPoint> exts;

    public VmStartOnHypervisorFlow() {
        exts = pluginRgty.getExtensionList(VmBeforeStartOnHypervisorExtensionPoint.class);
    }

    private void fireExtensions(VmInstanceSpec spec) {
        for (VmBeforeStartOnHypervisorExtensionPoint ext : exts) {
            ext.beforeStartVmOnHypervisor(spec);
        }
    }

    @Override
    public void run(final FlowTrigger chain, final Map data) {
        final VmInstanceSpec spec = (VmInstanceSpec) data.get(VmInstanceConstant.Params.VmInstanceSpec.toString());

        fireExtensions(spec);

        StartVmOnHypervisorMsg msg = new StartVmOnHypervisorMsg();
        msg.setVmSpec(spec);
        bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, spec.getDestHost().getUuid());
        bus.send(msg, new CloudBusCallBack(chain) {
            @Override
            public void run(MessageReply reply) {
                if (reply.isSuccess()) {
                    data.put(VmStartOnHypervisorFlow.class.getName(), true);
                    chain.next();
                } else {
                    chain.fail(reply.getError());
                }
            }
        });
    }

    @Override
    public void rollback(final FlowTrigger chain, Map data) {
        if (!(Boolean) data.get(VmStartOnHypervisorFlow.class.getName())) {
            chain.rollback();
            return;
        }

        final VmInstanceSpec spec = (VmInstanceSpec) data.get(VmInstanceConstant.Params.VmInstanceSpec.toString());
        StopVmOnHypervisorMsg msg = new StopVmOnHypervisorMsg();
        msg.setVmInventory(spec.getVmInventory());
        msg.getVmInventory().setHostUuid(spec.getDestHost().getUuid());
        bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, spec.getDestHost().getUuid());
        bus.send(msg, new CloudBusCallBack(chain) {
            @Override
            public void run(MessageReply reply) {
                if (!reply.isSuccess()) {
                    logger.warn(String.format("failed to stop vm[uuid:%s] on host[uuid:%s], %s", spec.getVmInventory().getUuid(), spec.getDestHost().getUuid(), reply.getError()));
                }
                chain.rollback();
            }
        });
    }
}


text:
package org.jboss.weld.injection;

import java.lang.reflect.Method;

import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.AnnotatedMethod;
import javax.enterprise.inject.spi.Bean;

import org.jboss.weld.annotated.enhanced.EnhancedAnnotatedCallable;
import org.jboss.weld.manager.BeanManagerImpl;

/**
 * Wraps a method whose parameters may be injected.
 *
 * @author Jozef Hartinger
 *
 * @param <T> the return type of the method
 * @param <X> the type of the class that declared the method
 */
public abstract class MethodInjectionPoint<T, X> extends AbstractCallableInjectionPoint<T, X, Method> {

    protected MethodInjectionPointType type;

    protected MethodInjectionPoint(MethodInjectionPointType methodInjectionPointType, EnhancedAnnotatedCallable<T, X, Method> callable, Bean<?> declaringBean, Class<?> declaringComponentClass,
             InjectionPointFactory factory, BeanManagerImpl manager) {
        super(callable, declaringBean, declaringComponentClass, MethodInjectionPointType.OBSERVER.equals(methodInjectionPointType) || MethodInjectionPointType.DISPOSER.equals(methodInjectionPointType), factory, manager);
        this.type = methodInjectionPointType;
    }

    /**
     * Invokes the method.
     *
     * @param receiver the instance to receive the method invocation or null if this is a static method
     * @param specialValue value to be passed to the special parameter (observer or disposer parameter) or null if the method is not an observer or disposer
     * @param manager the bean manager
     * @param ctx the creational context
     * @param exceptionTypeToThrow exception type to be used to wrap potential exceptions within
     * @return the value returned from the method
     */
    public abstract T invoke(Object receiver, Object specialValue, BeanManagerImpl manager, CreationalContext<?> ctx, Class<? extends RuntimeException> exceptionTypeToThrow);

    abstract T invoke(Object receiver, Object[] parameters, Class<? extends RuntimeException> exceptionTypeToThrow);

    @Override
    public abstract AnnotatedMethod<X> getAnnotated();

    public static enum MethodInjectionPointType {

        INITIALIZER, PRODUCER, DISPOSER, OBSERVER;

    }

}


text:
module.exports = function(server, req, res, next) {
  res.send(200, JSON.stringify({msg: 'test passed'}));
  res.end();
  return next();
};


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AppLink.core
{
    public static class APIFactory
    {
        static APIInstance instance = null;
        public static APIInstance GetInstance()
        {
            if (instance == null)
            {
                string url = ConfigurationManager.AppSettings.Get("applink.api");
                instance = new APIInstance(url);
            }
            return instance;
        }
    }
}


text:
/*	$NetBSD: linux_sem.h,v 1.4 1998/10/04 00:02:41 fvdl Exp $	*/

/*-
 * Copyright (c) 1995, 1998 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Frank van der Linden and Eric Haszlakiewicz.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the NetBSD
 *	Foundation, Inc. and its contributors.
 * 4. Neither the name of The NetBSD Foundation nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef _LINUX_SEM_H
#define _LINUX_SEM_H

#include <sys/sem.h>

/*
 * Operations for semctl(2), in addition to IPC_STAT and IPC_SET
 */
#define LINUX_GETPID  11
#define LINUX_GETVAL  12
#define LINUX_GETALL  13
#define LINUX_GETNCNT 14
#define LINUX_GETZCNT 15
#define LINUX_SETVAL  16
#define LINUX_SETALL  17

/*
 * Linux semid_ds structure. Internally used pointer fields are not
 * important to us and have been changed to void *
 */

struct linux_semid_ds {
	struct linux_ipc_perm	 l_sem_perm;
	linux_time_t		 l_sem_otime;
	linux_time_t		 l_sem_ctime;
	void 			*l_sem_base;
	void			*l_eventn;
	void			*l_eventz;
	void			*l_undo;
	ushort			 l_sem_nsems;
};

union linux_semun {
	int			 l_val;
	struct linux_semid_ds	*l_buf;
	ushort			*l_array;
	void			*l___buf;	/* For unsupported IPC_INFO */
	void			*l___pad;
};

/* Pretend the sys_semctl syscall is defined */
struct linux_sys_semctl_args {
	syscallarg(int) semid;
	syscallarg(int) semnum;
	syscallarg(int) cmd;
	syscallarg(union linux_semun) arg;
};

#ifdef SYSVSEM
#ifdef _KERNEL
__BEGIN_DECLS
int linux_sys_semctl __P((struct proc *, void *, register_t *));
void bsd_to_linux_semid_ds __P((struct semid_ds *,
    struct linux_semid_ds *));
void linux_to_bsd_semid_ds __P((struct linux_semid_ds *,
    struct semid_ds *));
__END_DECLS
#endif	/* !_KERNEL */
#endif	/* !SYSVSEM */

#endif /* !_LINUX_SEM_H */