text:
#include <CubicVR/Texture.h>
#include <CubicVR/Logger.h>
#include <algorithm>

IMPEXP std::vector<Texture *> Texture::textures;
IMPEXP std::map<std::string, cvrIndex, string_less> Texture::nameref;

IMPEXP TextureInit Texture::initializer = TextureInit();

#ifdef OPENGL_ES
	#define TEXTURE_MAX 32
#else
#ifdef ARCH_PSP
	#define TEXTURE_MAX 8
#else
	#define TEXTURE_MAX 32
#endif
#endif

IMPEXP int Texture::tex_use = -1;
IMPEXP int Texture::tex_lock = -1;

#ifdef ARCH_DC
#include <pcx/pcx.h>
/* Load a texture using pcx_load_texture and glKosTex2D */
void loadtxr(const char *fn, GLuint *txr) {
	kos_img_t img;
	pvr_ptr_t txaddr;

	if (pcx_to_img(fn, &img) < 0) {
		Logger::log(LOG_ERROR,"can't load %s\n", fn);
		return;
	}

	txaddr = pvr_mem_malloc(img.w * img.h * 2);
	pvr_txr_load_kimg(&img, txaddr, PVR_TXRLOAD_INVERT_Y);
	kos_img_free(&img, 0);

	glKosTex2D(GL_RGB565_TWID, img.w, img.h, txaddr);
}

#include <kos.h>
/* Sega Dreamcast PVR Textures Loading Function (c) Josh 'PH3NOM' Pearson 2011 */
/* Thanks to SmokesGrass for the PVR file header information. */

/* Various PVR texture assets */
struct pvr_tex {
       int texWidth;
       int texHeight;
       int txrFmt;
       int txrColor;
       pvr_ptr_t txrAddr;
};

/* Open the pvr texture and send it to VRAM, then bind it to the glKosTex2D context */
void loadpvr( const char * file_name, GLuint *txr ) {

  /* set up the files and buffers */
  FILE *pvr_file;
  char *pvr_header = NULL, *pvr_buffer = NULL;
  int header_len=0;
  struct pvr_tex pvr;
  pvr.texWidth = pvr.texHeight = pvr.txrFmt = pvr.txrColor = 0;

  /* open the pvr file */
  pvr_file = fopen( file_name ,"rb");
  if (pvr_file==NULL) {
	Logger::log("Error reading PVR file [%s]\n",file_name);
  }

  /* Read the possible 0x00100000 byte header */
  pvr_header = (char*)malloc( 32 );
  fread( pvr_header, 16, 2, pvr_file);

  /* obtain the PVR file size using fseek */
  fseek (pvr_file , 0 , SEEK_END);
  int pvrSize = ftell (pvr_file);

  /* Move to the begining of the PVR file */
  fseek (pvr_file , 0, SEEK_SET);

  /* Allocate RAM to contain the PVR file */
//  if( pvr_buffer ) free( pvr_buffer );
  pvr_buffer = (char*)memalign( 32, pvrSize );
  //pvr_buffer = (char*)malloc( pvrSize );
  if ( pvr_buffer == NULL ) Logger::log ("PVR memory alloc error\n");

  /* GBIX = 0x00100000 byte header */
  if( (char)pvr_header[0] == 'G' && (char)pvr_header[1] == 'B'
      && (char)pvr_header[2] == 'I' && (char)pvr_header[3] == 'X' )
    header_len = 32;
  /* PVRT = 0x00010000 byte header */
  else if ( (char)pvr_header[0] == 'P' && (char)pvr_header[1] == 'V'
            && (char)pvr_header[2] == 'R' )
    header_len = 16;

  /* Move past the header */
  fseek (pvr_file , header_len, SEEK_SET);

  /* Read the pvr texture data into RAM and close the file */
  fread (pvr_buffer,16,(pvrSize-header_len)/16,pvr_file);
  fclose( pvr_file );

  /* Get PVR Colorspace */
  unsigned int pvr_color = (unsigned int)pvr_header[header_len-8];
  switch( pvr_color ) {
          case 0x00: pvr.txrColor = PVR_TXRFMT_ARGB1555; break; //(bilevel translucent alpha 0,255)
          case 0x01: pvr.txrColor = PVR_TXRFMT_RGB565;   break; //(non translucent RGB565 )
          case 0x02: pvr.txrColor = PVR_TXRFMT_ARGB4444; break; //(translucent alpha 0-255)
          case 0x03: pvr.txrColor = PVR_TXRFMT_YUV422;   break; //(non translucent UYVY )
          case 0x04: pvr.txrColor = PVR_TXRFMT_BUMP;     break; //(special bump-mapping format)
          case 0x05: pvr.txrColor = PVR_TXRFMT_PAL4BPP;  break; //(4-bit palleted texture)
          case 0x06: pvr.txrColor = PVR_TXRFMT_PAL8BPP;  break; //(8-bit palleted texture)
          default:   break;
  }

  /* Get PVR Format. Mip-Maps and Palleted Textures not Currently handled */
  unsigned int pvr_fmt = (unsigned int)pvr_header[header_len-7];
  switch( pvr_fmt ) {
          case 0x01: pvr.txrFmt = PVR_TXRFMT_TWIDDLED;                           break;//SQUARE TWIDDLED
          //case 0x02: pvr.txrFmt = SQUARE TWIDDLED & MIPMAP
          case 0x03: pvr.txrFmt = PVR_TXRFMT_VQ_ENABLE | PVR_TXRFMT_TWIDDLED;    break;//VQ TWIDDLED
          //case 0x04: pvr.txrFmt = VQ & MIPMAP
          //case 0X05: pvr.txrFmt = 8-BIT CLUT TWIDDLED
          //case 0X06: pvr.txrFmt = 4-BIT CLUT TWIDDLED
          //case 0x07: pvr.txrFmt = 8-BIT DIRECT TWIDDLED
          //case 0X08: pvr.txrFmt = 4-BIT DIRECT TWIDDLED
          case 0x09: pvr.txrFmt = PVR_TXRFMT_NONTWIDDLED;                        break;//RECTANGLE
          case 0x0B: pvr.txrFmt = PVR_TXRFMT_STRIDE | PVR_TXRFMT_NONTWIDDLED;    break;//RECTANGULAR STRIDE
          case 0x0D: pvr.txrFmt = PVR_TXRFMT_TWIDDLED;                           break;//RECTANGULAR TWIDDLED
          case 0x10: pvr.txrFmt = PVR_TXRFMT_VQ_ENABLE | PVR_TXRFMT_NONTWIDDLED; break;//SMALL VQ
          //case 0x11: pvr.txrFmt = SMALL VQ & MIPMAP
          //case 0x12: pvr.txrFmt = SQUARE TWIDDLED & MIPMAP
          default:   pvr.txrFmt = PVR_TXRFMT_NONE; break;
  }

  /* Get PVR Texture Width */
  if( (unsigned int)pvr_header[header_len-4] == 0x08 && (unsigned int)pvr_header[header_len-3] == 0x00 )
        pvr.texWidth = 8;
  else if( (unsigned int)pvr_header[header_len-4] == 0x10 && (unsigned int)pvr_header[header_len-3] == 0x00 )
        pvr.texWidth = 16;
  else if( (unsigned int)pvr_header[header_len-4] == 0x20 && (unsigned int)pvr_header[header_len-3] == 0x00 )
        pvr.texWidth = 32;
  else if( (unsigned int)pvr_header[header_len-4] == 0x40 && (unsigned int)pvr_header[header_len-3] == 0x00 )
        pvr.texWidth = 64;
  else if( (unsigned int)pvr_header[header_len-4] == -0x80 && (unsigned int)pvr_header[header_len-3] == 0x00 )
        pvr.texWidth = 128;
  else if( (unsigned int)pvr_header[header_len-4] == 0x00 && (unsigned int)pvr_header[header_len-3] == 0x01 )
        pvr.texWidth = 256;
  else if( (unsigned int)pvr_header[header_len-4] == 0x00 && (unsigned int)pvr_header[header_len-3] == 0x02 )
        pvr.texWidth = 512;
  else if( (unsigned int)pvr_header[header_len-4] == 0x00 && (unsigned int)pvr_header[header_len-3] == 0x04 )
        pvr.texWidth = 1024;
   /* Get PVR Texture  Height */
  if( (unsigned int)pvr_header[header_len-2] == 0x08 && (unsigned int)pvr_header[header_len-1] == 0x00 )
        pvr.texHeight = 8;
  else if( (unsigned int)pvr_header[header_len-2] == 0x10 && (unsigned int)pvr_header[header_len-1] == 0x00 )
        pvr.texHeight = 16;
  else if( (unsigned int)pvr_header[header_len-2] == 0x20 && (unsigned int)pvr_header[header_len-1] == 0x00 )
        pvr.texHeight = 32;
  else if( (unsigned int)pvr_header[header_len-2] == 0x40 && (unsigned int)pvr_header[header_len-1] == 0x00 )
        pvr.texHeight = 64;
  else if( (unsigned int)pvr_header[header_len-2] == -0x80 && (unsigned int)pvr_header[header_len-1] == 0x00 )
        pvr.texHeight = 128;
  else if( (unsigned int)pvr_header[header_len-2] == 0x00 && (unsigned int)pvr_header[header_len-1] == 0x01 )
        pvr.texHeight = 256;
  else if( (unsigned int)pvr_header[header_len-2] == 0x00 && (unsigned int)pvr_header[header_len-1] == 0x02 )
        pvr.texHeight = 512;
  else if( (unsigned int)pvr_header[header_len-2] == 0x00 && (unsigned int)pvr_header[header_len-1] == 0x04 )
        pvr.texHeight = 1024;

  printf("PVR TXR Size: %i bytes, %ix%i pixels\n", pvrSize, pvr.texWidth, pvr.texHeight );

  /* Allocate VRAM */
//  if(pvr.txrAddr) pvr_mem_free(pvr.txrAddr);
  pvr.txrAddr = pvr_mem_malloc(pvrSize);

  /* Transfer the texture from RAM to VRAM */
  /* SH4->PVR DMA Transfer */
  if( header_len != 16 ) {
     if( pvrSize > 16384)
        dcache_flush_range((uint32)pvr_buffer, 16384);
     else
        dcache_flush_range((uint32)pvr_buffer, pvrSize);
     while (!pvr_dma_ready());
     pvr_dma_transfer( (void*)pvr_buffer, (uint32)pvr.txrAddr, pvrSize,
                       PVR_DMA_VRAM64, PVR_TXRLOAD_NONBLOCK, NULL, 0);
  }
  /* SH4->PVR SQ Transfer */
  else {
     pvr_txr_load( pvr_buffer, pvr.txrAddr, pvrSize);
  }

  /* Free the RAM */
  if( pvr_header ) free( pvr_header );
  if( pvr_buffer ) free( pvr_buffer );

  /* Bind the texture data to the glTex2D context */
  glKosTex2D( pvr.txrColor | pvr.txrFmt, pvr.texWidth, pvr.texHeight, pvr.txrAddr);

}
#endif

Texture::Texture()
{
#ifndef ARCH_PSP
	glTexId = 0;
#endif
#if !defined(ARCH_DC) && !defined(ARCH_PSP) && !defined(OPENGL_ES)
	render_srf = false;
#endif
};

Texture::~Texture()
{
#ifndef ARCH_PSP
	if (glTexId)
	{
		glDeleteTextures(1, (GLuint *)&glTexId);
	}
#endif
#if !defined(ARCH_DC) && !defined(ARCH_PSP) && !defined(OPENGL_ES)
	if (render_srf)
	{
		destroyRenderTarget();
	}
#endif
};

cvrIndex Texture::create()
{
	if (textures.empty())	/* generate the 'null' material */
	{
		 textures.push_back(new Texture());

		 nameref["null"] = 0;  // this crashes MSVC++, wtf?
	}
	textures.push_back(new Texture());
	return textures.size()-1;
};

cvrIndex Texture::create(std::string file_name)
{
	create();
	textures.back()->load(file_name);
	return textures.size()-1;
};

cvrIndex Texture::create(std::string file_name, std::string tex_name)
{
	cvrIndex i = create(file_name);
	nameref[tex_name] = i;
	return i;
};

cvrIndex Texture::bindTexture(Texture *tex_in, std::string tex_name)
{
	if (textures.empty())	/* generate the 'null' material */
	{
		textures.push_back(new Texture());

		nameref["null"] = 0;  // this crashes MSVC++, wtf?
	}

	textures.push_back(tex_in);

	cvrIndex i = textures.size()-1;

	if (tex_name != "")
	{
		nameref[tex_name] = i;
	}

	return i;
};

void Texture::destroy(cvrIndex texNum)
{
	if (textures[texNum]) delete textures[texNum];
	textures[texNum] = NULL;
};

cvrIndex Texture::getTextureId(std::string tex_name)
{
	if (nameref.find(tex_name)==nameref.end()) {
		return 0;
	}
	return nameref[tex_name];
};

void Texture::use(cvrIndex texNum)
{
	if (textures[texNum]) textures[texNum]->use();
};

void Texture::generate()
{
#ifndef ARCH_PSP
	if (!glTexId)	glGenTextures(1, &glTexId);
	glBindTexture(GL_TEXTURE_2D, glTexId);
#endif
}

bool Texture::load(std::string strFn)
{
	string path_str,file_str,file_base,file_ext;
	str_file_extract(strFn, path_str, file_str, file_base, file_ext);
	std::transform(file_ext.begin(), file_ext.end(), file_ext.begin(), ::tolower);

	setId(file_str);

	bool imgLoaded = false;

	//Create texture
	//		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img.width, img.height, 0, img.format, GL_UNSIGNED_BYTE, img.data);

	// Special loaders for platforms first..

#ifdef ARCH_PSP	// PSP only supports TGA at the moment...
	if (file_ext==string("tga")) {
			Logger::log("Loading Texture: [%s] as [PSP TGA]\n", file_str.c_str());

   			imgLoaded = psp_texture.LoadTGA((char *)strFn.c_str());

			if (imgLoaded) {
	   			psp_texture.Swizzle();
   				Logger::log("ok.\n");
				return true;
			} else {
   				Logger::log(LOG_ERROR,"failed!\n");
				return false;
   			}
	}
#else

	bool isJpgTexture = false;

	if(	file_ext==string("jpg") || file_ext==string("jpeg") ) {
		isJpgTexture = true;
	}

#ifdef ARCH_DC // DC supports PCX and PVR
	if (file_ext==string("pcx")) {

			Logger::log("Loading Texture: [%s] as [DC PCX]\n", file_str.c_str());
			generate();

			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_FILTER, GL_FILTER_BILINEAR);

			loadtxr(strFn.c_str(), &glTexId);
			return true;

	} else if (file_ext==string("pvr"))	{

			Logger::log("Loading Texture: [%s] as [DC PVR]\n", file_str.c_str());
			generate();

			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_FILTER, GL_FILTER_BILINEAR);

			loadpvr(strFn.c_str(), &glTexId);
			return true;
	}
#endif

	// Generic loader for remainder
	imgLoaded = img.Load((char *)strFn.c_str());

	if (imgLoaded) {
		generate();
		glEnable(GL_TEXTURE_2D);

#ifdef OPENGL_ES
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
#endif
#ifdef ARCH_DC
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
#endif

#if !defined(ARCH_DC) && !defined(OPENGL_ES) && !defined(ARCH_PSP)
		glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS, GL_TRUE);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
#endif

#ifndef ARCH_DC
		if(isJpgTexture) {
			glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
		}
#endif

		format = img.format;
		alpha = (format==GL_RGBA)?true:false;

		glTexImage2D(GL_TEXTURE_2D, 0, img.format, img.width, img.height, 0, img.format, GL_UNSIGNED_BYTE, img.data);

#ifndef ARCH_DC
		if(isJpgTexture) {
			glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
		}
#endif

		return true;
	}
	else
	{
		return false;
	}
#endif
}

#ifndef ARCH_PSP
#ifndef ARCH_DC
// todo: lightmap support for PSP and ES
bool Texture::loadMipmap(std::string strFn)
{
	bool isJpgTexture = false;

	string path_str,file_str,file_base,file_ext;
	str_file_extract(strFn, path_str, file_str, file_base, file_ext);
	std::transform(file_ext.begin(), file_ext.end(), file_ext.begin(), ::tolower);

	if (file_ext==string("jpg") || file_ext==string("jpeg")) {
		isJpgTexture = true;
	}

	//if a jpg texture, need to set UNPACK_ALIGNMENT to 1

	if (img.Load((char *)strFn.c_str()))
	{
		generate();
		glEnable(GL_TEXTURE_2D);

#ifdef OPENGL_ES
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

#else
		//Set Parameters
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
#endif

#ifndef ARCH_DC
		if(isJpgTexture)
			glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
#endif

#ifdef OPENGL_ES
		//Create texture
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, img.width, img.height, 0, img.format, GL_UNSIGNED_BYTE, img.data);
#else
		gluBuild2DMipmaps(	GL_TEXTURE_2D, GL_RGBA8, img.width, img.height,
						  img.format, GL_UNSIGNED_BYTE, img.data);
#endif

#ifndef ARCH_DC
		glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
#endif
		return true;
	}
	else
	{
		return false;
	}
	//	char c = toupper(strFn[strFn.length()-3]);
	//
	//	if (c == 'T')
	//	{
	//		load(strFn,FORMAT_TGA);
	//	}
	//	else
	//	if (c == 'P')
	//	{
	//		load(strFn,FORMAT_PNG);
	//	}
}

void Texture::loadLightMap(GLubyte *data, int width, int height)
{
		generate();
		//Create texture

#ifdef OPENGL_ES
	//Create texture
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
#else
	gluBuild2DMipmaps(	GL_TEXTURE_2D, GL_RGBA8, width, height,
					  GL_RGB, GL_UNSIGNED_BYTE, data);
#endif

		//Set Parameters
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
}

#endif
#endif

void Texture::load(std::string strFn,int imgType)
{
#ifndef ARCH_PSP
//	bool success = false;

	if (!glTexId)	glGenTextures(1, (GLuint *)&glTexId);
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D, glTexId);
#endif

	switch (imgType)
	{
//#ifdef ARCH_PSP
//		case FORMAT_TGA:
//
//			Logger::log("[Texture:%s] Loading....",strFn.c_str());
//
//			if( !psp_texture.LoadTGA((char *)strFn.c_str()) )
//			{
//				Logger::log("failed!\n");
//				//sceKernelExitGame();
//			}
//			else
//			{
//				Logger::log("ok.");
//			}
//			psp_texture.Swizzle();
//			Logger::log("\n");
//		break;
//		case FORMAT_PNG:
//			Logger::log("PNG Loading disabled, texture load failed.\n");
//		break;
//#else
//		case FORMAT_TGA:
//
//				TextureImage tex;
//
//				success = loadTGA(&tex, strFn.c_str());
//
//				if (success)
//				{
//#ifdef OPENGL_ES
//					glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
//					glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
//#else
//					glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS, GL_TRUE);
//					glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
//					glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
//#endif
//
//					glTexImage2D(GL_TEXTURE_2D, 0, tex.type, tex.width, tex.height, 0, tex.type, GL_UNSIGNED_BYTE, tex.imageData);
//
//					width = tex.width;
//					height = tex.height;
//					std::free(tex.imageData);
//				}
//				else
//				{
//					std::cout << "Texture::error, could not find " << strFn << std::endl;
//				}
//		break;
//
//
//		case FORMAT_PNG:
//			LodePNG::Decoder pngDecoder;
//			std::vector<unsigned char> buffer;
//
//			Logger::log("Loading png file %s..\n",strFn.c_str());
//
//			LodePNG::loadFile(buffer,strFn);
//
//			Logger::log("Calling PNG decoder..\n");
//			pngDecoder.decode(image, buffer);
//
//			Logger::log("Checking decoder state..\n");
//			if(pngDecoder.hasError())
//			{
//				Logger::log("[loadTextureFromPng] Error %d", pngDecoder.getError());
//				Logger::log(" while trying to load \'%s\'",strFn.c_str());
//				return;
//			}
//
//			int pngwidth = pngDecoder.getWidth();
//			int pngheight = pngDecoder.getHeight();
//
//			Logger::log("PNG Decoder Info [ width: %d, height: %d ]..\n",pngwidth,pngheight);
//
//			std::vector<unsigned char>::iterator iStart, iEnd, iTarget;
//
//			Logger::log("Swapping ranges");
//
//			for (int i = 0; i < pngheight / 2; i++)
//			{
//				iStart = image.begin() + (i *  (pngwidth * 4));
//				iEnd = iStart + (pngwidth * 4);
//				iTarget = image.begin() + (((pngheight - 1) - i) *  (pngwidth * 4));
//				swap_ranges(iStart, iEnd, iTarget);
//				Logger::log(".");
//			}
//
//			Logger::log("\n");
//
//			width=pngwidth;
//			height=pngheight;
//#ifdef OPENGL_ES
//			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
//			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
//
//#else
//			glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS, GL_TRUE);
//			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
//			glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
//#endif
//
//			glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, &image[0]);
//
//		break;
//#endif
	}
};

void Texture::use()
{
#ifdef ARCH_PSP
	sceGuEnable( GU_TEXTURE_2D );
	sceGuTexFilter( GU_LINEAR, GU_LINEAR );
	sceGuTexMode( GU_PSM_8888, 0, 0, psp_texture.Swizzled() );
 	sceGuTexImage( 0, psp_texture.Width(), psp_texture.Height(), psp_texture.Width(), psp_texture.Image() );
	sceGuTexFunc( GU_TFX_MODULATE, GU_TCC_RGB );
	sceGuTexScale( 1.0f, 1.0f );                    // No scaling
	sceGuTexOffset( 0.0f, 0.0f );
#else
	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D,glTexId);
#endif
};

void Texture::clear()
{
	std::vector<Texture *>::iterator i;

	for (i = Texture::textures.begin(); i != Texture::textures.end(); i++)
	{
		if ((*i)) delete (*i);
	}

	textures.clear();

	tex_use = 0;
	tex_lock = 0;
}

TextureInit::TextureInit() {
//#ifdef _WIN32
//	Logger::log(LOG_DEBUG,"Initializing GLEW..\n");
//	GLenum err = glewInit();
//#endif
};

TextureInit::~TextureInit()
{
	Texture::clear();
};

void Texture::setTexture(int tex_index)
{
#ifdef ARCH_PSP
#warning ARCH_PSP: need glActiveTexture replacement
#endif

#ifndef ARCH_PSP
#ifndef ARCH_DC
	glActiveTexture(GL_TEXTURE0+tex_index);
	glClientActiveTexture(GL_TEXTURE0+tex_index);
	glEnable(GL_TEXTURE_2D);
#endif
#endif

	if (tex_index > tex_use) tex_use = tex_index;
}

int Texture::nextTexture()
{
	tex_use++;

	setTexture(tex_use);

	return tex_use;
}

void Texture::clearAllTextures()
{
#ifndef ARCH_PSP
#ifndef ARCH_DC
	for (int i = tex_lock+1; i <= tex_use; i++)
	{
		glActiveTexture(GL_TEXTURE0+i);
		glDisable(GL_TEXTURE_2D);
		glClientActiveTexture(GL_TEXTURE0+i);
		glDisableClientState(GL_TEXTURE_COORD_ARRAY);
//		glMatrixMode(GL_TEXTURE);
//		glLoadIdentity();
#ifndef OPENGL_ES
		glDisable(GL_TEXTURE_GEN_S);
		glDisable(GL_TEXTURE_GEN_T);
		glDisable(GL_TEXTURE_GEN_R);
		glDisable(GL_TEXTURE_GEN_Q);
#endif
	}
#endif
#endif
	tex_use = tex_lock;
}

void Texture::lock()
{
	tex_lock = tex_use;
}

void Texture::clearLocks()
{
	tex_lock = -1;
}

#if !defined(ARCH_PSP) && !defined(OPENGL_ES) && !defined(ARCH_DC)
void Texture::destroyRenderTarget()
{
	phDestroySurface(&renderSurface);
	glTexId = 0;
}

bool Texture::createRenderTarget(unsigned int width, unsigned int height, GLboolean depth, int fp, GLboolean linear, GLboolean stencil, int attachments)
{
	render_srf = true;

	renderSurface.width = width;
	renderSurface.height = height;

	phCreateSurface(&renderSurface,depth,fp,linear,stencil,attachments);
	phCheckFBO();

	glTexId = renderSurface.texture;

	use();

//	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
//	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

	return true;
}

void Texture::bindRenderTarget()
{
	if (!render_srf) return;

    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, renderSurface.fbo);

	GLenum buffers[] = { GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT, GL_COLOR_ATTACHMENT2_EXT, GL_COLOR_ATTACHMENT3_EXT };
	glDrawBuffers(renderSurface.numAttachments, buffers);

}

void Texture::resetRenderTarget()
{
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
}
#endif


text:
<MainProgram>
  <Name>
    SHADER_caustics
  </Name>
  <ProgramFile>
    "programs/caustics.frag"
  </ProgramFile>
</MainProgram>

<Parameters>
  <Parameter>
    rgba color
    <Default>
      0 120 255 255
    </Default>
  </Parameter>

  <Parameter>
    float time
  </Parameter>
</Parameters>

redpajama_set_name: RedPajamaGithub


text:
from django.shortcuts import render
from wikipendium.wiki.models import Article
from django.utils import timezone
from collections import Counter
from django.utils.timezone import utc
from datetime import datetime
from wikipendium.cache.decorators import cache
import time

def index(request):
    acs = Article.get_all_newest_contents_all_languages()
    now = timezone.now()

    acs_updated_in_the_last_24_hours = list(filter(
        lambda ac: ac.updated > now - timezone.timedelta(hours=24), acs))

    acs_updated_in_the_last_week = list(filter(
        lambda ac: ac.updated > now - timezone.timedelta(days=7), acs))

    acs_updated_in_the_last_month = list(filter(
        lambda ac: ac.updated > now - timezone.timedelta(days=30), acs))

    user_stats = _generate_user_statistics_for_one_day(
        year=now.year, month=now.month, day=now.day
    )

    article_length_stats = _generate_article_length_statistics(acs)

    return render(request, 'stats/index.html', {
        'number_of_acs_updated_in_the_last_24_hours':
            len(acs_updated_in_the_last_24_hours),
        'number_of_acs_updated_in_the_last_week':
            len(acs_updated_in_the_last_week),
        'number_of_acs_updated_in_the_last_month':
            len(acs_updated_in_the_last_month),
        'users': user_stats,
        'compendium_length_stats': article_length_stats,
    })

one_hour_in_seconds = 60 * 60

@cache(key=lambda *args, **kwargs:
       'wikipendium.wiki.stats.views.'
       '_generate_article_length_statistics(t=%s)' %
       (int(time.time()) / one_hour_in_seconds))
def _generate_article_length_statistics(acs):
    return {
        'longest_compendiums': sorted([{
            'length': len(ac.content.split()),
            'compendium': ac
        } for ac in acs], key=lambda d: -d['length'])[:10],
    }

@cache
def _generate_user_statistics_for_one_day(year=None, month=None, day=None):
    now = datetime(year, month, day)
    now = now.replace(tzinfo=utc)
    users_24_hours = map(
        lambda a: a.edited_by,
        Article.get_all_contents(timezone.timedelta(hours=24), now)
        )
    users_week = map(
        lambda a: a.edited_by,
        Article.get_all_contents(timezone.timedelta(weeks=1), now)
        )
    users_month = map(
        lambda a: a.edited_by,
        Article.get_all_contents(timezone.timedelta(weeks=4), now)
        )

    user_most_contributions_24_hours = next(
        iter(Counter(users_24_hours).most_common(1)), [None, 0])
    user_most_contributions_week = next(
        iter(Counter(users_week).most_common(1)), [None, 0])
    user_most_contributions_month = next(
        iter(Counter(users_month).most_common(1)), [None, 0])

    return {
        'most_contrib_24_hours': {
            'user': user_most_contributions_24_hours[0],
            'contributions': user_most_contributions_24_hours[1],
        },
        'most_contrib_week': {
            'user': user_most_contributions_week[0],
            'contributions': user_most_contributions_week[1],
        },
        'most_contrib_month': {
            'user': user_most_contributions_month[0],
            'contributions': user_most_contributions_month[1],
        }
    }


text:
#include "VSido.hpp"
using namespace VSido;

#include <boost/test/unit_test.hpp>
#include <boost/test/unit_test.hpp>

#include "parser_dump.hpp"

BOOST_AUTO_TEST_CASE(test_case_FeedBackRequest_0)
{

	/// uart data
	list<unsigned char> expected =
	{
		0,
		53,
	};
	GEN_COMMON_SEND_UART('r');
	dumpTestData(expected);

	FeedBackRequest req;
	req.feedback(0,53);
	auto ack = req.execBK();
	dumpTestData(sendBuffer);
	BOOST_CHECK(expected == sendBuffer);

}


text:
"use strict";
define(['Ember', 'EmberData', 'cnc/cam/cam', 'cnc/util', 'cnc/cam/operations', 'cnc/cam/toolpath'],
    function (Ember, DS, cam, util, Operations, tp) {
        var attr = DS.attr;

        return DS.Model.extend({
            name: attr('string', {defaultValue: 'Unnamed Job'}),
            safetyZ: attr('number', {defaultValue: 5}),
            toolDiameter: attr('number', {defaultValue: 3}),
            userFeedrate: attr('number', {defaultValue: 100}),
            startPoint: attr('point', {defaultValue: new util.Point(0, 0, 10)}),
            jobSummary: DS.belongsTo('jobSummary', {inverse: 'job', async: true}),
            shapes: DS.hasMany('shape', {inverse: 'job', embedded: true}),
            operations: DS.hasMany('operation', {inverse: 'job', embedded: true}),
            offsetX: attr('number', {defaultValue: 0}),
            offsetY: attr('number', {defaultValue: 0}),
            startSpindle: attr('boolean', {defaultValue: true}),
            startSocket: attr('boolean', {defaultValue: true}),
            transitionTravels: [],
            operationsOrderProperty: ['index'],
            orderedOperations: Ember.computed.sort('operations', 'operationsOrderProperty'),
            enabledOperations: Ember.computed.filterBy('orderedOperations', 'enabled', true),
            computingOperations: Ember.computed.filterBy('operations', 'computing', true),
            computing: Ember.computed.notEmpty('computingOperations'),
            operationsTravelsBits: Ember.computed.mapBy('enabledOperations', 'travelBits'),
            toolRadius: function () {
                return parseFloat(this.get('toolDiameter')) / 2;
            }.property('toolDiameter'),
            didLoad: function () {
                //re-number operations, because some of them were serialized before the index field existed.
                var i = 0;
                this.get('orderedOperations').slice().forEach(function (op) {
                    op.set('index', i);
                    i++;
                });
            },
            deleteOperation: function (operation) {
                this.get('operations').removeObject(operation);
                operation.destroyRecord();
                this.save();
            },
            deleteShape: function (shape) {
                this.get('shapes').removeObject(shape);
                shape.destroyRecord();
                this.save();
            },
            safeStartPoint: function () {
                var startPoint = this.get('startPoint');
                return new util.Point(startPoint.x, startPoint.y, Math.max(startPoint.z, this.get('safetyZ')));
            }.property('startPoint', 'safetyZ'),
            prefixTravel: function () {
                var firstPath = this.get('enabledOperations.firstObject.toolpath.firstObject');
                var result = new tp.GeneralPolylineToolpath([this.get('safeStartPoint')]);
                result.speedTag = 'rapid';
                result.initialPoint = this.get('startPoint');
                if (firstPath) {
                    var firstPoint = firstPath.getStartPoint(0);
                    result.pushPointXYZ(firstPoint.x, firstPoint.y, this.get('safetyZ'));
                }
                return result;
            }.property('startPoint', 'safeStartPoint', 'safetyZ', 'enabledOperations.firstObject.toolpath.firstObject'),
            suffixTravel: function () {
                var lastPath = this.get('enabledOperations.lastObject.toolpath.lastObject');
                var result = new tp.GeneralPolylineToolpath();
                result.speedTag = 'rapid';
                if (lastPath) {
                    var lastPoint = lastPath.getStopPoint(0);
                    result.initialPoint = lastPoint;
                    result.pushPointXYZ(lastPoint.x, lastPoint.y, this.get('safetyZ'));
                    result.pushPoint(this.get('safeStartPoint'))
                }
                return result;
            }.property('safeStartPoint', 'safetyZ', 'enabledOperations.lastObject', 'enabledOperations.lastObject.toolpath'),
            transitionTravelsObeserved: function () {
                Ember.run.debounce(this, this.computeTransitionTravels, 100);
            }.observes('startPoint', 'operationsTravelsBits', 'prefixTravel', 'suffixTravel', 'enabledOperations.@each.assembledPath'),
            computeTransitionTravels: function () {
                this.set('transitionTravels', this.get('wholeProgram').getTravelBits());
            }.on('didLoad'),
            wholeProgram: function () {
                return tp.assembleWholeProgram(this.get('prefixTravel'), this.get('suffixTravel'), this.get('safetyZ'),
                    this.get('enabledOperations').filterBy('assembledPath.isEmpty', false).mapBy('assembledPath'));
            }.property('prefixTravel', 'suffixTravel', 'enabledOperations.@each.assembledPath', 'safetyZ'),
            createOperation: function (params) {
                var lastOp = this.get('orderedOperations.lastObject');
                if (lastOp) {
                    if (params == null) {
                        params = lastOp.toJSON();
                        params.job = this;
                        params.outline = lastOp.get('outline');
                        params.index = lastOp.get('index') + 1;
                    }
                    if (params.index == null)
                        params.index = lastOp.get('index') + 1;
                }
                var operation = this.store.createRecord('operation', params);
                operation.set('job', this);
                this.get('operations').pushObject(operation);
                return operation;
            },
            createShape: function (def, name, params) {
                var shape = this.store.createRecord('shape', $.extend({definition: def, name: name}, params));
                this.get('shapes').pushObject(shape);
                return shape;
            },
            saveAll: function () {
                var summaryPromise = this.get('jobSummary');
                var _this = this;
                summaryPromise.then(function (summary) {
                    if (summary == null) {
                        summary = _this.store.createRecord('jobSummary', {job: _this, name: _this.get('name')});
                        _this.set('jobSummary', summary);
                    } else
                        summary.set('name', _this.get('name'));
                    return Ember.RSVP.all([summary.save(), _this.save()]);
                });
            },
            feedrate: Ember.computed.alias('userFeedrate'),
            canSendProgram: function () {
                var operations = this.get('operations');
                if (operations.length == 0)
                    return false;
                var oneIsComputing = false;
                var oneIsEnabled = false;
                operations.forEach(function (op) {
                    if (op.get('enabled')) {
                        oneIsEnabled = true;
                        if (op.get('computing'))
                            oneIsComputing = true;
                    }
                });
                return oneIsEnabled && !oneIsComputing;
            }.property('operations', 'operations.@each.enabled', 'operations.@each.computing'),
            computeDuration: function () {
                if (!this.get('wholeProgram').path.length)
                    return;
                this.set('duration', 'computing...');
                if (this.get('durationWorker'))
                    this.get('durationWorker').terminate();
                var worker = new Worker(require.toUrl('worker.js'));
                this.set('durationWorker', worker);
                var _this = this;
                worker.onmessage = Ember.run.bind(this, function (event) {
                    _this.set('duration', event.data.duration);
                    worker.terminate();
                    _this.set('durationWorker', null);
                });
                worker.postMessage({
                    operation: 'computeDuration',
                    path: this.get('wholeProgram').path
                });
            },
            observeOperationDuration: function () {
                this.set('duration', null);
                if (this.get('enabledOperations').filterBy('computing', true).length == 0)
                    Ember.run.debounce(this, 'computeDuration', 100);
            }.observes('wholeProgram', 'operations.@each.actualFeedrate', 'operations.@each.computing'),
            computeCompactToolPath: function () {
                console.log('computeCompactToolPath');
                var operations = this.get('enabledOperations');
                var safetyZ = this.get('safetyZ');
                var travelBits = [];
                var pathFragments = [];
                var endPoint = null;
                operations.forEach(function (operation) {
                    pathFragments.pushObjects(operation.get('toolpath'));
                });
                var startPoint = this.get('startPoint');
                console.timeEnd('preparation');
                var position = startPoint;
                var safeStartPoint = new util.Point(startPoint.x, startPoint.y, Math.max(startPoint.z, safetyZ));

                function segment(p1, p2) {
                    return new Float32Array([p1.x, p1.y, p1.z, p2.x, p2.y, p2.z]);
                }

                travelBits.push({speedTag: 'rapid', path: segment(startPoint, safeStartPoint)});
                if (pathFragments.length) {
                    position = pathFragments[0].getStartPoint();
                    travelBits.push({speedTag: 'rapid', path: segment(safeStartPoint, position)});
                    for (var i = 0; i < pathFragments.length; i++) {
                        var fragment = pathFragments[i];
                        console.log('feedrate', fragment.feedrate);
                        travelBits.push({
                            operation: fragment.operation,
                            speedTag: 'normal',
                            feedRate: fragment.feedrate,
                            path: fragment.asCompactToolpath()
                        });
                        endPoint = fragment.getStopPoint();
                        position = new util.Point(endPoint.x, endPoint.y, safetyZ);
                        travelBits.push({speedTag: 'rapid', path: segment(endPoint, position)});
                        if (i + 1 < pathFragments.length) {
                            var destinationPoint = pathFragments[i + 1].getStartPoint();
                            var newPos = new util.Point(destinationPoint.x, destinationPoint.y, safetyZ);
                            travelBits.push({speedTag: 'rapid', path: segment(position, newPos)});
                            position = newPos;
                        }
                    }
                    travelBits.push({speedTag: 'rapid', path: segment(position, safeStartPoint)});
                }
                return travelBits;
            }
        });
    });


text:
using System;
using System.Collections.Generic;

namespace Thor.Generator.Types
{
    internal class ParameterTypeInfo<T>
        : IParameterTypeInfo
    {
        private readonly List<string> _names;

        public ParameterTypeInfo(int size)
        {
            _names = new List<string>
            {
                typeof(T).Name,
                typeof(T).FullName
            };

            Name = typeof(T).Name;
            Size = size.ToString();
            Operator = "&";
            IsString = false;
        }

        public ParameterTypeInfo(string alias, int size)
            : this(alias, size.ToString())
        {
        }

        public ParameterTypeInfo(string alias, string size)
        {
            if (alias == null)
            {
                throw new ArgumentNullException(nameof(alias));
            }

            if (size == null)
            {
                throw new ArgumentNullException(nameof(size));
            }

            _names = new List<string>
            {
                alias,
                typeof(T).Name,
                typeof(T).FullName
            };

            Name = alias;
            Size = size;
            Operator = "&";
            IsString = false;
        }

        public string Name { get; }

        public string Size { get; }

        public bool IsString { get; internal set; }

        public string Operator { get; internal set; }

        public IEnumerable<string> GetNames()
        {
            return _names;
        }
    }
}


text:
package org.apache.commons.jelly.tags.bean;

import org.apache.commons.jelly.JellyException;
import org.apache.commons.jelly.Tag;
import org.apache.commons.jelly.TagLibrary;
import org.apache.commons.jelly.impl.TagFactory;
import org.apache.commons.jelly.impl.TagScript;

import org.xml.sax.Attributes;

/**
 * A normal tag library which will use a BeanTag to create beans but this tag
 * library does not derive from BeanTagLibrary and so does not have a <
 * beandef> tag
 *
 * @author James Strachan
 * @version $Revision: 155420 $
 */
public class MyTagLibrary extends TagLibrary {

    public MyTagLibrary() {
    }

    // TagLibrary interface
    //-------------------------------------------------------------------------
    public TagScript createTagScript(String name, Attributes attributes) throws JellyException {

        TagFactory factory = new TagFactory() {
            public Tag createTag(String name, Attributes attributes) throws JellyException {
                return createBeanTag(name, attributes);
            }
        };
        return new TagScript( factory );
    }

    // Implementation methods
    //-------------------------------------------------------------------------

    /**
     * Factory method to create a Tag for the given tag and attributes. If this
     * tag matches a root bean, then a BeanTag will be created, otherwise a
     * BeanPropertyTag is created to make a nested property.
     */
    protected Tag createBeanTag(String name, Attributes attributes) throws JellyException {
        // is the name bound to a specific class
        Class beanType = getBeanType(name, attributes);
        if (beanType != null) {
            return new BeanTag(beanType, name);
        }

        // its a property tag
        return new BeanPropertyTag(name);
    }

    /**
     * Return the bean class that we should use for the given element name
     *
     * @param name is the XML element name
     * @param attributes the XML attributes
     * @return Class the bean class to use for this element or null if the tag
     * is a nested property
     */
    protected Class getBeanType(String name, Attributes attributes) {
        if (name.equals( "customer")) {
            return Customer.class;
        }
        return null;
    }
}


text:
class RailsInfo::RoutesPresenter < ::RailsInfo::Presenter
  def accordion
    routes = request.env['action_dispatch.routes'].routes.map do |route|
      {
        source: (route.verb.respond_to?(:source) ? route.verb.source : route.verb).gsub(/[$^]/, ''),
        spec: route.path.respond_to?(:spec) ? route.path.spec.to_s : route.path,
        name: route.name,
        requirements: route.requirements.inspect
      }
    end

    namespaced_routes = {}

    routes.each do |route|
      namespace = '/'

      unless route[:spec] == namespace
        spec = route[:spec].split('/')
        spec.shift
        namespace = spec.shift
      end

      namespaced_routes[namespace] ||= []
      namespaced_routes[namespace] << route
    end

    content_tag :div, class: 'accordions' do
      html = ''

      namespaced_routes.each do |namespace, routes|
        html += content_tag(
          :h3, raw("        #{namespace}")
        )
        table = render partial: 'rails_info/routes/table', locals: { routes: routes }
        html += content_tag :div, raw(table), style: "max-height:300px; overflow: auto"
      end

      raw html
    end
  end
end


text:
/**
 * @file
 * Sanderson Flipped panel layout
 **/

.sanderson-flipped-container {
  margin-bottom: 1em;
}

.sanderson-flipped-secondary-column-content-region {
  min-height: 1px;
  width: 51.064%;
  float: left;
}

  .sanderson-flipped-secondary-column2 {
    width: 48.936%;
  }

  .sanderson-flipped-secondary-column-content-region-inner {
    margin-right: 20px;
  }

.sanderson-flipped-column-content-region {
  min-height: 1px;
  width: 34.043%;
  float: left;
}

  .sanderson-flipped-column-content-region-inner {
    margin-right: 20px;
  }

  .sanderson-flipped-column3 {
    width: 31.915%;
  }

    .sanderson-flipped-secondary-column2-inner,
    .sanderson-flipped-column3-inner {
      margin-right: 0;
    }

/* iPhone [portrait + landscape] */
@media only screen and (max-width: 480px) {
  .sanderson-flipped-secondary-column-content-region,
  .sanderson-flipped-secondary-column2,
  .sanderson-flipped-column-content-region,
  .sanderson-flipped-column3 {
    width: 100%;
    float: none;
  }

  .sanderson-flipped-secondary-column-content-region-inner,
  .sanderson-flipped-column-content-region-inner {
    margin-right: 0;
  }
}


text:
table.contact-list tr:nth-child(even) {background: #CCC}
table.contact-list tr:nth-child(odd) {background: #FFF}


text:
<!DOCTYPE html>

        <meta charset="utf-8" />

        <link rel="stylesheet" type="text/css" href="{Saivi::RES}/css/189/css/snower.css" media="all" />

        <link rel="stylesheet" type="text/css" href="{Saivi::RES}/css/189/css/common.css" media="all" />

        <link rel="stylesheet" type="text/css" href="{Saivi::RES}/css/189/css/reset.css" media="all" />

        <link rel="stylesheet" type="text/css" href="{Saivi::RES}/css/189/css/home-64.css" media="all" />

        <title>{Saivi:$tpl.wxname}</title>

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

        <meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport"/>

        <meta content="application/xhtml+xml;charset=UTF-8" http-equiv="Content-Type"/>

        <meta content="no-cache,must-revalidate" http-equiv="Cache-Control"/>

        <meta content="no-cache" http-equiv="pragma"/>

        <meta content="telephone=no, address=no" name="format-detection"/>

        <meta content="width=device-width, initial-scale=1.0" name="viewport"/>

        <meta name="apple-mobile-web-app-capable" content="yes" />

        <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" /><link type="text/css" rel="stylesheet" href="{Saivi::$staticFilePath}/css/touch_index.css">

$_GET['token'],'wecha_id'=>$_GET['wecha_id']))}">所有商品

$_GET['token'],'wecha_id'=>$_GET['wecha_id']))}">购物车

$_GET['token'],'wecha_id'=>$_GET['wecha_id']))}">查物流

$_GET['token'],'wecha_id'=>$_GET['wecha_id']))}">用户中心

<audio src="{Saivi:$homebgmp3}" loop id="audio"></audio>

<volist name="cats" id="hostlist">

						<?php $xx=count($info); ?>

				        <php>$ii++;</php>

<a href="<if condition="$hostlist['url'] eq ''">{Saivi::U('Store/products',array('token' => $_GET['token'], 'catid' => $hostlist['id'], 'wecha_id' => $wecha_id))}<else/>{Saivi:$hostlist.url|htmlspecialchars_decode}</if>">{Saivi:$hostlist.name}

<php>if ($ii%9==0 & $ii!=$xx){

                        	echo "

";

                            }</php>

					</volist>

</volist>

<if condition="$iscopyright eq 1">{Saivi:$homeInfo.copyright}<else/>{Saivi:$siteCopyright}</if>

<if condition="$kefu['sc'] eq '1'"></if>


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

    <service name="IdentityProviderAdminService" scope="transportsession">
        <transports>
            <transport>https</transport>
        </transports>
        <schema schemaNamespace="http://org.apache.axis2/xsd" elementFormDefaultQualified="true"/>
        <description>
            To administer Identity Provider related functionality.
        </description>
        <parameter name="ServiceClass">org.wso2.carbon.identity.provider.IdentityProviderService</parameter>
        <parameter name="AuthorizationAction" locked="true">/permission/admin/login</parameter>
        <parameter name="adminService" locked="true">true</parameter>
    </service>

    <service name="OpenIDProviderService" scope="transportsession">
        <transports>
            <transport>https</transport>
        </transports>
        <schema schemaNamespace="http://org.apache.axis2/xsd" elementFormDefaultQualified="true"/>
        <description>
            To administer Identity Provider related functionality.
        </description>
        <parameter name="ServiceClass">org.wso2.carbon.identity.provider.OpenIDProviderService</parameter>
        <parameter name="DoAuthentication" locked="true">false</parameter>
    </service>

    <service name="XMPPConfigurationService" scope="transportsession">
        <transports>
            <transport>https</transport>
        </transports>
        <schema schemaNamespace="http://org.apache.axis2/xsd" elementFormDefaultQualified="true"/>
        <description>
            To Configure the XMPP Settings for multi-factor authentication based on XMPP.
        </description>
        <parameter name="ServiceClass">org.wso2.carbon.identity.provider.XMPPConfigurationService</parameter>
        <parameter name="AuthorizationAction" locked="true">/permission/admin/login</parameter>
        <parameter name="adminService" locked="true">true</parameter>
    </service>

    <parameter name="hiddenService" locked="true">true</parameter>

</serviceGroup>


text:
if [ $# -eq 0 ]
then
	echo "First argument must be the service name"
	exit 1
fi

eval $(docker-machine env --swarm swarm-m)

master=$(docker-machine ip swarm-m)
if [ $# -eq 1 ]
then
	docker run -d -P -e SERVICE_NAME=$1 --net=cluster --name $1 -v /var/log/micro:/var/log/micro afein/service
	exit 0
fi
docker run -d -P -e SERVICE_NAME=$1 --net=cluster -e constraint:node==$2 --name $1 -v /var/log/micro:/var/log/micro afein/service


text:
package org.elasticsearch.gradle.internal.util.ports;

import java.io.IOException;
import java.net.DatagramSocket;
import java.net.ServerSocket;

public class DefaultPortDetector implements PortDetector {
    /**
     * Checks to see if a specific port is available.
     *
     * @param port the port to check for availability
     * @return true if the port is available, false otherwise
     */
    public boolean isAvailable(int port) {
        try {
            ServerSocket ss = new ServerSocket(port);
            try {
                ss.setReuseAddress(true);
            } finally {
                ss.close();
            }

            DatagramSocket ds = new DatagramSocket(port);
            try {
                ds.setReuseAddress(true);
            } finally {
                ds.close();
            }

            return true;
        } catch (IOException e) {
            return false;
        }

    }

}


text:
export CLOUDSDK_CORE_DISABLE_PROMPTS=1

if [ -z "$GCLOUD_KEY" ]; then
  >&2 echo "Missing GCLOUD_KEY"
  exit 1
fi

# remove whatever version was installed with a package manager
if [ -d "/usr/lib/google-cloud-sdk" ]; then
  sudo rm -rf "/usr/lib/google-cloud-sdk"
fi

if [ ! -d "$HOME/google-cloud-sdk/bin" ]; then
  rm -rf "$HOME/google-cloud-sdk"
  curl https://sdk.cloud.google.com | bash > /dev/null
fi

source "$HOME/google-cloud-sdk/path.bash.inc"
gcloud version
gcloud --quiet components update

# authenticate
echo $GCLOUD_KEY | base64 --decode > gcloud.json
gcloud auth activate-service-account $GCLOUD_EMAIL --key-file gcloud.json
ssh-keygen -f ~/.ssh/google_compute_engine -N ""

# install kubectl and configure docker
gcloud --quiet components update kubectl
gcloud auth configure-docker


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Hunters - SumIFIT</title>

    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">

    <link rel="stylesheet" href="../bootstrap/css/bootstrap.min.css">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

    <link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
    <link rel="stylesheet" href="../dist/css/skins/_all-skins.min.css">

    <link rel="stylesheet" href="../plugins/datepicker/datepicker3.css">

    <link rel="stylesheet" href="../plugins/daterangepicker/daterangepicker-bs3.css">

    <link rel="stylesheet" href="../plugins/iCheck/all.css">

    <link rel="stylesheet" href="../plugins/colorpicker/bootstrap-colorpicker.min.css">

    <link rel="stylesheet" href="../plugins/timepicker/bootstrap-timepicker.min.css">

    <link rel="stylesheet" href="../plugins/select2/select2.min.css">

    <link rel="stylesheet" href="../dist/css/AdminLTE.min.css">

	<link href="../bootstrap/css/bootstrap-switch.css" rel="stylesheet">

    <link rel="stylesheet" href="../plugins/datatables/dataTables.bootstrap.css">

          HSMF

          HuntersSUMIFIT

            Toggle navigation - Rodrigo

                  Rodrigo Gomes

                      Rodrigo Gomes - HeadHunter
                      Menbro desde Dezembro 2015

                      Perfil

                      Sair

MENU

				 Home

 Dashboard

 Perfil

 Cadastro de Usuários

                 Agenda
                3

				 Vagas

 Publicar Vagas

 Painel de Vagas

 Pesquisa de Candidatos

				 Assinaturas

 Assinatura Empresarial

 Assinatura Individual

 Detalhamento da Assinatura

                 Caixa de Entrada
                4

                 Avaliação Técnica

 Cadastro

                   Avaliações

 Avaliações Cadastradas

 Registro de Avaliações

            Perfil do Candidato

 Home

Pesquisa de Candidatos

Perfil do Candidato

Rodrigo Gomes

Analista de Business Intelligence

                      Deseja receber propostas de curto prazo?

					   <input id="switch-size" type="checkbox" disabled name="projeto_curto_prazo" data-on-text="Sim" data-off-text="Não" data-size="mini">

                      Aceita propostas para trabalhos Home Office?

					   <input id="switch-size" type="checkbox" disabled name="home_office" checked data-on-text="Sim" data-off-text="Não" data-size="mini">

                      Aceita propostas de horários alternativos?

					   <input id="switch-size" type="checkbox" disabled name="horarios_alternativos" data-on-text="Sim" data-off-text="Não" data-size="mini">

                      Disponível para viagens?

					   <input id="switch-size" type="checkbox" disabled name="disponivel_viagens" checked data-on-text="Sim" data-off-text="Não" data-size="mini">

                      Você é fumante?

					   <input id="switch-size" type="checkbox" disabled name="fumante" data-on-text="Sim" data-off-text="Não" data-size="mini">

                      É PCD?

					   <input id="switch-size" type="checkbox" disabled name="pcd" data-on-text="Sim" data-off-text="Não" data-size="mini">

Sobre Rodrigo

                    Formação Acadêmica

                    Bacharel em Ciências da Computação pelo Centro Universitário Nove de Julho - Conclusão em 12/2003

                   Localização Atual

São Paulo, Alphaville

                   Habilidades

                    SSAS
                    SSRS
                    SSIS
                    SQL Server
                    Oracle
					Power Center

                   Resumo Profissional

 Análise e Desenvolvimento de Projetos para empresas de grande porte e multinacionais,
				     desenvolvendo soluções com alta tecnologia e diferenciadas.
					 Analista Desenvolvedor, com conhecimentos em diversas tecnologias, tais como, Visual Basic 6
					 ,Crystal Reports 8.5, SQL SERVER (2000/2005/2008R2), Oracle, Visual Studio .NET 2008/2010
					 ,VB.NET, C#, Web Services, SSAS 2008, SSIS 2008, SSRS 2008, Qlikview 10,
					 Plataforma Informatica (Power Center 9 , B2B Data Transformation).

Dados Pessoais

Formação_Acadêmica

Experiência Profissional

Certificações

Cursos Extra Curriculares

Perfil Online

Outras Informações

Dados Pessoais

Identificação

 Nome: Rodrigo dos Santos Gomes

 RG: 33.236.748

 Dígito: 5

 Data de Expedição: 06/09/1997

 CPF: 285.476.985-41

 Data de Nasicmento: 12/11/1981

 Sexo: Masculino

 Nacilonalidade: Brasileira

 Estado Civil: Casado

Filiação

 Mãe: Jovelina Maria Santos

 Pai: Aluizio Gonçalves Gomes

Contato

 Telefone: (011) 4875-5525

 Celular: (011) 98758-2541

 E-mail: ro_drigosg@hotmail.com

 WebSite: -

Endereço

 CEP: 03560-150

 Endereço: Rua Maestro Jorge Galati

 Número: 256

 Complemento: Próximo à avenida Itaquera

 Bairro: Vila Nhocuné

 Cidade: São Paulo

 Estado: SP

Histórico Acadêmico

 Instituição: Centro Universitário Nove de Julho

 Curso: Ciências da Computação

 Grau de Escolaridade: Bacharel - Completo

 Data de Conclusão: 01/12/2003

												Mais informações

Descrição

-

Histórico Profissional

 Empresa: SystemsIT

 WebSite: http://www.systemsit.com.br/

 Cargo: Analista Business Intelligence

 Início: 01/12/2015

 Fim: -

 Cargo Atual: Sim

												Mais informações

Localidade

 Barueri -Alphaville

Atividades

 Análise/levantamento de requisitos com usuários, Definição de especificações funcionais e técnicas, desenvolvimento e manutenção de cargas ETL utilizando as ferramentas POWER CENTER 9.5.1 e ORACLE 11g, Modelagem de dados (PowerDesingner).Obs.: Projeto de migração Cielo juntamente com a equipe de Power Center da própria Informatica.

Habilidades

														POWER CENTER 9.5.1
														ORACLE 11g
														PowerDesingner

 Empresa: Netpartners

 WebSite: http://www.netpartners.com.br

 Cargo: Analista Business Intelligence

 Início: 01/09/2015

 Fim: 01/12/2015

 Cargo Atual: Não

													Mais informações

Localidade

 Barueri -Alphaville

Atividades

 Análise/levantamento de requisitos, Definição de especificações funcionais e técnicas, desenvolvimento e manutenção de cargas ETL utilizando as ferramentas POWER CENTER 9.5.1 e ORACLE 11g, Modelagem de dados (EA), Definições e estratégias de controles de cargas.

Habilidades

															POWER CENTER 9.5.1
															ORACLE 11g
															EA

Certificações

 Instituição: Informatica

 Certificado: Informatica Certified Developer

 Data de Conslusão: 01/03/2016

												Mais informações

Número da Licença

 -

URL do Certificado

 -

Descrição

 -

Cursos Extras Curriculares

 Instituição: Ka Solution Tecnologia em Software Ltda

 Curso: Microsoft SQL Server 2008 Integration Services

 Total de Horas: 40

 Data de Conslusão: 01/05/2011

												Mais informações

Descrição

 -

 Instituição: Impacta Tecnologia Eletrônica Ltda

 Curso:  	Programando em SQL Server 2000

 Total de Horas: 40

 Data de Conslusão: 01/04/2006

													Mais informações

Descrição

 -

Rodrigo Gomes vídeo compartilhado

												Sem comentários

Outras Informações

													Resumo Profissional

															Análise e Desenvolvimento de Projetos para empresas de grande porte e multinacionais, desenvolvendo soluções com alta tecnologia e diferenciadas.
															Analista, com conhecimentos em diversas tecnologias, tais como, Visual Basic 6, Crystal Reports 8.5, SQL SERVER (2000/2005/2008R2), Oracle, Visual Studio .NET 2008/2010, VB.NET, C#, Web Services, SSAS 2008, SSIS 2008, SSRS 2008, Qlikview 10, Power Center 9 (B2B Data Transformation).
															Tec II – Performance e técnicas de Tuning em SQL Server 2005/2008R2 e ETL com SSIS e Power Center.
															Processos - Boa experiência em projetos de ETL com participação de reuniões junto ao cliente e auxiliando na elaboração dos fluxos.
															Raciocínio lógico, habilidade em solução de problemas, ágil, proativo, comprometimento, comunicativo e dedicado, compartilhando conhecimento com o objetivo de aprender novas linguagens, tecnologias e metodologias.

													Habilidades Gerais

															Windows
															Linux
															MS Office
															Open Office
															Help & Manual 3.5
															Altova XMLSpy 2008
															Adobe Acrobat
															Internet
															Page Maker
															Front Page
															Crystal Reports 8.5
															Crystal Reports 9
															Micro Point S
															RM Sistemas
															HTML
															ASP
															PHP
															Adobe Flex 3.0
															Dreamweawer 4
															FireWorks 8
															Spread 3.0 – Far Point
															Visual Basic 6
															VB.Net
															C#
															Delphi 7
															Oracle 10g
															Oracle 11g
															PL\SQL
															SQL Server 2000
															SQL Server 2005
															SQL Server 2008R2
															SQL Server Analysis Services 2008
															SQL Server Integration Services 2008
															SQL Server Reporting Services 2008
															Visual Studio 2005
															Visual Studio 2008
															Visual Studio 2010
															Power Center 8.5
															Power Center 9.5.1
															ER\Studio 9
															QlikView 10
															SourceSafe 6.0
															Fox PRO
															Inno Setup 5.0
															Istool 5.2
															Java
															VRML
															C
															Pascal

												Idioma
												Nível

												Português
												Nativo

												Inglês
												Técnico

Expectativas para o próximo emprego

												Cargo Principal
												Cargo Secundário
												Cargo Terceário

												Arquiteto da Informação Sênior
												Analista de Web Development Sênior
												Analista Programador Sênior

												Forma de Contratação
												Pretensão Salarial (base 168/mês)
												Disponibilidade para Início

												CLT Full
												11.500,00
												Até 15 dias

Trabalhos Voluntários

 Organização: Pet Vida

 Causas: Proteção Animal

 Cargo: Assitente de domicílio

												Mais informações

Início

 01/05/2011

Fim

 -

Cargo Atual

 Sim

 Organização: Um Futuro Melhor

 Causas: Crianças

 Cargo: Psicólogo(a)

												Mais informações

Início

 01/04/2010

Fim

 30/08/2010

Cargo Atual

 Não

Sobre Você

													Perfil - Hobby

															Eu sou um cara estrovertido, nos finais de semana gosto de sair com minha filha e leva-lá a parques juntamente com minha esposa. Gosto de jogar futebol e também pratico boxe.

          Version 1.0.0

        Copyright © 2016-2016  SumIFIT  All rights reserved.

Recent Activity

Langdon's Birthday

Will be 23 on April 24th

Frodo Updated His Profile

New phone +1(800)555-1234

Nora Joined Mailing List

nora@example.com

Cron Job 254 Executed

Execution time 5 seconds

Tasks Progress

                    Custom Template Design
                    70%

                    Update Resume
                    95%

                    Laravel Integration
                    50%

                    Back End Framework
                    68%

Stats Tab Content

            <form method="post">

General Settings

                  Report panel usage
                  <input type="checkbox" class="pull-right" checked>

                  Some information about this general settings option

                  Allow mail redirect
                  <input type="checkbox" class="pull-right" checked>

                  Other sets of options are available

                  Expose author name in posts
                  <input type="checkbox" class="pull-right" checked>

                  Allow the user to show his name in blog posts

Chat Settings

                  Show me as online
                  <input type="checkbox" class="pull-right" checked>

                  Turn off notifications
                  <input type="checkbox" class="pull-right">

                  Delete chat history

            </form>


text:
.class public interface abstract Lcom/umeng/analytics/onlineconfig/c;
.super Ljava/lang/Object;

# virtual methods
.method public abstract a(IJ)V
.end method


text:
#ifndef __LXUTILITIES_H

#define __LXUTILITIES_H

#include "layout/LETypes.h"

U_NAMESPACE_BEGIN

class LXUtilities
{
public:
    static le_int8 highBit(le_int32 value);
    static le_int32 search(le_int32 value, const le_int32 array[], le_int32 count);
    static void reverse(le_int32 array[], le_int32 count);
    static void reverse(float array[], le_int32 count);
};

U_NAMESPACE_END
#endif


text:
<?php

// src/TableTennis/AnnouncementBundle/DataFixtures/ORM/LoadAnnouncementData.php
namespace TableTennis\AnnouncementBundle\DataFixtures\ORM;

use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\FixtureInterface;
use TableTennis\AnnouncementBundle\Entity\Announcement;

class LoadAnnouncementData implements FixtureInterface
{
    public function load(ObjectManager $manager)
    {
        require_once(__DIR__.'/../../../../../external_scripts/DB.php');
        require_once(__DIR__.'/../../../../../external_scripts/load_announcement.php');

        foreach( $dataList as $data )
        {
            if( !is_null( $data["creation_user_id"] ) ) {
                $creationUser = $manager->getRepository('Application\Sonata\UserBundle\Entity\User')->find( $data["creation_user_id"] );
            }
            if( !is_null( $data["modification_user_id"] ) ) {
                $modificationUser = $manager->getRepository('Application\Sonata\UserBundle\Entity\User')->find( $data["modification_user_id"] );
            }

            $announcement = new Announcement();
            $announcement->setId( $data["id"] );
            if( isset( $creationUser ) ) {
                $announcement->setCreationUserId( $creationUser );
            }
            if( isset( $modificationUser ) ) {
                $announcement->setModificationUserId( $modificationUser );
            }
            $announcement->setTitle( $data["title"] );
            $announcement->setContent( $data["description"] );
            $announcement->setLink( $data["type"] == "home" ? "/" : "/equipes-du-club.html" );
            // $announcement->setSlug();
            $announcement->setCreatedAt( new \DateTime($data["created_at"]) );
            $announcement->setUpdatedAt( new \DateTime($data["updated_at"]) );
            $announcement->setIsPublished( 1 );

            $manager->persist($announcement);

            /* Pour forcer l'id */
            $metadata = $manager->getClassMetaData(get_class($announcement));
            $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_NONE);

            $manager->flush();
        }
    }

    /**
     * The order in which these fixtures will be loaded.
     */
    public function getOrder()
    {
        return 3;
    }
}

?>


text:
package com.intellij.psi.impl;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.progress.EmptyProgressIndicator;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.UnfairTextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.PomManager;
import com.intellij.pom.PomModel;
import com.intellij.pom.event.PomModelEvent;
import com.intellij.pom.impl.PomTransactionBase;
import com.intellij.pom.tree.TreeAspect;
import com.intellij.pom.tree.TreeAspectEvent;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiLock;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.psi.impl.source.text.DiffLog;
import com.intellij.psi.impl.source.tree.FileElement;
import com.intellij.psi.text.BlockSupport;
import com.intellij.util.FileContentUtilCore;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.Processor;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Arrays;

public abstract class DocumentCommitProcessor {
  private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.DocumentCommitThread");

  public abstract void commitSynchronously(@NotNull Document document, @NotNull Project project);
  public abstract void commitAsynchronously(@NotNull final Project project, @NotNull final Document document, @NonNls @NotNull Object reason);

  protected static class CommitTask {
    public final Document document;
    public final Project project;

    // when queued it's not started
    // when dequeued it's started
    // when failed it's canceled
    public final ProgressIndicator indicator; // progress to commit this doc under.
    public final Object reason;
    public boolean removed; // task marked as removed, should be ignored.

    public CommitTask(@NotNull Document document,
                       @NotNull Project project,
                       @NotNull ProgressIndicator indicator,
                       @NotNull Object reason) {
      this.document = document;
      this.project = project;
      this.indicator = indicator;
      this.reason = reason;
    }

    @NonNls
    @Override
    public String toString() {
      return "Project: " + project.getName()
             + ", Doc: "+ document +" ("+  StringUtil.first(document.getText(), 12, true).replaceAll("\n"," ")+")"
             +(indicator.isCanceled() ? " (Canceled)" : "") + (removed ? "Removed" : "");
    }

    @Override
    public boolean equals(Object o) {
      if (this == o) return true;
      if (!(o instanceof CommitTask)) return false;

      CommitTask task = (CommitTask)o;

      return document.equals(task.document) && project.equals(task.project);
    }

    @Override
    public int hashCode() {
      int result = document.hashCode();
      result = 31 * result + project.hashCode();
      return result;
    }
  }

  @Nullable("returns runnable to execute under write action in AWT to finish the commit")
  public Processor<Document> doCommit(@NotNull final CommitTask task,
                                      @NotNull final PsiFile file,
                                      final boolean synchronously) {
    Document document = task.document;
    final TextBlock textBlock = TextBlock.get(file);
    if (textBlock.isEmpty()) return null;
    final long startDocModificationTimeStamp = document.getModificationStamp();
    final FileElement myTreeElementBeingReparsedSoItWontBeCollected = ((PsiFileImpl)file).calcTreeElement();
    if (textBlock.isEmpty()) return null; // if tree was just loaded above textBlock will be cleared by contentsLoaded
    final CharSequence chars = document.getCharsSequence();
    final Boolean data = document.getUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY);
    if (data != null) {
      document.putUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY, null);
      file.putUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY, data);
    }
    final String oldPsiText = ApplicationManager.getApplication().isInternal() && ApplicationManager.getApplication().isUnitTestMode()
                              ? myTreeElementBeingReparsedSoItWontBeCollected.getText()
                              : null;
    final TextRange changedPsiRange =
      getChangedPsiRange(file, textBlock.getStartOffset(), textBlock.getPsiEndOffset(), document.getTextLength());
    if (!assertBeforeCommit(document, file, textBlock, chars, oldPsiText, myTreeElementBeingReparsedSoItWontBeCollected)) {
      return new Processor<Document>() {
        @Override
        public boolean process(Document document) {
          VirtualFile vFile = FileDocumentManager.getInstance().getFile(document);
          log("Recovering from assertBeforeCommit", task, synchronously, vFile, vFile != null && vFile.isValid());
          if (vFile != null && vFile.isValid()) {
            FileContentUtilCore.reparseFiles(Arrays.asList(vFile));
          }
          return true;
        }
      };
    }
    BlockSupport blockSupport = BlockSupport.getInstance(file.getProject());
    final DiffLog diffLog = blockSupport.reparseRange(file, changedPsiRange, chars, task.indicator);

    return new Processor<Document>() {
      @Override
      public boolean process(Document document) {
        ApplicationManager.getApplication().assertWriteAccessAllowed();
        log("Finishing", task, synchronously, document.getModificationStamp(), startDocModificationTimeStamp);
        if (document.getModificationStamp() != startDocModificationTimeStamp) {
          return false; // optimistic locking failed
        }

        try {
          CodeStyleManager.getInstance(file.getProject()).performActionWithFormatterDisabled(new Runnable() {
            @Override
            public void run() {
              synchronized (PsiLock.LOCK) {
                doActualPsiChange(file, diffLog);
              }
            }
          });

          assertAfterCommit(document, file, oldPsiText, myTreeElementBeingReparsedSoItWontBeCollected);
        }
        finally {
          textBlock.clear();
        }

        return true;
      }
    };
  }

  public static TextRange getChangedPsiRange(PsiFile file, int changeStart, int changeEnd, int newTextLength) {
    if (file.getViewProvider().supportsIncrementalReparse(file.getLanguage())) {
      return new UnfairTextRange(changeStart, changeEnd);
    }
    return new TextRange(0, newTextLength);
  }

  public static void doActualPsiChange(@NotNull final PsiFile file, @NotNull final DiffLog diffLog) {
    file.getViewProvider().beforeContentsSynchronized();

    try {
      final Document document = file.getViewProvider().getDocument();
      PsiDocumentManagerBase documentManager = (PsiDocumentManagerBase)PsiDocumentManager.getInstance(file.getProject());
      PsiToDocumentSynchronizer.DocumentChangeTransaction transaction = documentManager.getSynchronizer().getTransaction(document);

      final PsiFileImpl fileImpl = (PsiFileImpl)file;

      if (transaction == null) {
        final PomModel model = PomManager.getModel(fileImpl.getProject());

        model.runTransaction(new PomTransactionBase(fileImpl, model.getModelAspect(TreeAspect.class)) {
          @Override
          public PomModelEvent runInner() {
            return new TreeAspectEvent(model, diffLog.performActualPsiChange(file));
          }
        });
      }
      else {
        diffLog.performActualPsiChange(file);
      }
    }
    catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }

  private static boolean assertBeforeCommit(@NotNull Document document,
                                         @NotNull PsiFile file,
                                         @NotNull TextBlock textBlock,
                                         @NotNull CharSequence chars,
                                         String oldPsiText,
                                         @NotNull FileElement myTreeElementBeingReparsedSoItWontBeCollected) {
    int startOffset = textBlock.getStartOffset();
    int psiEndOffset = textBlock.getPsiEndOffset();
    if (oldPsiText != null) {
      @NonNls String msg = "PSI/document inconsistency before reparse: file=" + file + " of class " + file.getClass();
      if (startOffset >= oldPsiText.length()) {
        msg += "\nstartOffset=" + oldPsiText + " while text length is " + oldPsiText.length() + "; ";
        startOffset = oldPsiText.length();
      }

      String psiPrefix = oldPsiText.substring(0, startOffset);
      String docPrefix = chars.subSequence(0, startOffset).toString();
      String psiSuffix = psiEndOffset > oldPsiText.length() ? "<psiEndOffset too large>" : oldPsiText.substring(psiEndOffset);
      String docSuffix = chars.subSequence(textBlock.getTextEndOffset(), chars.length()).toString();
      if (!psiPrefix.equals(docPrefix) || !psiSuffix.equals(docSuffix)) {
        if (!psiPrefix.equals(docPrefix)) {
          msg = msg + "\n\npsiPrefix=" + psiPrefix + "\n\ndocPrefix=" + docPrefix;
        }
        if (!psiSuffix.equals(docSuffix)) {
          msg = msg + "\n\npsiSuffix=" + psiSuffix + "\n\ndocSuffix=" + docSuffix;
        }
        LOG.error(msg);
        return false;
      }
    }
    else if (document.getTextLength() - textBlock.getTextEndOffset() !=
             myTreeElementBeingReparsedSoItWontBeCollected.getTextLength() - psiEndOffset) {
      LOG.error("PSI/document inconsistency before reparse: file=" + file);
      return false;
    }

    return true;
  }

  private void assertAfterCommit(Document document,
                                        final PsiFile file,
                                        String oldPsiText,
                                        FileElement myTreeElementBeingReparsedSoItWontBeCollected) {
    if (myTreeElementBeingReparsedSoItWontBeCollected.getTextLength() != document.getTextLength()) {
      final String documentText = document.getText();
      if (ApplicationManager.getApplication().isInternal()) {
        String fileText = file.getText();
        LOG.error("commitDocument left PSI inconsistent; file len=" + myTreeElementBeingReparsedSoItWontBeCollected.getTextLength() +
                  "; doc len=" + document.getTextLength() +
                  "; doc.getText() == file.getText(): " + Comparing.equal(fileText, documentText) +
                  ";\n file psi text=" + fileText +
                  ";\n doc text=" + documentText +
                  ";\n old psi file text=" + oldPsiText);
      }
      else {
        LOG.error("commitDocument left PSI inconsistent: " + file);
      }

      file.putUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY, Boolean.TRUE);
      try {
        BlockSupport blockSupport = BlockSupport.getInstance(file.getProject());
        final DiffLog diffLog = blockSupport.reparseRange(file, new TextRange(0, documentText.length()), documentText, createProgressIndicator());
        CodeStyleManager.getInstance(file.getProject()).performActionWithFormatterDisabled(new Runnable() {
          @Override
          public void run() {
            synchronized (PsiLock.LOCK) {
              doActualPsiChange(file, diffLog);
            }
          }
        });

        if (myTreeElementBeingReparsedSoItWontBeCollected.getTextLength() != document.getTextLength()) {
          LOG.error("PSI is broken beyond repair in: " + file);
        }
      }
      finally {
        file.putUserData(BlockSupport.DO_NOT_REPARSE_INCREMENTALLY, null);
      }
    }
  }

  public void log(@NonNls String msg, CommitTask task, boolean synchronously, @NonNls Object... args) {
  }

  @NotNull
  protected ProgressIndicator createProgressIndicator() {
    return new EmptyProgressIndicator();
  }
}


text:
package org.apache.pulsar.functions.instance;

import org.apache.logging.log4j.core.*;
import org.apache.pulsar.client.api.CompressionType;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.ProducerBuilder;
import org.apache.pulsar.client.api.PulsarClient;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

/**
 * LogAppender class that is used to send log statements from Pulsar Functions logger
 * to a log topic.
 */
public class LogAppender implements Appender {
    private PulsarClient pulsarClient;
    private String logTopic;
    private String fqn;
    private State state;
    private ErrorHandler errorHandler;
    private Producer<byte[]> producer;

    public LogAppender(PulsarClient pulsarClient, String logTopic, String fqn) {
        this.pulsarClient = pulsarClient;
        this.logTopic = logTopic;
        this.fqn = fqn;
    }

    @Override
    public void append(LogEvent logEvent) {
        producer.sendAsync(logEvent.getMessage().getFormattedMessage().getBytes());
    }

    @Override
    public String getName() {
        return fqn;
    }

    @Override
    public Layout<? extends Serializable> getLayout() {
        return null;
    }

    @Override
    public boolean ignoreExceptions() {
        return false;
    }

    @Override
    public ErrorHandler getHandler() {
        return errorHandler;
    }

    @Override
    public void setHandler(ErrorHandler errorHandler) {
        this.errorHandler = errorHandler;
    }

    @Override
    public State getState() {
        return state;
    }

    @Override
    public void initialize() {
        this.state = State.INITIALIZED;
    }

    @Override
    public void start() {
        this.state = State.STARTING;
        try {
            producer = pulsarClient.newProducer()
                    .topic(logTopic)
                    .blockIfQueueFull(false)
                    .enableBatching(true)
                    .compressionType(CompressionType.LZ4)
                    .batchingMaxPublishDelay(100, TimeUnit.MILLISECONDS)
                    .property("function", fqn)
                    .create();
        } catch (Exception e) {
            throw new RuntimeException("Error starting LogTopic Producer", e);
        }
        this.state = State.STARTED;
    }

    @Override
    public void stop() {
        this.state = State.STOPPING;
        producer.closeAsync();
        producer = null;
        this.state = State.STOPPED;
    }

    @Override
    public boolean isStarted() {
        return state == State.STARTED;
    }

    @Override
    public boolean isStopped() {
        return state == State.STOPPED;
    }
}


text:
'use strict';
var exporter = require('../lib/exporter.js');
var assert = require('assert');
var sinon = require('sinon');
var http = require('http');
var express = require('express');
var bodyParser = require('body-parser');
var qs = require('querystring');

describe('remote', function () {
  var mock = [];
  var oldEngine;
  var spy;
  var remoteURL = '';

  beforeEach(function (done) {
    // create a data-passthrough "fake" engine
    exporter.engines.fake = function (data) {
      return new Promise(function (resolve, reject) {
        resolve(data);
      });
    };

    // create a server that calls the spy on each request
    mock = [1, 2, 3, 4, 5, 6];

    exporter.config = {};
    exporter.config = require('./fixtures/config.json');
    exporter.config.participants.$engine = 'fake';

    spy = sinon.spy();
    var remote = express();
    remote.use(bodyParser.json());
    remote.all('*', function (req, res) {
      spy({
        body: req.body,
        method: req.method,
        headers: req.headers
      });
      res.status(200, { 'content-type': 'application/json' });
      res.send(mock);
    });

    var server = http.createServer(remote);

    server.listen(0);

    // reconfigure exporter to send fetch requests to this new server
    server.on('listening', function () {
      remoteURL = 'http://localhost:' + server.address().port;
      done();
    });
  });

  afterEach(function () {
    delete exporter.engines.fake;
    delete exporter.config.$remote;
    delete process.env.NODE_ENV;
  });

  it('should support sending headers', function () {
    var expected = [
      { title: 1, date: '2015-09-13' },
      { title: 2, date: '2015-09-13' },
    ];

    return exporter().config({
      $root: remoteURL,
    }).get.participants.byDate({
      date: '[2015,05,22]',
      $request: {
        method: 'post',
        headers: {
          'x-custom': 'true',
        },
      },
    })
    .then(function (data) {
      if (!spy.called) {
        throw new Error('local server not was hit - fail');
      }

      var call = spy.args[0].pop();

      assert.equal(call.method, 'POST', 'request was a ' + call.method);
      assert.equal(call.headers['x-custom'], 'true', 'custom header was present: ' + JSON.stringify(call.headers));
    }).__state;
  });
});


text:
AliAnalysisTaskPHOSObjectCreator* AddTaskPHOSObjectCreator(
    const char* name           = "PHOSObjectCreator",
    const UInt_t trigger       = AliVEvent::kINT7|AliVEvent::kPHI7,
    const Bool_t usePHOSTender = kTRUE,
    const Bool_t isMC          = kFALSE,
    const Double_t BunchSpace  = 25.,
    const Double_t distanceBC  = 0.,
    const Bool_t NonLinCorr    = kTRUE,
    const Bool_t excludeM4     = kTRUE,
    const TString period       = "LHC15n"
    )
{
  //Add a task AliAnalysisTaskPHOSObjectCreator to the analysis train
  //Author: Daiki Sekihata
  /* $Id$ */

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskPHOSObjectCreator", "No analysis manager to connect to");
    return NULL;
  }

  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskPHOSObjectCreator", "This task requires an input event handler");
    return NULL;
  }

  TString taskname = Form("%s_BS%dns_DBC%dcm",name,(Int_t)BunchSpace,(Int_t)(distanceBC*10));

  AliAnalysisTaskPHOSObjectCreator* task = new AliAnalysisTaskPHOSObjectCreator(taskname);
  task->SelectCollisionCandidates(trigger);
  task->SetTenderFlag(usePHOSTender);
  task->SetMCFlag(isMC);
  task->SetBunchSpace(BunchSpace);//in unit of ns
  task->SetMinimumDistanceFromBC(distanceBC);
  task->ExcludeM4(excludeM4);

  if(isMC && NonLinCorr){
    TF1 *f1nonlin = new TF1("f1nonlin","[2]*(1.+[0]*TMath::Exp(-x*x/2./[1]/[1]))",0,100);
    f1nonlin->SetNpx(1000);
    f1nonlin->SetParNames("a","b");
    //f1nonlin->FixParameter(0,0);//for core E
    //f1nonlin->FixParameter(1,1);//for core E
    //f1nonlin->FixParameter(0,-0.03);//for core E at ZS5
    //f1nonlin->FixParameter(1,  0.6);//for core E at ZS5
    //f1nonlin->FixParameter(0,-0.06); //for full E at ZS5 ;
    //f1nonlin->FixParameter(1,  0.4); //for full E at ZS5 ;
    if(period.Contains("LHC15n")){
      f1nonlin->FixParameter(0,-0.05); //for full E, ZS = 20MeV;
      f1nonlin->FixParameter(1,  0.6); //for full E, ZS = 20MeV;
      f1nonlin->FixParameter(2,1.006); //for full E, ZS = 20MeV;//decalib 3% on M123
      //f1nonlin->FixParameter(0,-0.03);//for core E at ZS 20 MeV
      //f1nonlin->FixParameter(1,  0.9);//for core E at ZS 20 MeV
    }
    else if(period.Contains("LHC15o")){
      f1nonlin->FixParameter(0,-0.04);//for core E at ZS 20 MeV with only MIP cut
      f1nonlin->FixParameter(1,  0.8);//for core E at ZS 20 MeV with only MIP cut
      f1nonlin->FixParameter(2, 0.99);//for core E at ZS 20 MeV with only MIP cut
    }
    task->SetUserDefinedNonlinearity(f1nonlin);
  }

  mgr->AddTask(task);
  mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
  const TString listname = Form("hist_%s",name);

  TString outputFile = AliAnalysisManager::GetCommonFileName();
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(Form("%s",listname.Data()), THashList::Class(), AliAnalysisManager::kOutputContainer, Form("%s:%s",outputFile.Data(),"PWGGA_PHOSTasks_PHOSRun2"));
  mgr->ConnectOutput(task, 1, coutput1);

  return task;
}


text:
package org.tao.j2otp;

import junit.framework.TestCase;

/**
 * Created by junjie on 1/4/15.
 */
public class Pubsub extends TestCase {
    protected Tlor _tlor = null;
    protected boolean _debug = false;
    protected static final String _NODE_NAME = "/home/xwtec.im/newspub/debug";

    @Override
    public void setUp() throws Exception {
        super.setUp();
        if (_debug) {
            _tlor = new Tlor(new Options("tlor@192.168.4.11:tlor@192.168.21.168",
                    "abc",
                    "newspub@xwtec.im", "Welc0me"));
        }
    }

    public void test() throws Exception {
        if (!_debug) return;

        _delete_node();
        _create_node();
        _unsubscribe();
        _subscribe();
    }

    private void _delete_node() throws Exception {
        final Options o = _tlor.options();
        TlorResponse r = _tlor.delete_node(o.user(), o.password(), _NODE_NAME);
        assertNotNull("r is null", r);
        assertTrue(r.raw(), r.status());
    }

    private void _create_node() throws Exception {
        final Options o = _tlor.options();
        TlorResponse r = _tlor.create_node(o.user(), o.password(), _NODE_NAME);
        assertNotNull("r is null", r);
        assertTrue(r.raw(), r.status());
    }

    private void _unsubscribe() {
        TlorResponse r = _tlor.unsubscribe("beta@xwtec.im", "Welc0me");
        assertNotNull("r is null", r);
        assertTrue(r.raw(), r.status());
    }

    private void _subscribe() {
        TlorResponse r = _tlor.subscribe("beta@xwtec.im", "Welc0me", _NODE_NAME);
        assertNotNull("r is null", r);
        assertTrue(r.raw(), r.status());
    }

}