text:
/* Début de parseur de fichiers .h
 *
 * Ce parseur analyse un fichier header, à la recherche de définitions des
 * classes et stocke les informations trouvées dans un objet BPositionIO
 *
 *
 * Pour l'instant le parseur est très simplifié:
 * + n'utiliser qu'avec des syntaxes simples
 * + ne gère pas les define, include et autres #machin
 * + ne gère pas les typedef
 * + ne reconnait pas les #define sur plusieurs lignes avec des \
 * + les inline, static sont ignorés, ainsi que les passages par référence (&)
 * + ignore les classes amies (friend)
 * + n'a pas été essayé avec des tableaux (définis par [] ) comportement incertain dans ce cas
 * + les classes imbriquées ne sont pas gérées (pareil, comportement incertain dans ce cas)
 * + sûrement d'autres trucs que je n'ai pas vu
 */

/* Utilisation de la classe:
 * Au moment où on doit faire un parsing, créer un objet CSParser en lui
 * donnant en argument l'objet BPositionIO que l'on veut utiliser pour
 * stocker les informations.
 * Ensuite on fait un appel à Parse() pour chaque fichier .h que l'on veut
 * parser.
 * Enfin on détruit l'objet CSParser.
 * ON NE DOIT PAS LIRE L'OBJET BPOSITIONIO AVANT QUE L'OBJET CSPARSER SOIT
 * DETRUIT
 */

/* La classe suppose que le fichier donné est dans un format valide. (en gros
 * que les chunks se suivent bien et qu'aucune dimension ne soit farfelue)
 * Le comportement est indéterminé si ce n'est pas le cas. Il y a de grandes
 * chances que ça fasse boum.
 */

#include "CSParser.h"
#include "CSClass.h"			// pour les constances CSMT_...
#include "CSLibrary.h"		// pour la constante CSP_NOT_MODIFIED
#include <stdio.h>
#include <ctype.h>

#include <String.h>
#include <File.h>
#include <Directory.h>
#include <Entry.h>
#include <Path.h>
#include <NodeInfo.h>

//#define PRINT_PARSE_DEBUG

// macro pour le débug
#ifdef PRINT_PARSE_DEBUG
#define DBG(x) printf(x)
#define DBG2(x,y) printf(x,y)
#else
#define DBG(x)
#define DBG2(x,y)
#endif

CSParser::CSParser(BPositionIO *data)
{
	m_Data = data;
	m_InitCheck = B_ERROR;

	// on vérifie le header du fichier
	unsigned int l_Type,l_Size;
	if (!ChunkInfo(0,&l_Type,&l_Size)|| (l_Type != g_CFile))
	{
		// va pa...
		// on recrée un header propre
		m_EndClassChunk = 0;
		if (ChunkUpdate(&m_EndClassChunk,g_CFile,0) &&
			ChunkUpdate(&m_EndClassChunk,g_CClassList,0))
		{
			m_BegClassChunk = m_EndClassChunk;
			m_InitCheck = B_OK;
		}
	}
	else
	{
		// chargement des données contenues dans le fichier
		unsigned int l_Pointer = g_ChunkHeaderSize;
		m_EndClassChunk = 0;
		while (ChunkInfo(l_Pointer,&l_Type,&l_Size))
		{
			// on est tombés sur quel chunk?
			switch(l_Type)
			{
				case g_CClassList:	// liste de chunks 'CLAS'
				{
					// on repère le début du chunk
					m_BegClassChunk = l_Pointer+g_ChunkHeaderSize;

					// on va à la fin du chunk et on place le pointeur
					// m_EndClassChunk dessus
					if (!ChunkSkip(&l_Pointer))
						return;

					m_EndClassChunk = l_Pointer;
					break;
				}

				case g_CClassNames:	// espace de stockage des chaînes
							// de caractères pour les noms de classes
				{
					// on charge le chunk 'CLNM', dans m_ClassNamesData
					m_ClassNamesData.SetSize(l_Size);

					if (!ChunkRead(&l_Pointer,(void*)m_ClassNamesData.Buffer()))
						return;
					break;
				}

				case g_CNamesList:	// liste classée des noms de classes
				{
					// on charge la liste et on passe au chunk suivant
					if ((!m_ClassNamesList.Init(this,l_Pointer)) ||
						(!ChunkSkip(&l_Pointer)))
						return;
					break;
				}

				default:
				{
					// on saute simplement le chunk
					if (!ChunkSkip(&l_Pointer))
						return;
				}
			}

		}

		// si m_EndClassChunk n'a pas été positionné, c'est qu'on a pas trouvé le chunk 'LCLA' (boum)
		if (m_EndClassChunk == 0)
			return;
	}

	m_InitCheck = B_OK;
}

CSParser::~CSParser()
{
	// on va commencer par mettre à jour le chunk 'LCLA'
	// pour ça on va commencer par le chercher
	unsigned int l_Pointer = g_ChunkHeaderSize, l_Type=0, l_Size;
	if (!ChunkInfo(l_Pointer,&l_Type,&l_Size))
		// on ne devrait jamais arriver à ce point. On DOIT tomber sur le chunk 'LCLA' avant
		// la fin du fichier. Sinon c'est qu'il y a un gros problème...
		return;

	while (l_Type != g_CClassList)
	{
		// on passe au chunk suivant
		if ((!ChunkSkip(&l_Pointer)) || (!ChunkInfo(l_Pointer,&l_Type,&l_Size)))
			// même remarque que ci-dessus
			return;
	}

	// on est au début du chunk 'LCLA'. On peut mettre sa taille à jour
	if (!ChunkUpdate(&l_Pointer,g_CClassList,m_EndClassChunk-l_Pointer-g_ChunkHeaderSize))
		return;

	// écriture du chunk 'CLNM'
	if (!ChunkWrite(&l_Pointer,g_CClassNames,m_ClassNamesData.Buffer(),m_ClassNamesData.Seek(0,SEEK_END)))
		return;

	// et enfin du chunk 'LIST'
	if (!m_ClassNamesList.Write(this,&l_Pointer))
		return;

	// mise à jour du chunk principal
	unsigned int l_BegPointer=0;
	if (!ChunkUpdate(&l_BegPointer,g_CFile,l_Pointer-g_ChunkHeaderSize))
		return;

	// tout s'est bien passé!
	m_Data->SetSize(l_Pointer);
}

// fonctions utilitaires pour le parsing
/// recherche de mot
bool CSParser::ExtractWord(BString &word,const char **pointer, const char *endOfText, bool *isOperator)
{
	// n'est-on pas à la fin du fichier?
	if (*pointer >= endOfText)
		return false;

	// débord on vire les espaces du début, et les commentaires
	while(isspace(**pointer) || **pointer == '/')
	{
		// s'agit-il d'un commentaire?
		if (**pointer == '/')
		{
			// peut-être...

			// s'agit-il d'un commentaire en '//'?
			if (*(*pointer+1) == '/')
				// oui
				SkipToEndOfLine(pointer,endOfText);
			// ou d'un commentaire en '/*'?
			else if (*(*pointer+1) == '*')
			{
				// oui... recherche du */
				(*pointer)++;
				if (*pointer >= endOfText)
					return false;
				(*pointer)++;

				while ((**pointer != '*') || (*(*pointer+1) != '/'))
				{
					if (*pointer >= endOfText)
						return false;

					(*pointer)++;
				}
				*pointer += 2;
			}
			else
			// non, ce n'est pas un commentaire. On est devant un authentique opérateur
				break;

			// n'est-on pas à la fin du fichier?
			if (*pointer >= endOfText)
				return false;
		}
		else
		{
			// c'est un espace tout bête... on passe au caractère suivant
			(*pointer)++;
			if (*pointer >= endOfText)
				return false;
		}
	}

	// maintenant pointer pointe sur un caractère utile
	// s'agit-il d'un mot?
	if (isalnum(**pointer) || **pointer=='_')
	{
		const char *l_Begin = *pointer;

		// oui, on va en chercher la fin
		while (isalnum(**pointer) || **pointer=='_')
		{
			(*pointer)++;
			if (*pointer >= endOfText)
				return false;
		}
		word.SetTo(l_Begin,*pointer-l_Begin);
		*isOperator = false;
		return true;
	}
	else
	// non
	{
		// est-ce une chaîne de caractères?
		if ((**pointer == '"') && (*(*pointer-1) != '\\') && (*(*pointer-1) != '\''))	// 39 c'est l'apostrophe
		{
			// oui
			const char *l_Begin = *pointer;
			SkipToEndOfString(pointer,endOfText);

			word.SetTo(l_Begin,*pointer-l_Begin);
			*isOperator = false;
			return true;
		}

		// non, c'est bien un opérateur
		word.SetTo(*pointer,1);
		(*pointer)++;
		*isOperator = true;
		return true;
	}
}

/// va à la ligne suivante
void CSParser::SkipToEndOfLine(const char **pointer, const char *endOfText)
{
	while(**pointer != '\n')
	{
		if (*pointer >= endOfText)
			return;
		(*pointer)++;
	}
	(*pointer)++;
}

/// va à l'instruction suivante
void CSParser::SkipToNextInstruction(const char **pointer, const char *endOfText)
{
	bool l_IsOperator=false;
	BString l_Word;

	while (!l_IsOperator || l_Word != ";")
	{
		if (!ExtractWord(l_Word,pointer,endOfText,&l_IsOperator))
			return;

		if (l_IsOperator && l_Word == "\"")
			// on est tombés sur un ", donc une chaîne de caractères... on cherche la fin
			SkipToEndOfString(pointer,endOfText);
		else if (l_IsOperator && l_Word == "{")
			// on est au début d'un bloc logique... on va en chercher la fin
			SkipToClosingBracket(pointer,endOfText);
	}
}

/// va à la fin d'un bloc logique
void CSParser::SkipToClosingBracket(const char **pointer, const char *endOfText)
{
/*	bool l_IsOperator=false;
	BString l_Word;

	while (!l_IsOperator || l_Word != "}")
	{
		if (!ExtractWord(l_Word,pointer,&l_IsOperator))
			return;

		if (l_IsOperator && l_Word == "\"")
			// on est tombés sur un ", donc une chaîne de caractères... on cherche la fin
			SkipToEndOfString(pointer);
		else if (l_IsOperator && l_Word == "{")
			// on est un autre bloc logique à l'intérieur de celui-ci. On va le sauter aussi
			SkipToClosingBracket(pointer);
	}
*/
	while(**pointer != '}')
	{
		if (*pointer >= endOfText)
			return;

		char l_Char = *(*pointer)++;

		switch(l_Char)
		{
			case 0:
				(*pointer)--;
				return;
				break;

			case '"':
				SkipToEndOfString(pointer,endOfText);
				break;

			case '{':
				SkipToClosingBracket(pointer,endOfText);
				break;

			case '/':
				// peut-être un commentaire
				if (**pointer=='/')
					// oui, un commentaire sur une ligne
					SkipToEndOfLine(pointer,endOfText);
				else if (**pointer=='*')
				{
					// oui, un commentaire en /* */
					(*pointer)++;
					while (((**pointer) != '*') || (*(*pointer+1) != '/'))
					{
						if (*pointer >= endOfText)
							return;
						(*pointer)++;
					}
					*pointer += 2;
				}
				break;
		}
	}

	// on passe au caractère après le '}'
	(*pointer)++;
}

/// va à la fin d'une chaîne de caractères
void CSParser::SkipToEndOfString(const char **pointer, const char *endOfText)
{
	for (;;)
	{
		(*pointer)++;

		while(**pointer != '"')
		{
			if (*pointer >= endOfText)
				return;

			(*pointer)++;
		}

		// on vérifie que c'est pas un \" dans la chaîne
		if (*(*pointer-1) != '\\')
		{
			// on est bien à la fin de la chaîne
			(*pointer)++;
			return;
		}
		// c'était un \"... on continue la boucle infinie
	}
}

unsigned int CSParser::CreateTempString(const char *string,BMallocIO &space)
{
	unsigned int l_Index = space.Position();
	space.Write(string,strlen(string)+1);

	return l_Index;
}

// Parsing
status_t CSParser::Parse(const char *path, bool directory, unsigned int recurse_dirs, bool savePath)
{
	// si on ne veut faire que le parsing d'un fichier, on appelle directement DoFile
	if (directory == false)
		return DoFile(path,savePath);

	// bon, ben à priori c'est un répertoire...
	BDirectory l_Dir(path);

	// on boucle dans son contenu...
	status_t l_Error;
	BEntry l_Entry;
	while ((l_Error = l_Dir.GetNextEntry(&l_Entry,true)) == B_OK)
	{
		BPath l_Path;
		l_Entry.GetPath(&l_Path);
		// est-on tombés sur un répertoire?
		if (l_Entry.IsDirectory())
		{
			// oui... a-t-on le droit d'y aller?
			if (recurse_dirs>0)
			{
				// oui... on y va
				DBG2("On entre dans le répertoire %s\n",l_Path.Path());

				l_Error = Parse(l_Path.Path(),true,recurse_dirs-1,savePath);
				if (l_Error != B_OK)
					return l_Error;
			}
		}
		else
		{
			// non, c'est un fichier. Est-il du bon type?
			BFile l_File(&l_Entry,B_READ_ONLY);
			BNodeInfo l_NodeInfo(&l_File);
			char l_MimeType[B_MIME_TYPE_LENGTH+1];
			l_NodeInfo.GetType(l_MimeType);
			if (strcmp(l_MimeType,"text/x-source-code") == 0)
			{
				// c'est bien un fichier source. ça doit être un header!
				DBG2("On parse le fichier %s\n",l_Path.Path());
				DoFile(l_Path.Path(),savePath);
			}
			else
			{
				DBG2("Le fichier %s n'est pas du bon type\n",l_Path.Path());
			}
		}
	}

	// pourquoi est-on sorti du while?
	// si c'est parce qu'on est arrivés à la fin du répertoire, c'est normal
	if (l_Error == B_ENTRY_NOT_FOUND)
		l_Error = B_OK;

	return l_Error;
}

status_t CSParser::DoFile(const char *path, bool savePath)
{
	BFile l_File(path,B_READ_ONLY);
	if (l_File.InitCheck() != B_OK)
		return l_File.InitCheck();

	// chargement du fichier
	off_t l_Size;
	l_File.GetSize(&l_Size);
	char *l_Text = new char[l_Size];
	if (l_File.Read(l_Text,l_Size) != l_Size)
	{
		delete l_Text;
		return B_ERROR;
	}

	// parsing proprement dit
	time_t l_ModificationTime=0;
	if (savePath)
		l_File.GetModificationTime(&l_ModificationTime);

	status_t l_Error = Parse(l_Text,l_Size,(savePath?path:NULL),l_ModificationTime);

	// on détruit les données qu'on avait chargé
	delete l_Text;
	return l_Error;
}

status_t CSParser::Parse( const char *text, unsigned int textLength, const char *path,time_t modificationTime)
{
	const char *l_Pointer=text,*l_EndOfText = text+textLength;
	BString l_Word;
	bool l_IsOperator;
	status_t l_Error = B_OK;

	while (ExtractWord(l_Word,&l_Pointer,l_EndOfText,&l_IsOperator))
	{
		if (l_IsOperator && l_Word=="#")
		{
			// on est sur un #define, ou #include etc...
			// on passe à la ligne suivante
			SkipToEndOfLine(&l_Pointer,l_EndOfText);
			continue;
		}

		if (!l_IsOperator && l_Word=="class")
		{
			l_Error = DoClass(&l_Pointer,l_EndOfText,path,modificationTime);

			if (l_Error != B_OK)
				return l_Error;
			continue;
		}

		// sinon, ce n'est pas une nouvelle classe... on saute l'instruction
		if (!l_IsOperator)
		{
			SkipToNextInstruction(&l_Pointer,l_EndOfText);
			continue;
		}
	}

	return B_OK;
}

status_t CSParser::DoClass(const char **pointer, const char *endOfText, const char *headerFilePath, time_t modificationTime)
{
	DBG("\n\n****\nDébut de parsing de classe:");

	BString l_Word,l_ClassName;
	bool l_IsOperator;

	// blocs de mémoire qui vont stocker toutes les infos sur la classe
	BMallocIO l_CInfo,l_CMethods,l_CMemberVariables,l_CStrings,l_Friends;
	off_t l_CMethodsOffset=0;	// offset vers l'espace qui stocke la méthode en cours
	unsigned char l_NumFathers = 0, l_NumFriends = 0;
	unsigned short l_NumMemberVariables = 0;
		// compteurs qui seront utilisés par la suite
	// ces deux variables servent à stocker temporairement des entiers sur 8 et 32 bits avant de les stocker dans le fichier
	unsigned int l_TempInt;
	unsigned char l_TempChar;

	// pointeur relatif vers le chemin du fichier (on utilisera ça si headerFilePath est NULL)
	unsigned int l_PointerToPath = 0xffffffff;

	// booléen qui sert à savoir si le fichier a été modifié depuis le dernier parsing
	bool l_FileModified = true;

	// on extrait le nom de la classe
	if (!ExtractWord(l_ClassName,pointer,endOfText,&l_IsOperator) || l_IsOperator)
		// pb. Soit on est à la fin du fichier, soit on est derrière un truc bizarre
	{
		DBG("Erreur: ne peut pas trouver le nom\n");
		return B_ERROR;
	}

	DBG2("nom: %s\n",l_ClassName.String());

	// on regarde si le fichier header a été modifié depuis le dernier parsing
	unsigned int l_ClassPointer = m_ClassNamesList.FindName(l_ClassName.String(),&m_ClassNamesData);
	if (l_ClassPointer != 0xffffffff)
	{
		// on va chercher la date dans le chunk INFO
		l_ClassPointer+= m_BegClassChunk+g_ChunkHeaderSize;
		unsigned int l_Type,l_Size;
		if ((ChunkInfo(l_ClassPointer,&l_Type,&l_Size) && (l_Type == g_CClassInfo)))
		{
			// on va se mettre au bon endroit pour lire la date de modification
			l_ClassPointer += g_ChunkHeaderSize;
			unsigned int l_ModTimePointer = l_ClassPointer+16;

			// on ajoute ce qu'il faut pour les classes père
			unsigned char l_TempByte;
			m_Data->ReadAt(l_ClassPointer+10,&l_TempByte,1);
			l_ModTimePointer += l_TempByte*4;

			// et les classes amies
			m_Data->ReadAt(l_ClassPointer+11,&l_TempByte,1);
			l_ModTimePointer += l_TempByte*4;

			// on vérifie qu'on n'est pas sorti du chunk info (si par exemple on a un fichier de version antérieure à la 6)
			if (l_ModTimePointer-l_ClassPointer+4 <= l_Size)
			{
				if(headerFilePath != NULL)
				{
					// on peut lire la date de modif!
					time_t l_ModTime;
					m_Data->ReadAt(l_ModTimePointer,&l_ModTime,4);

					// alors, faut-il faire la mise à jour?
					if (l_ModTime >= modificationTime)
						// non
						l_FileModified = false;
				}
				else
				{
					// on va lire l'ancien chemin du fichier, et prendre ça quand on stockera la classe
					m_Data->ReadAt(l_ModTimePointer-4,&l_PointerToPath,4);
				}
			}
		}
	}

	// mise en forme du chunk INFO
	l_TempInt = m_ClassNamesList.AddName(l_ClassName.String(),&m_ClassNamesData);
	l_CInfo.Write(&l_TempInt,4);
	l_TempInt = 0xffffffff;	// ce n'est pas un typedef
	l_CInfo.Write(&l_TempInt,4);
	l_TempInt = 0;		// on remplira ces valeurs plus tard
	l_CInfo.Write(&l_TempInt,4);

	// pareil pour le chunk MVRS (variables membres). On remplira ces 4 octets plus tard
	l_CMemberVariables.Write(&l_TempInt,4);

	// on cherche le début de la classe, et les classes dont elle hérite
	while (!l_IsOperator || l_Word != "{")
	{
		if (!ExtractWord(l_Word,pointer,endOfText,&l_IsOperator))
		{
			DBG("Erreur: fin prématurée de la déclaration\n");
			return B_ERROR;
		}

		if (!l_IsOperator && (l_Word != "public"))
		{
			DBG2("Hérite de: %s\n",l_Word.String());

			// héritage
			l_TempInt = m_ClassNamesList.AddName(l_Word.String(),&m_ClassNamesData);
			l_CInfo.Write(&l_TempInt,4);
			l_NumFathers++;
		}

		if (l_IsOperator && l_Word==";")
		{
			DBG("Simple déclaration, pas définition... dommage\n");
			return B_OK;
		}
		else
			if (!l_FileModified)
				// c'est une définition de classe, et le fichier n'a pas été modifié... on sort
				return CSP_NOT_MODIFIED;

		if (l_IsOperator && l_Word=="#")
		{
			// on est sur un #define, ou #include etc...
			// on passe à la ligne suivante
			SkipToEndOfLine(pointer,endOfText);
		}
	}

	// on est au début de la classe!!
	BString l_Type;		// cette chaîne va servir à retenir les types de variables
	BString l_Name;	// et celle-ci les noms (de variables ou de fonction)
	unsigned char l_PointerLevel = 0;
				// cet entier va stocker le niveau de pointeur
	unsigned char l_NumArguments = 0;
				// et celui-là le nombre d'arguments d'une fonction
	unsigned int l_State = 0;
				// et celui-là l'état en cours:
				// 	0: on lit un nom de fonction/variable membre
				//	1: on lit un nom d'argument
				//	2: on lit la valeur par défaut de l'argument
				//	3: c'est la fin de la fonction (on attend un ; ou un {..} )
				//	4: on a lu un 'friend', on attend un 'class'
				//	5: on a lu un 'friend' puis un 'class', on attend le nom de la classe amie
				//	6: on a lu le nom d'une variable membre, on attend un ',' ou un ';'
	unsigned int l_Part = 0;
				// enfin celui-là la partie du nom de fonction ou d'argument qu'on
				// est en train de retirer:
				//	0: on lit le type (de retour pour une fonction)
				//	1: on lit le nom
	unsigned char l_Zone = CSMT_PRIVATE;
				// pour savoir si on est en zone privée/pubique/protégée
	bool l_Virtual = false;
				// mis à true si la méthode qu'on lit en ce moment est virtuelle
	bool l_Const = false;	// mis à true si le type de retour ou de paramètre est constant
	bool l_Ref = false;	// mis à trus si le type de retour ou de paramètre est une référence

	// on boucle jusqu'à ce qu'on arrive à la fin de la classe
	while(!l_IsOperator || (l_Word != "}"))
	{
		if (!ExtractWord(l_Word,pointer,endOfText,&l_IsOperator))
		{
			DBG("Erreur:Fin prématurée...\n");
			return B_ERROR;
		}

		// petite exception pour les mots clefs public, protected et private
		// dans ce cas on note le changement de zone
		if (!l_IsOperator && (l_State==0))
		{
			if (l_Word == "public")
			{
				DBG("Passage en zone publique\n");
				l_Zone = CSMT_PUBLIC;
				continue;
			}
			else if (l_Word == "protected")
			{
				DBG("Passage en zone protégée\n");
				l_Zone = CSMT_PROTECTED;
				continue;
			}
			else if (l_Word == "private")
			{
				DBG("Passage en zone privée\n");
				l_Zone = CSMT_PRIVATE;
				continue;
			}
		}

		// autres mots à ignorer
		if (!l_IsOperator && ((l_Word == "static") || (l_Word == "inline")))
			continue;

		// si c'est un mot, on l'ajoute à ce qu'on est en train de stocker
		if (!l_IsOperator)
		{
			// gestion des mots spéciaux "virtual" et "const"
			if (l_Word == "virtual")
			{
				l_Virtual = true;
				continue;
			}
			if (l_Word == "const")
			{
				l_Const = true;
				continue;
			}

			switch (l_State)
			{
				case 0:
				case 1:
				case 2:
				case 3:
				{
					if (l_Part == 0)
					{
						// gestion des classes amies
						if (l_Word == "friend")
						{
							DBG("Class friend: 4\n");
							l_State = 4;
						}
						else
						{
							// on stocke le type
							l_Type += l_Word;

							// si on a stocké "unsigned", c'est que le vrai type va suivre
							// sinon c'est le nom qui va suivre
							if (l_Word == "unsigned")
								l_Type += " ";
							else
								l_Part = 1;
						}
					}
					else if (l_Part == 1)
					{
						// on stocke le nom
						l_Name += l_Word;
					}
				}
				break;

				// gestion des classes amies... on a vu un 'friend', a-ton un 'class'?
				case 4:
				{
					DBG2("Class friend: 5, trouvé '%s'\n",l_Word.String());
					if (l_Word == "class")
					{
						l_State = 5;
					}
					else
						l_State = 0;
				}
				break;

				// on a eu 'friend class', donc maintenant on a le nom de la classe amie
				case 5:
				{
					// on a un ami!!!!
					DBG2("Class friend: '%s'\n", l_Word.String());

					// on stoque le nom de cette classe amie
					l_TempInt = m_ClassNamesList.AddName(l_Word.String(),&m_ClassNamesData);
					l_Friends.Write(&l_TempInt,4);
					l_NumFriends++;
				}
				break;

				// dans les autres cas, on ne fait rien
				case 6:
				default:
					break;
			}
		}
		else
		{
			// ce n'est pas un mot. c'est un opérateur

			if (l_Word=="#")
			{
				// on est sur un #define, ou #include etc...
				// on passe à la ligne suivante
				SkipToEndOfLine(pointer,endOfText);
				continue;
			}

			//Si c'est un *, ça change le niveau de pointeur, sauf si on redéfinit l'opérateur
			if ((l_Word == "*") && ((l_Part == 0) || (l_Word != "operator")))
			{
				l_PointerLevel++;
				continue;
			}

			if (l_Word == "&")
			{
				l_Ref = true;
				continue;
			}

			// sinon on va voir si ça ne peut pas nous faire changer d'état
			bool l_Clear = false;	// à mettre à true s'il faut effacer Type,Name et PointerLevel
			switch(l_State)
			{
			case 0:
				// 	0: on lit un nom de fonction/variable membre
				if (l_Word == "~")
				{
					// ça doit être un destructeur
					l_Type = "~";
				}
				else if (l_Word == "[")
				{
					// c'est un tableau
					l_Part=2;
						// on ne retient plus les mots qu'on va trouver, puisqu'ils
						// seront la taille du tableau
					l_PointerLevel++;
				}
				else if ((l_Word == ";") || (l_Word == "=") || (l_Word == ","))
				{
					// c'est une variable membre
					DBG2("Variable: %s",l_Name.String());
					DBG2(", type: %s",l_Type.String());
					if (l_Const)
						DBG(" (const)");
					DBG2(", niveau de pointeur: %d\n",(int)l_PointerLevel);

					// on stocke tout ça
					l_TempInt = m_ClassNamesList.AddName(l_Type.String(),&m_ClassNamesData);
					l_CMemberVariables.Write(&l_TempInt,4);
					/// nom
					if (l_Name != B_EMPTY_STRING)
						l_TempInt = CreateTempString(l_Name,l_CStrings);
					else
						l_TempInt = 0xffffffff;
					l_CMemberVariables.Write(&l_TempInt,4);

					// infos diverses
					/// niveau de pointeur
					l_CMemberVariables.Write(&l_PointerLevel,1);

					/// flag const (pas fait encore)
					l_TempChar = (l_Const?1:0);
					l_CMemberVariables.Write(&l_TempChar,1);

					/// zone
					l_CMemberVariables.Write(&l_Zone,1);

					/// réservé
					l_TempChar = 0;
					l_CMemberVariables.Write(&l_TempChar,1);

					l_NumMemberVariables++;

					// maintenant ce qu'il reste dépend de l'opérateur qu'on a vu
					if (l_Word == ";")
					{
						// retour à l'état initial
						l_Clear = true;
					}
					else if (l_Word == ",")
					{
						// il y aura une autre variable
						l_Name=B_EMPTY_STRING;
					}
					else if (l_Word == "=")
					{
						// on donne une valeur par défaut. on attend jusqu'au ',' ou ';' suivant
						l_State=6;
					}
				}
				else if (l_Word == "(")
				{
					// c'est une fonction

					// si c'est un constructeur ou un destructeur, il n'y a pas de
					// type de retour, et le parseur a pris le nom des fonctions
					// pour un type
					if (l_Name == B_EMPTY_STRING)
					{
						l_Name = l_Type;
						l_Type = B_EMPTY_STRING;
					}

					DBG2("Fonction: %s",l_Name.String());
					if (l_Virtual)
						DBG(" (virtual)");
					DBG2(", type de retour: %s",l_Type.String());
					if (l_Const)
						DBG(" (const)");
					if (l_Ref)
						DBG("(&)");
					DBG2(", niveau de pointeur: %d\n",l_PointerLevel);

					// on stocke tout ça
					/// création d'un nouveau chunk
					l_TempInt = g_CClassMethod;
					l_CMethods.Write(&l_TempInt,4);
						// taille encore inconnue
					l_TempInt = 0;
					l_CMethods.Write(&l_TempInt,4);

					/// stockage des autres informations
					l_TempInt = CreateTempString(l_Name,l_CStrings);
					l_CMethods.Write(&l_TempInt,4);
					l_TempInt = m_ClassNamesList.AddName(l_Type.String(),&m_ClassNamesData);
					l_CMethods.Write(&l_TempInt,4);
					l_CMethods.Write(&l_PointerLevel,1);
					/// const et virtual
					l_TempChar = (l_Const?1:0) | (l_Virtual?2:0) | (l_Ref?4:0);
					l_CMethods.Write(&l_TempChar,1);
					/// le nombre d'arguments on ne connait pas encore
					l_TempChar= 0;
					l_CMethods.Write(&l_TempChar,1);
					/// mais la zone on connait
					l_CMethods.Write(&l_Zone,1);

					// passage à l'état 1
					l_State = 1;
					l_Clear = true;
				}
					// gestion du nom spécial 'operator'
				else if ((l_Part == 1) && (l_Name.Compare("operator",8) == 0))
					l_Name += l_Word;
				break;

			case 1:
				//	1: on lit un nom d'argument
				{
					bool l_EndOfArgument = false;
					if (l_Word == ",")
					{
						// fin de l'argument, on passe au suivant
						l_EndOfArgument = true;
						l_Clear = true;
					}
					else if (l_Word == "=")
					{
						// il y a une valeur par défaut
						l_EndOfArgument = true;
						l_State = 2;
						l_Clear = true;
					}
					else if (l_Word == "[")
					{
						// c'est un tableau
						l_Part=2;
							// on ne retient plus les mots qu'on va trouver, puisqu'ils
							// seront la taille du tableau
						l_PointerLevel++;
					}
					else if ((l_Word == ")") || (l_Word == ";") || (l_Word == "}"))
					{
						// c'est le dernier argument de la fonction
						if ((l_Name == "") && (l_Type == ""))
						{
							// en fait la fonction est vide
							DBG("  + fonction vide\n");
						}
						else
							l_EndOfArgument = true;

						// on passe en état 3 (fin de fonction)
						l_State = 3;
						l_Clear = true;
					}

					if (l_EndOfArgument)
					{
						DBG2("  + argument: %s",l_Name.String());
						DBG2(", type: %s",l_Type.String());
						if (l_Const)
							DBG(" (const)");
						if (l_Ref)
							DBG("(&)");
						DBG2(", niveau de pointeur: %d\n",l_PointerLevel);

						// on stocke les infos sur l'argument
						l_TempInt = m_ClassNamesList.AddName(l_Type.String(),&m_ClassNamesData);
						l_CMethods.Write(&l_TempInt,4);
						l_TempInt = CreateTempString(l_Name,l_CStrings);
						l_CMethods.Write(&l_TempInt,4);
						l_TempInt = 0xffffffff;	// la valeur par défaut sera réglée plus tard si nécessaire
						l_CMethods.Write(&l_TempInt,4);
						l_CMethods.Write(&l_PointerLevel,1);
						l_TempChar = (l_Const?1:0) | (l_Ref?2:0);
						l_CMethods.Write(&l_TempChar,1);
							// le reste est à zéro
						l_TempInt = 0;
						l_CMethods.Write(&l_TempInt,2);
						l_NumArguments++;
					}
				}
				break;

			case 2:
				//	2: on lit la valeur par défaut de l'argument
				if (l_Word == ",")
				{
					// on passe à l'argument suivant
					l_State = 1;
					l_Clear = true;
				}
				else if ((l_Word == ")") || (l_Word == ";") || (l_Word == "}"))
				{
					// c'est la fin de la fonction
					l_State = 3;
					l_Clear = true;
				}
				else
				{
					// c'est un opérateur qui rentre dans le calcul de la valeur par défaut
					l_Name << l_Word;
				}

				if (l_Clear)
				{
					l_Type << l_Name;
					DBG2("   + valeur par défaut:%s\n",l_Type.String());

					// pour stocker la valeur par défaut il faut revenir un peu en arrière
					l_CMethods.Seek(-8,SEEK_CUR);
					l_TempInt = CreateTempString(l_Type,l_CStrings);
					l_CMethods.Write(&l_TempInt,4);
					l_CMethods.Seek(4,SEEK_CUR);
				}
				break;

			case 3:
				//	3: c'est la fin de la fonction (on attend un ; ou un {..} )
				if (l_Word == ";")
				{
					// c'est bon, on est à la fin... on repasse à l'état de départ
					l_State = 0;
					l_Clear = true;
				}
				else if (l_Word == "{")
				{
					// la fonction est définie ici... on va à la fin, et on repasse
					// à l'état de départ
					SkipToClosingBracket(pointer,endOfText);
					l_State = 0;
					l_Clear = true;
				}

				if (l_Clear)
				{
					// on est arrivé à la fin de la fonction, il faudrait remettre un peu d'ordre...
					off_t l_EndOfMethod = l_CMethods.Position();

					// mise à jour de la taille du chunk 'METH'
					l_TempInt = l_EndOfMethod - l_CMethodsOffset;
					l_CMethods.WriteAt(l_CMethodsOffset+4,&l_TempInt,4);

					// mise à jour du nombre d'arguments
					l_CMethods.WriteAt(l_CMethodsOffset+g_ChunkHeaderSize+10,&l_NumArguments,1);
					l_NumArguments = 0;

					// et enfin mise à jour de l'offset vers la méthode en cours de décryptage dans
					// le chunk 'METS'
					l_CMethodsOffset = l_EndOfMethod;
				}
				break;

			case 4:
			case 5:
				// on était en train de gérer un 'friend class'
				l_State = 0;
				DBG("Class friend: abandon\n");
				break;

			case 6:
				// on ne sort de cet état qu'avec un ',' ou un ';'
				if (l_Word == ",")
				{
					// il y aura d'autres variables du même type
					l_State=0;
					l_Name=B_EMPTY_STRING;
				}
				else if (l_Word == ";")
				{
					// c'est fini pour cette variable
					l_Clear = true;
					l_State = 0;
				}
				break;

			default:
				DBG("Erreur... je ne sais pas comment je suis arrivé là\n");
				break;
			}

			if (l_Clear)
			{
				l_Type = B_EMPTY_STRING;
				l_Name = B_EMPTY_STRING;
				l_PointerLevel = 0;
				l_Part = 0;
				l_Const = false;
				l_Virtual = false;
			}
		}

	}

	DBG("Fin de la visite de la classe\n");

	// mise à jour du chunk 'INFO'
	/// nombre de classes père
	l_CInfo.WriteAt(10,&l_NumFathers,1);

	/// et nombre d'amis
	l_CInfo.WriteAt(11,&l_NumFriends,1);

	/// les classes amies
	if (l_NumFriends != 0)
	{
		l_CInfo.Write(l_Friends.Buffer(),l_Friends.BufferLength());
	}

	/// le champ qui contient le chemin vers le fichier
	l_CInfo.Seek(0,SEEK_END);
	if (headerFilePath != NULL)
		l_PointerToPath = CreateTempString(headerFilePath,l_CStrings);
	l_CInfo.Write(&l_PointerToPath,4);

	/// la date de modification du fichier header
	l_CInfo.Write(&modificationTime,4);

	// mise à jour du chunk 'MVRS'
	l_CMemberVariables.WriteAt(0,&l_NumMemberVariables,2);

	// et enfin on écrit tous ces chunks dans le fichier, dans un gros chunk 'CLAS'
	/// quelle taille fait tout le chunk?
	unsigned int l_ChunkSize = l_CInfo.Position()+l_CMethods.Position()+l_CMemberVariables.Position()+l_CStrings.Position()+5*g_ChunkHeaderSize;

	/// on prépare l'écriture du chunk
	unsigned int l_Pointer =   ReadyToWriteClass(l_ClassName,l_ChunkSize);

	/// écriture du header
	l_TempInt = g_CClass;
	m_Data->Write(&l_TempInt,4);
	m_Data->Write(&l_ChunkSize,4);

	/// écriture du chunk 'INFO'
	l_TempInt = g_CClassInfo;
	m_Data->Write(&l_TempInt,4);
	l_TempInt = l_CInfo.Position()+g_ChunkHeaderSize;
	m_Data->Write(&l_TempInt,4);
	m_Data->Write(l_CInfo.Buffer(),l_TempInt-g_ChunkHeaderSize);

	/// écriture du chunk 'METS'
	l_TempInt = g_CClassMethodsList;
	m_Data->Write(&l_TempInt,4);
	l_TempInt = l_CMethods.Position()+g_ChunkHeaderSize;
	m_Data->Write(&l_TempInt,4);
	m_Data->Write(l_CMethods.Buffer(),l_TempInt-g_ChunkHeaderSize);

	/// écriture du chunk 'MVRS'
	l_TempInt = g_CClassMemberVariables;
	m_Data->Write(&l_TempInt,4);
	l_TempInt = l_CMemberVariables.Position()+g_ChunkHeaderSize;
	m_Data->Write(&l_TempInt,4);
	m_Data->Write(l_CMemberVariables.Buffer(),l_TempInt-g_ChunkHeaderSize);

	/// écriture du chunk 'STRS'
	l_TempInt = g_CClassStrings;
	m_Data->Write(&l_TempInt,4);
	l_TempInt = l_CStrings.Position()+g_ChunkHeaderSize;
	m_Data->Write(&l_TempInt,4);
	m_Data->Write(l_CStrings.Buffer(),l_TempInt-g_ChunkHeaderSize);

	// mise à jour de la liste de classes, pour qu'elle pointe vers le nouveau chunk 'CLAS' qu'on vient de créer
	m_ClassNamesList.AddName(l_ClassName.String(),&m_ClassNamesData,l_Pointer-m_BegClassChunk);

	return B_OK;
}

unsigned int CSParser::ReadyToWriteClass(BString &className, unsigned int chunkSize)
{
	// la classe existe-t'elle déjà?
	unsigned int l_ClassPosition = m_ClassNamesList.FindName(className.String(),&m_ClassNamesData);
	if (l_ClassPosition == 0xffffffff)
	{
		// elle n'existe pas
		l_ClassPosition = m_EndClassChunk;
		m_Data->Seek(l_ClassPosition,SEEK_SET);

		// la zone liste de classes grandit
		m_EndClassChunk += chunkSize;
	}
	else
	{
		// elle existe...
		// bon, ben on va devoir y aller
		// déjà on récupère la vraie position dans m_Data
		l_ClassPosition += m_BegClassChunk;

		// quelle est la taille actuelle de la classe?
		unsigned int l_CurrentChunkSize;
		m_Data->ReadAt(l_ClassPosition+4,&l_CurrentChunkSize,4);

		// si la classe est déjà à la fin du buffer, ou si elle garde la même taille, on n'a rien à faire
		if ((l_ClassPosition+l_CurrentChunkSize >= m_EndClassChunk) ||
		 (l_CurrentChunkSize == chunkSize))
		 {
			m_Data->Seek(l_ClassPosition,SEEK_SET);
			if (l_CurrentChunkSize != chunkSize)
			{
				// c'est qu'on est à la fin du buffer.
				// si la taille de la classe a diminué... il faut diminuer la taille de la zone
				m_EndClassChunk = l_ClassPosition+chunkSize;
			}
		}
		else
		{
			// on va devoir déplacer les données situées après la classe
			/// allocation du buffer
			/// calcul de la quantité de données à déplacer
			unsigned int l_BufferLength = m_EndClassChunk-l_ClassPosition-l_CurrentChunkSize;
			char *l_Buffer = new char[l_BufferLength];

			/// lecture des données
			m_Data->ReadAt(l_ClassPosition+l_CurrentChunkSize,l_Buffer,l_BufferLength);

			/// écriture à leur nouvelle place
			m_Data->WriteAt(l_ClassPosition+chunkSize,l_Buffer,l_BufferLength);
			m_EndClassChunk = l_ClassPosition+chunkSize+l_BufferLength;

			/// destruction du buffer
			delete l_Buffer;

			// on se place au bon endroit dans le buffer
			m_Data->Seek(l_ClassPosition,SEEK_SET);

			// il faut décaler tous les pointeurs
			m_ClassNamesList.Offset(l_ClassPosition,chunkSize-l_CurrentChunkSize);
		}
	}

	return l_ClassPosition;
}


text:
StateMachine::StateMachine(unsigned char maxStates) :
    _maxStates(maxStates),
    currentState(0),
    _eventGenerated(false),
    _pEventData(NULL)
{
}

// generates an external event. called once per external event
// to start the state machine executing
void StateMachine::ExternalEvent(unsigned char newState,
                                 EventData* pData)
{
    // if we are supposed to ignore this event
    if (newState == EVENT_IGNORED) {
        // just delete the event data, if any
        if (pData)
            delete pData;
    }
    else {
		// TODO - capture software lock here for thread-safety if necessary

        // generate the event and execute the state engine
        InternalEvent(newState, pData);
        StateEngine();

		// TODO - release software lock here
    }
}

// generates an internal event. called from within a state
// function to transition to a new state
void StateMachine::InternalEvent(unsigned char newState,
                                 EventData* pData)
{
	if (pData == NULL)
		pData = new EventData();

    _pEventData = pData;
    _eventGenerated = true;
    currentState = newState;
}

// the state engine executes the state machine states
void StateMachine::StateEngine(void)
{
    EventData* pDataTemp = NULL;

    // while events are being generated keep executing states
    while (_eventGenerated) {
        pDataTemp = _pEventData;  // copy of event data pointer
        _pEventData = NULL;       // event data used up, reset ptr
        _eventGenerated = false;  // event used up, reset flag

        assert(currentState < _maxStates);

		// get state map
        const StateStruct* pStateMap = GetStateMap();

        // execute the state passing in event data, if any
        (this->*pStateMap[currentState].pStateFunc)(pDataTemp);

        // if event data was used, then delete it
        if (pDataTemp) {
            delete pDataTemp;
            pDataTemp = NULL;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package net.tomp2p.p2p;

public interface PeerInit {
    public void init(Peer peer);
}


text:
package com.alibaba.jstorm.message.netty;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import backtype.storm.Config;
import backtype.storm.messaging.IConnection;
import backtype.storm.messaging.IContext;
import backtype.storm.utils.DisruptorQueue;
import backtype.storm.utils.Utils;

import com.alibaba.jstorm.callback.AsyncLoopThread;
import com.alibaba.jstorm.client.ConfigExtension;
import com.alibaba.jstorm.metric.MetricDef;
import com.alibaba.jstorm.utils.JStormUtils;

public class NettyContext implements IContext {
    private final static Logger LOG = LoggerFactory.getLogger(NettyContext.class);
    @SuppressWarnings("rawtypes")
    private Map storm_conf;

    private NioClientSocketChannelFactory clientChannelFactory;

    private ScheduledExecutorService clientScheduleService;
    private final int MAX_CLIENT_SCHEDULER_THREAD_POOL_SIZE = 5;

    private ReconnectRunnable reconnector;

    private boolean isSyncMode = false;

    @SuppressWarnings("unused")
    public NettyContext() {
    }

    /**
     * initialization per Storm configuration
     */
    @SuppressWarnings("rawtypes")
    public void prepare(Map storm_conf) {
        this.storm_conf = storm_conf;

        int maxWorkers = Utils.getInt(storm_conf.get(Config.STORM_MESSAGING_NETTY_CLIENT_WORKER_THREADS));
        ThreadFactory bossFactory = new NettyRenameThreadFactory(MetricDef.NETTY_CLI + "boss");
        ThreadFactory workerFactory = new NettyRenameThreadFactory(MetricDef.NETTY_CLI + "worker");

        if (maxWorkers > 0) {
            clientChannelFactory =
                    new NioClientSocketChannelFactory(Executors.newCachedThreadPool(bossFactory), Executors.newCachedThreadPool(workerFactory), maxWorkers);
        } else {
            clientChannelFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(bossFactory), Executors.newCachedThreadPool(workerFactory));
        }
        int otherWorkers = Utils.getInt(storm_conf.get(Config.TOPOLOGY_WORKERS), 1) - 1;
        int poolSize = Math.min(Math.max(1, otherWorkers), MAX_CLIENT_SCHEDULER_THREAD_POOL_SIZE);
        clientScheduleService = Executors.newScheduledThreadPool(poolSize, new NettyRenameThreadFactory("client-schedule-service"));

        reconnector = new ReconnectRunnable();
        new AsyncLoopThread(reconnector, true, Thread.MIN_PRIORITY, true);

        isSyncMode = ConfigExtension.isNettySyncMode(storm_conf);
    }

    @Override
    public IConnection bind(String topology_id, int port, ConcurrentHashMap<Integer, DisruptorQueue> deserializedQueue,
                            DisruptorQueue recvControlQueue) {
        IConnection retConnection = null;
        try {

            retConnection = new NettyServer(storm_conf, port, isSyncMode, deserializedQueue, recvControlQueue);
        } catch (Throwable e) {
            LOG.error("Failed to instance NettyServer", e.getCause());
            JStormUtils.halt_process(-1, "Failed to bind " + port);
        }

        return retConnection;
    }

    @Override
    public IConnection connect(String topology_id, String host, int port) {
        if (isSyncMode == true) {
            return new NettyClientSync(storm_conf, clientChannelFactory, clientScheduleService, host, port, reconnector);
        } else {
            return new NettyClientAsync(storm_conf, clientChannelFactory, clientScheduleService, host, port, reconnector);
        }
    }

    /**
     * terminate this context
     */
    public void term() {
        clientScheduleService.shutdown();
        // for (IConnection conn : connections) {
        // conn.close();
        // }
        try {
            clientScheduleService.awaitTermination(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            LOG.error("Error when shutting down client scheduler", e);
        }
        // connections = null;

        clientChannelFactory.releaseExternalResources();

        reconnector.shutdown();
    }

}


text:
package com.yammer.metrics.spring;

import com.yammer.metrics.annotation.Gauge;
import com.yammer.metrics.core.MetricName;
import com.yammer.metrics.core.MetricsRegistry;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.FieldCallback;
import org.springframework.util.ReflectionUtils.MethodCallback;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class GaugeAnnotationBeanPostProcessor implements BeanPostProcessor, Ordered {

    private static final Log log = LogFactory.getLog(GaugeAnnotationBeanPostProcessor.class);

    private static final AnnotationFilter filter = new AnnotationFilter(Gauge.class);

    private final MetricsRegistry metrics;
    private final String scope;

    public GaugeAnnotationBeanPostProcessor(final MetricsRegistry metrics, final String scope) {
        this.metrics = metrics;
        this.scope = scope;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException {
        final Class<?> targetClass = AopUtils.getTargetClass(bean);

        ReflectionUtils.doWithFields(targetClass, new FieldCallback() {
            @Override
            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                final Gauge gauge = field.getAnnotation(Gauge.class);
                final String group = MetricName.chooseGroup(gauge.group(), targetClass);
                final String type = MetricName.chooseType(gauge.type(), targetClass);
                final String name = gauge.name().isEmpty() ? field.getName() : gauge.name();
                final MetricName metricName = new MetricName(group, type, name, scope);

                metrics.newGauge(metricName, new GaugeField(bean, field));

                if (log.isDebugEnabled()) {
                    log.debug("Created gauge " + metricName + " for field " + targetClass.getCanonicalName() + "." + field.getName());
                }
            }
        }, filter);

        ReflectionUtils.doWithMethods(targetClass, new MethodCallback() {
            @Override
            public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                if (method.getParameterTypes().length > 0) {
                    throw new IllegalStateException("Method " + method.getName() + " is annotated with @Gauge but requires parameters.");
                }

                final Gauge gauge = method.getAnnotation(Gauge.class);
                final String group = MetricName.chooseGroup(gauge.group(), targetClass);
                final String type = MetricName.chooseType(gauge.type(), targetClass);
                final String name = MetricName.chooseName(gauge.name(), method);
                final MetricName metricName = new MetricName(group, type, name, scope);

                metrics.newGauge(metricName, new GaugeMethod(bean, method));

                if (log.isDebugEnabled()) {
                    log.debug("Created gauge " + metricName + " for method " + targetClass.getCanonicalName() + "." + method.getName());
                }
            }
        }, filter);

        return bean;
    }

    @Override
    public int getOrder() {
        return LOWEST_PRECEDENCE;
    }

}


text:
import processing.core.*;

// All PApplet GUI files will contain this file structure
public class MyPApplet extends PApplet {
  public void setup() {
    // setup code here
    // This code will only work once
  }
  public void draw() {
    // draw code here
    // This code will execute in a loop
  }
}


text:
'use strict';

var sortingState = angular.module( 'sortingState',
[
	'ui.router',
	'projectState',
  //'uiGmapgoogle-maps'
] );

sortingState.config( function( $stateProvider )
{
	$stateProvider.state( 'root.section-state.sorting-state',
	{
		url: '/:sortingType?q?e?p?sub'
	} );
} );


text:
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_HTML_FORMS_HTML_OPTION_ELEMENT_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_FORMS_HTML_OPTION_ELEMENT_H_

#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/dom/events/simulated_click_options.h"
#include "third_party/blink/renderer/core/html/html_element.h"

namespace blink {

class ExceptionState;
class HTMLDataListElement;
class HTMLSelectElement;
class OptionTextObserver;

class CORE_EXPORT HTMLOptionElement final : public HTMLElement {
  DEFINE_WRAPPERTYPEINFO();

 public:
  static HTMLOptionElement* CreateForJSConstructor(
      Document& document,
      const String& data,
      ExceptionState& exception_state) {
    return CreateForJSConstructor(document, data, AtomicString(), false, false,
                                  exception_state);
  }
  static HTMLOptionElement* CreateForJSConstructor(Document&,
                                                   const String& data,
                                                   const AtomicString& value,
                                                   bool default_selected,
                                                   bool selected,
                                                   ExceptionState&);

  explicit HTMLOptionElement(Document&);
  ~HTMLOptionElement() override;
  void Trace(Visitor* visitor) const override;

  // A text to be shown to users.  The difference from |label()| is |label()|
  // returns an empty string if |label| content attribute is empty.
  // |displayLabel()| returns the value string in that case.
  String DisplayLabel() const;

  // |text| IDL attribute implementations.
  String text() const;
  void setText(const String&);

  int index() const;

  String value() const;
  void setValue(const AtomicString&);

  bool Selected() const;
  void SetSelected(bool);
  bool selectedForBinding() const;
  void setSelectedForBinding(bool);

  HTMLDataListElement* OwnerDataListElement() const;
  HTMLSelectElement* OwnerSelectElement() const;

  String label() const;
  void setLabel(const AtomicString&);

  bool OwnElementDisabled() const;

  bool IsDisabledFormControl() const override;
  String DefaultToolTip() const override;

  String TextIndentedToRespectGroupLabel() const;

  // Update 'selectedness'.
  void SetSelectedState(bool);
  // Update 'dirtiness'.
  void SetDirty(bool);

  HTMLFormElement* form() const;
  bool SpatialNavigationFocused() const;

  bool IsDisplayNone() const;

  int ListIndex() const;

  void SetMultiSelectFocusedState(bool);
  bool IsMultiSelectFocused() const;

  void SetWasOptionInsertedCalled(bool flag) {
    was_option_inserted_called_ = flag;
  }
  bool WasOptionInsertedCalled() const { return was_option_inserted_called_; }

  void OptionInsertedIntoSelectMenuElement();
  void OptionRemovedFromSelectMenuElement();

  // Callback for OptionTextObserver.
  void DidChangeTextContent();

 private:
  bool SupportsFocus() const override;
  bool MatchesDefaultPseudoClass() const override;
  bool MatchesEnabledPseudoClass() const override;
  void ParseAttribute(const AttributeModificationParams&) override;
  void AccessKeyAction(SimulatedClickCreationScope) override;
  void ChildrenChanged(const ChildrenChange&) override;

  void DidAddUserAgentShadowRoot(ShadowRoot&) override;

  String CollectOptionInnerText() const;

  void UpdateLabel();

  Member<OptionTextObserver> text_observer_;

  // Represents 'selectedness'.
  // https://html.spec.whatwg.org/C/#concept-option-selectedness
  bool is_selected_;
  // Represents 'dirtiness'.
  // https://html.spec.whatwg.org/C/#concept-option-dirtiness
  bool is_dirty_ = false;
  // Represents the option being focused on in a multi-select non-contiguous
  // traversal via the keyboard.
  bool is_multi_select_focused_ = false;

  // True while HTMLSelectElement::OptionInserted(this) and OptionRemoved(this);
  // This flag is necessary to detect a state where DOM tree is updated and
  // OptionInserted() is not called yet.
  bool was_option_inserted_called_ = false;

  // This flag is necessary to detect when an option is a descendant of
  // <selectmenu> in order to be able to render arbitrary content.
  bool is_descendant_of_select_menu_ = false;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_HTML_FORMS_HTML_OPTION_ELEMENT_H_


text:
using System.Collections.Generic;
using System.Web.Mvc;
using Geolocation.Example.Models;

namespace Geolocation.Example.ViewModels
{
    public class HomeViewModel
    {
        public HomeViewModel()
        {
            Results = new List<ResultModel>();
        }

        public int SelectedRadius { get; set; }

        public IEnumerable<SelectListItem> Radii
        {
            get
            {
                return new List<SelectListItem>
                {
                    new SelectListItem {Text = "5", Value = "5"},
                    new SelectListItem {Text = "10", Value = "10"},
                    new SelectListItem {Text = "25", Value = "25"},
                    new SelectListItem {Text = "100", Value = "100"},
                    new SelectListItem {Text = "500", Value = "500"}
                };
            }
        }

        public DistanceUnit SelectedDistanceUnit { get; set; }

        public IEnumerable<ResultModel> Results { get; set; }
    }
}


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" />
<base href="<?php echo base_url(); ?>" />
<title>:: ###SITE_NAME_UC### ::</title>
<link href="css/admin/style.css" rel="stylesheet" type="text/css" media="screen" />

<? /////////Jquery////// ?>

<?php /*<link  type="text/css" rel="stylesheet" media="screen" href="js/jquery/themes/redmond/jquery.ui.all.css" />*/?>
<link  type="text/css" rel="stylesheet" media="screen" href="js/jquery/themes/ui-darkness/ui.all.css" />
<link  type="text/css" rel="stylesheet" media="screen" href="js/jquery/themes/jquery.ui.tooltip.css" />

<link  type="text/css" rel="stylesheet" media="screen" href="js/jquery/themes/prettyPhoto/prettyPhoto.css" />

<? /////////end Jquery////// ?>

Welcome to ###SITE_NAME_LC### admin panel

  <form id="frm_login" action="" method="post">

            <?php
              show_msg("error");
              echo validation_errors();
            ?>

User Name :

<input id="txt_user_name" name="txt_user_name" value="<?php if(isset($txt_user_name))echo $txt_user_name;?>" type="text" size="34" maxlength="20" />

Password :

<input id="txt_password" name="txt_password" type="password" size="34" maxlength="20" />

<input type="submit" value="Submit" />

	<?php /*?>

<a href="<?php echo admin_base_url()?>forgot_password" style="color:#FFFFFF;text-decoration:none;">Forgot Password?

<?php */?>
  </form>

© 2013 Copyright ###SITE_NAME_LC###


text:
<?php
namespace LolAPI\Service\Summoner\Ver1_4\Runes\DTO;

use LolAPI\Service\Summoner\Ver1_4\Runes\DTO\RuneSlotDto;

class RunePageDto
{
    /**
     * Rune page ID
     * @var int
     */
    private $id;

    /**
     * Indicates if the page is the current page
     * @var bool
     */
    private $current;

    /**
     * Rune page name
     * @var string
     */
    private $name;

    /**
     * Collection of rune slots associated with the rune page
     * @var RuneSlotDto[]
     */
    private $slots;

    function __construct($id, $current, $name, $slots)
    {
        $this->id = $id;
        $this->current = $current;
        $this->name = $name;
        $this->slots = $slots;
    }

    /**
     * Returns rune page ID
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Returns true if the page is the current page
     * @return boolean
     */
    public function isCurrent()
    {
        return $this->current;
    }

    /**
     * Returns rune page name
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Returns collection of rune slots associated with the rune page
     * @return RuneSlotDto[]
     */
    public function getSlots()
    {
        return $this->slots;
    }

    /**
     * Returns true if rune page has slots
     * @return bool
     */
    public function hasSlots()
    {
        return count($this->slots) > 0;
    }
}


text:
package nodes

import (
	"github.com/hashicorp/nomad/api"
	"github.com/jippi/hashi-ui/backend/structs"
)

const (
	Remove = "NOMAD_REMOVE_CLIENT"
)

type remove struct {
	action structs.Action
	client *api.Client
}

func NewRemove(action structs.Action, client *api.Client) *remove {
	return &remove{
		action: action,
		client: client,
	}
}

func (w *remove) Do() (structs.Response, error) {
	ID := w.action.Payload.(string)

	err := w.client.Agent().ForceLeave(ID)
	if err != nil {
		return structs.NewErrorResponse(err)
	}

	return structs.NewSuccessResponse("Successfully force leaved the client")
}

func (w *remove) Key() string {
	return "/node/" + w.action.Payload.(string) + "/remove"
}

func (w *remove) IsMutable() bool {
	return true
}

func (w *remove) BackendType() string {
	return "nomad"
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Injection Workshop</title>

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

            <form class="form-signin">
                <select class="form-control" name="vendor" placeholder="Vendor">
                    <option value="">Select Vendor</option>
                    <option value="HVAC Company">HVAC Company</option>
                    <option value="Electrician">Electrician</option>
                    <option value="Recycling">Recycling</option>
                </select>

                <input class="form-control" name="password" type="password" placeholder="Password">

                <button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
            </form>


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Updater
{
    public partial class FormUpdate : Form
    {
        public FormUpdate()
        {
            InitializeComponent();
        }

        public void Init(String temp)
        {
            label2.Text = temp;
        }

        private void btnAbortUpdate_Click(object sender, EventArgs e)
        {
            this.Close();

        }

        private void FormUpdate_Load(object sender, EventArgs e)
        {

        }
    }
}


text:
"""
Engine feature add on functionality such as default NAT, Antivirus,
File Reputation, etc. These are common settings that are located under
the SMC AddOn or General properties.

Property features will have a common interface allowing you to `enable`,
`disable` and check `status` from the engine reference. When property
features are modified, they are done so against a local copy of the server
intsance. To commit the change, you must call .update() on the engine instance.

For example, to view status of antivirus, given a specific engine::

    engine.antivirus.status

Then enable or disable::

    engine.antivirus.enable()
    engine.antivirus.disable()
    engine.update()

..note:: Engine property settings require that you call engine.update() after
    making / queuing your changes.
"""
from smc.base.model import Element
from smc.base.structs import NestedDict
from smc.elements.profiles import SandboxService, SandboxDataCenter
from smc.base.util import element_resolver

def get_proxy(http_proxy):
    if http_proxy:
        proxies = [element_resolver(proxy) for proxy in http_proxy]
    else:
        proxies = []
    return proxies

class AntiVirus(NestedDict):
    """
    Antivirus settings for the engine. In order to use AV,
    you must also have DNS server addresses configured on
    the engine.

    Enable AV, use a proxy for updates and adjust update
    schedule::

        engine.antivirus.enable()
        engine.antivirus.update_frequency('daily')
        engine.antivirus.update_day('tu')
        engine.antivirus.log_level('transient')
        engine.antivirus.http_proxy('10.0.0.1', proxy_port=8080, user='foo', password='password')
        engine.update()

    :ivar bool antivirus_enabled: is antivirus enabled
    :ivar str antivirus_http_proxy: http proxy settings
    :ivar bool antivirus_http_proxy_enabled: is http proxy enabled
    :ivar int antivirus_proxy_port: http proxy port
    :ivar str antivirus_proxy_user: http proxy user
    :ivar str antivirus_update: how often to update
    :ivar str antivirus_update_day: if update set to weekly, which day to update
    :ivar int antivirus_update_time: time to update av signatures
    :ivar str virus_log_level: antivirus logging level

    .. note:: You must call engine.update() to commit any changes.
    """
    def __init__(self, engine):
        av = engine.data.get('antivirus', {})
        super(AntiVirus, self).__init__(data=av)

    def update_frequency(self, when):
        """
        Set the update frequency. By default this is daily.

        :param str antivirus_update: how often to check for updates. Valid options
            are: 'never','1hour', 'startup', 'daily', 'weekly'
        """
        if when in ('never', '1hour', 'startup', 'daily', 'weekly'):
            self.update(antivirus_update=when)

    def update_day(self, day):
        """
        Update the day when updates should occur.

        :param str day: only used if 'weekly' is specified. Which day
            or week to perform update. Valid options: mo, tu, we, th,
            fr, sa, su.
        """
        if day in ('mo','tu','we','th','fr','sa','su'):
            self.update(antivirus_update_day=day)

    def log_level(self, level):
        """
        Set the log level for antivirus alerting.

        :param str log_level: none,transient,stored,essential,alert
        """
        if level in ('none', 'transient', 'stored' ,'essential','alert'):
            self.update(virus_log_level=level)

    def http_proxy(self, proxy, proxy_port, user=None, password=None):
        """
        .. versionadded:: 0.5.7
            Requires SMC and engine version >= 6.4

        Set http proxy settings for Antivirus updates.

        :param str proxy: proxy IP address
        :param str,int proxy_port: proxy port
        :param str user: optional user for authentication
        """
        self.update(
            antivirus_http_proxy=proxy,
            antivirus_proxy_port=proxy_port,
            antivirus_proxy_user=user if user else '',
            antivirus_proxy_password=password if password else '',
            antivirus_http_proxy_enabled=True)

    def disable(self):
        """
        Disable antivirus on the engine
        """
        self.update(antivirus_enabled=False)

    @property
    def status(self):
        """
        Status of AV on this engine

        :rtype: bool
        """
        return self.get('antivirus_enabled', False)

    def enable(self):
        """
        Enable antivirus on the engine
        """
        self.update(antivirus_enabled=True,
                    virus_mirror='update.nai.com/Products/CommonUpdater' if \
                        not self.get('virus_mirror') else self.virus_mirror,
                    antivirus_update_time=self.antivirus_update_time if \
                        self.get('antivirus_update_time') else 21600000)

    def __repr__(self):
        return '{0}(enabled={1})'.format(
            self.__class__.__name__, self.status)

class FileReputation(NestedDict):
    """
    Configure the engine to use File Reputation capabilities.

    Enable file reputation and specify outbound http proxies for
    queries::

        engine.file_reputation.enable(http_proxy=[HttpProxy('myproxy')])
        engine.update()

    :ivar str file_reputation_context: file reputation context, either
        gti_cloud_only or disabled

    .. note:: You must call engine.update() to commit any changes.
    """
    def __init__(self, engine):
        gti = engine.data.get('gti_settings', {})
        super(FileReputation, self).__init__(data=gti)

    def disable(self):
        """
        Disable any file reputation on the engine.
        """
        self.update(file_reputation_context='disabled')

    @property
    def status(self):
        """
        Return the status of File Reputation on this engine.

        :rtype: bool
        """
        if self.file_reputation_context == 'disabled':
            return False
        return True

    @property
    def http_proxy(self):
        """
        Return any HTTP Proxies that are configured for File
        Reputation.

        :return: list of http proxy instances
        :rtype: list(HttpProxy)
        """
        return [Element.from_href(proxy) for proxy in self.get('http_proxy')]

    def enable(self, http_proxy=None):
        """
        Enable GTI reputation on the engine. If proxy servers
        are needed, provide a list of proxy elements.

        :param http_proxy: list of proxies for GTI connections
        :type http_proxy: list(str,HttpProxy)
        """
        self.update(file_reputation_context='gti_cloud_only',
                    http_proxy=get_proxy(http_proxy))

    def __repr__(self):
        return '{0}(enabled={1})'.format(
            self.__class__.__name__, self.status)

class SidewinderProxy(object):
    """
    Sidewinder status on this engine. Sidewinder proxy can only be
    enabled on specific engine types and also requires SMC and
    engine version >= 6.1.

    Enable Sidewinder proxy::

        engine.sidewinder_proxy.enable()

    .. note:: You must call engine.update() to commit any changes.
    """
    def __init__(self, engine):
        self.engine = engine

    def enable(self):
        """
        Enable Sidewinder proxy on the engine
        """
        self.engine.data['sidewinder_proxy_enabled'] = True

    def disable(self):
        """
        Disable Sidewinder proxy on the engine
        """
        self.engine.data['sidewinder_proxy_enabled'] = False

    @property
    def status(self):
        """
        Status of Sidewinder proxy on this engine

        :rtype: bool
        """
        return self.engine.data['sidewinder_proxy_enabled']

    def __repr__(self):
        return '{0}(enabled={1})'.format(
            self.__class__.__name__, self.status)

class UrlFiltering(NestedDict):
    """
    Enable URL Filtering on the engine.

    Enable Url Filtering with next hop proxies::

        engine.url_filtering.enable(http_proxy=[HttpProxy('myproxy')])
        engine.update()

    Disable Url Filtering::

        engine.url_filtering.disable()
        engine.update()

    .. note:: You must call engine.update() to commit any changes.
    """
    def __init__(self, engine):
        ts = engine.data.get('ts_settings', {})
        super(UrlFiltering, self).__init__(data=ts)

    @property
    def http_proxy(self):
        """
        Return any HTTP Proxies that are configured for Url
        Filtering.

        :return: list of http proxy instances
        :rtype: list(HttpProxy)
        """
        return [Element.from_href(proxy) for proxy in self.get('http_proxy')]

    def enable(self, http_proxy=None):
        """
        Enable URL Filtering on the engine. If proxy servers
        are needed, provide a list of HTTPProxy elements.

        :param http_proxy: list of proxies for GTI connections
        :type http_proxy: list(str,HttpProxy)
        """
        self.update(ts_enabled=True, http_proxy=get_proxy(http_proxy))

    def disable(self):
        """
        Disable URL Filtering on the engine
        """
        self.update(ts_enabled=False)

    @property
    def status(self):
        """
        Return the status of URL Filtering on the engine

        :rtype: bool
        """
        return self.get('ts_enabled', False)

    def __repr__(self):
        return '{0}(enabled={1})'.format(
            self.__class__.__name__, self.status)

class Sandbox(NestedDict):
    """
    Engine based sandbox settings. Sandbox can be configured for
    local (on prem) or cloud based sandbox. To create file filtering
    policies that use sandbox, you must first enable it and
    provide license keys on the engine.

    Enable cloud sandbox on the engine, specifying a proxy for outbound
    connections::

        engine.sandbox.enable(
            license_key='123',
            license_token='456',
            http_proxy=[HttpProxy('myproxy')])

    .. note:: You must call engine.update() to commit any changes.
    """
    def __init__(self, engine):
        self.engine = engine
        sb = engine.data.get('sandbox_settings', {})
        super(Sandbox, self).__init__(data=sb)

    @property
    def status(self):
        """
        Status of sandbox on this engine

        :rtype: bool
        """
        if 'sandbox_type' in self.engine.data:
            if self.engine.sandbox_type == 'none':
                return False
            return True
        return False  # Tmp, attribute missing on newly created engines

    def disable(self):
        """
        Disable the sandbox on this engine.
        """
        self.engine.data.update(sandbox_type='none')
        self.pop('cloud_sandbox_settings', None) #pre-6.3
        self.pop('sandbox_settings', None)

    def enable(self, license_key, license_token,
               sandbox_type='cloud_sandbox', service='Automatic',
               http_proxy=None, sandbox_data_center='Automatic'):
        """
        Enable sandbox on this engine. Provide a valid license key
        and license token obtained from your engine licensing.
        Requires SMC version >= 6.3.

        .. note:: Cloud sandbox is a feature that requires an engine license.

        :param str license_key: license key for specific engine
        :param str license_token: license token for specific engine
        :param str sandbox_type: 'local_sandbox' or 'cloud_sandbox'
        :param str,SandboxService service: a sandbox service element from SMC. The service
            defines which location the engine is in and which data centers to use.
            The default is to use the 'US Data Centers' profile if undefined.
        :param str,SandboxDataCenter sandbox_data_center: sandbox data center to use
            if the service specified does not exist. Requires SMC >= 6.4.3
        :return: None
        """
        service = element_resolver(SandboxService(service), do_raise=False) or \
            element_resolver(SandboxService.create(name=service,
                sandbox_data_center=SandboxDataCenter(sandbox_data_center)))

        self.update(sandbox_license_key=license_key,
                    sandbox_license_token=license_token,
                    sandbox_service=service,
                    http_proxy=get_proxy(http_proxy))

        self.engine.data.setdefault('sandbox_settings', {}).update(self.data)
        self.engine.data.update(sandbox_type=sandbox_type)

    @property
    def http_proxy(self):
        """
        Return any HTTP Proxies that are configured for Sandbox.

        :return: list of http proxy instances
        :rtype: list(HttpProxy)
        """
        return [Element.from_href(proxy) for proxy in self.get('http_proxy')]

    def __repr__(self):
        return '{0}(enabled={1})'.format(
            self.__class__.__name__, self.status)

class TLSInspection(object):
    """
    TLS Inspection settings control settings for doing inbound
    TLS decryption and outbound client TLS decryption. This
    provides an interface to manage TLSServerCredentials and
    TLSClientCredentials assigned to the engine.

    .. note:: You must call engine.update() to commit any changes.
    """
    def __init__(self, engine):
        self.engine = engine

    @property
    def server_credentials(self):
        """
        Return a list of assigned (if any) TLSServerCredentials
        assigned to this engine.

        :rtype: list(TLSServerCredential)
        """
        return [Element.from_href(credential)
                for credential in self.engine.server_credential]

    def add_tls_credential(self, credentials):
        """
        Add a list of TLSServerCredential to this engine.
        TLSServerCredentials can be in element form or can also
        be the href for the element.

        :param credentials: list of pre-created TLSServerCredentials
        :type credentials: list(str,TLSServerCredential)
        :return: None
        """
        for cred in credentials:
            href = element_resolver(cred)
            if href not in self.engine.server_credential:
                self.engine.server_credential.append(href)

    def remove_tls_credential(self, credentials):
        """
        Remove a list of TLSServerCredentials on this engine.

        :param credentials: list of credentials to remove from the
            engine
        :type credentials: list(str,TLSServerCredential)
        :return: None
        """
        for cred in credentials:
            href = element_resolver(cred)
            if href in self.engine.server_credential:
                self.engine.server_credential.remove(href)

'''
class ClientInspection(object):
    def __init__(self, engine):
        self.engine = engine

    @property
    def status(self):
        """
        Whether client based decryption is enabled or disabled.

        :rtype: bool
        """
        return getattr(self.engine, 'tls_client_protection', False)

    def enable(self, client_protection_ca):
        """
        Enable client decryption. Provide a valid client protection
        CA that the engine will use to decrypt.

        :param str,ClientProtectionCA client_protection_ca: href or
            element
        :return: None
        """
        self.engine.data.update(tls_client_protection=
            [{'ca_for_signing_ref': element_resolver(client_protection_ca)}])

    def disable(self):
        pass

    @property
    def client_protection_ca(self):
        """
        Return the Client Protection Certificate Authority assigned
        to this engine. The CA is used to provide decryption services
        to outbound client connections.

        :rtype: ClientProtectionCA
        """
        return Element.from_href(
            self.engine.tls_client_protection)
'''


text:
rootPath = ../..
include ${rootPath}/tests/include.mk

haplotypeSequences=${dataPath}/assemblathon1/simulatedHaplotypes/hap1.trf.repmask.fa.complete ${dataPath}/assemblathon1/simulatedHaplotypes/hap2.trf.repmask.fa.complete ${dataPath}/assemblathon1/simulatedHaplotypes/Escherichia_coliO83_H1_1.trf.repmask.fa.complete
assembliesDir=${dataPath}/tests/big
outputDir=${outputPath}/tests/big

include ${rootPath}/include.mk

all : basic

clean :
	rm -rf ${outputDir}/*


text:
<?php

/**
 * @uses       Zend_Service_WindowsAzure_Exception
 * @uses       Zend_Service_WindowsAzure_Storage_Blob
 * @category   Zend
 * @package    Zend_Service_WindowsAzure_Storage
 * @subpackage Blob
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Service_WindowsAzure_Storage_Blob_Stream
{
    /**
     * Current file name
     *
     * @var string
     */
    private $_fileName = null;

    /**
     * Temporary file name
     *
     * @var string
     */
    private $_temporaryFileName = null;

    /**
     * Temporary file handle
     *
     * @var resource
     */
    private $_temporaryFileHandle = null;

    /**
     * Blob storage client
     *
     * @var Zend_Service_WindowsAzure_Storage_Blob
     */
    private $_storageClient = null;

    /**
     * Write mode?
     *
     * @var boolean
     */
    private $_writeMode = false;

    /**
     * List of blobs
     *
     * @var array
     */
    private $_blobs = null;

    /**
     * Retrieve storage client for this stream type
     *
     * @param string $path
     * @return Zend_Service_WindowsAzure_Storage_Blob
     */
    protected function _getStorageClient($path = '')
    {
        if (is_null($this->_storageClient)) {
            $url = explode(':', $path);
            if (!$url) {
                throw new Zend_Service_WindowsAzure_Exception('Could not parse path "' . $path . '".');
            }

            $this->_storageClient = Zend_Service_WindowsAzure_Storage_Blob::getWrapperClient($url[0]);
            if (!$this->_storageClient) {
                throw new Zend_Service_WindowsAzure_Exception('No storage client registered for stream type "' . $url[0] . '://".');
            }
        }

        return $this->_storageClient;
    }

    /**
     * Extract container name
     *
     * @param string $path
     * @return string
     */
    protected function _getContainerName($path)
    {
        $url = parse_url($path);
        if ($url['host']) {
            return $url['host'];
        }

        return '';
    }

    /**
     * Extract file name
     *
     * @param string $path
     * @return string
     */
    protected function _getFileName($path)
    {
        $url = parse_url($path);
        if ($url['host']) {
            $fileName = isset($url['path']) ? $url['path'] : $url['host'];
    	    if (strpos($fileName, '/') === 0) {
    	        $fileName = substr($fileName, 1);
    	    }
            return $fileName;
        }

        return '';
    }

    /**
     * Open the stream
     *
     * @param  string  $path
     * @param  string  $mode
     * @param  integer $options
     * @param  string  $opened_path
     * @return boolean
     */
    public function stream_open($path, $mode, $options, $opened_path)
    {
        $this->_fileName = $path;
        $this->_temporaryFileName = tempnam(sys_get_temp_dir(), 'azure');

        // Check the file can be opened
        $fh = @fopen($this->_temporaryFileName, $mode);
        if ($fh === false) {
            return false;
        }
        fclose($fh);

        // Write mode?
        if (strpbrk($mode, 'wax+')) {
            $this->_writeMode = true;
    	} else {
            $this->_writeMode = false;
        }

        // If read/append, fetch the file
        if (!$this->_writeMode || strpbrk($mode, 'ra+')) {
            $this->_getStorageClient($this->_fileName)->getBlob(
                $this->_getContainerName($this->_fileName),
                $this->_getFileName($this->_fileName),
                $this->_temporaryFileName
            );
        }

        // Open temporary file handle
        $this->_temporaryFileHandle = fopen($this->_temporaryFileName, $mode);

        // Ok!
        return true;
    }

    /**
     * Close the stream
     *
     * @return void
     */
    public function stream_close()
    {
        @fclose($this->_temporaryFileHandle);

        // Upload the file?
        if ($this->_writeMode) {
            // Make sure the container exists
            $containerExists = $this->_getStorageClient($this->_fileName)->containerExists(
                $this->_getContainerName($this->_fileName)
            );
            if (!$containerExists) {
                $this->_getStorageClient($this->_fileName)->createContainer(
                    $this->_getContainerName($this->_fileName)
                );
            }

            // Upload the file
            try {
                $this->_getStorageClient($this->_fileName)->putBlob(
                    $this->_getContainerName($this->_fileName),
                    $this->_getFileName($this->_fileName),
                    $this->_temporaryFileName
                );
            } catch (Zend_Service_WindowsAzure_Exception $ex) {
                @unlink($this->_temporaryFileName);
                unset($this->_storageClient);

                throw $ex;
            }
        }

        @unlink($this->_temporaryFileName);
        unset($this->_storageClient);
    }

    /**
     * Read from the stream
     *
     * @param  integer $count
     * @return string
     */
    public function stream_read($count)
    {
        if (!$this->_temporaryFileHandle) {
            return false;
        }

        return fread($this->_temporaryFileHandle, $count);
    }

    /**
     * Write to the stream
     *
     * @param  string $data
     * @return integer
     */
    public function stream_write($data)
    {
        if (!$this->_temporaryFileHandle) {
            return 0;
        }

        $len = strlen($data);
        fwrite($this->_temporaryFileHandle, $data, $len);
        return $len;
    }

    /**
     * End of the stream?
     *
     * @return boolean
     */
    public function stream_eof()
    {
        if (!$this->_temporaryFileHandle) {
            return true;
        }

        return feof($this->_temporaryFileHandle);
    }

    /**
     * What is the current read/write position of the stream?
     *
     * @return integer
     */
    public function stream_tell()
    {
        return ftell($this->_temporaryFileHandle);
    }

    /**
     * Update the read/write position of the stream
     *
     * @param  integer $offset
     * @param  integer $whence
     * @return boolean
     */
    public function stream_seek($offset, $whence)
    {
        if (!$this->_temporaryFileHandle) {
            return false;
        }

        return (fseek($this->_temporaryFileHandle, $offset, $whence) === 0);
    }

    /**
     * Flush current cached stream data to storage
     *
     * @return boolean
     */
    public function stream_flush()
    {
        $result = fflush($this->_temporaryFileHandle);

         // Upload the file?
        if ($this->_writeMode) {
            // Make sure the container exists
            $containerExists = $this->_getStorageClient($this->_fileName)->containerExists(
                $this->_getContainerName($this->_fileName)
            );
            if (!$containerExists) {
                $this->_getStorageClient($this->_fileName)->createContainer(
                    $this->_getContainerName($this->_fileName)
                );
            }

            // Upload the file
            try {
                $this->_getStorageClient($this->_fileName)->putBlob(
                    $this->_getContainerName($this->_fileName),
                    $this->_getFileName($this->_fileName),
                    $this->_temporaryFileName
                );
            } catch (Zend_Service_WindowsAzure_Exception $ex) {
                @unlink($this->_temporaryFileName);
                unset($this->_storageClient);

                throw $ex;
            }
        }

        return $result;
    }

    /**
     * Returns data array of stream variables
     *
     * @return array
     */
    public function stream_stat()
    {
        if (!$this->_temporaryFileHandle) {
            return false;
        }

        $stat = array();
        $stat['dev'] = 0;
        $stat['ino'] = 0;
        $stat['mode'] = 0;
        $stat['nlink'] = 0;
        $stat['uid'] = 0;
        $stat['gid'] = 0;
        $stat['rdev'] = 0;
        $stat['size'] = 0;
        $stat['atime'] = 0;
        $stat['mtime'] = 0;
        $stat['ctime'] = 0;
        $stat['blksize'] = 0;
        $stat['blocks'] = 0;

        $info = null;
        try {
            $info = $this->_getStorageClient($this->_fileName)->getBlobInstance(
                        $this->_getContainerName($this->_fileName),
                        $this->_getFileName($this->_fileName)
                    );
        } catch (Zend_Service_WindowsAzure_Exception $ex) {
            // Unexisting file...
        }
        if (!is_null($info)) {
            $stat['size']  = $info->Size;
            $stat['atime'] = time();
        }

        return $stat;
    }

    /**
     * Attempt to delete the item
     *
     * @param  string $path
     * @return boolean
     */
    public function unlink($path)
    {
        $this->_getStorageClient($path)->deleteBlob(
            $this->_getContainerName($path),
            $this->_getFileName($path)
        );
    }

    /**
     * Attempt to rename the item
     *
     * @param  string  $path_from
     * @param  string  $path_to
     * @return boolean False
     */
    public function rename($path_from, $path_to)
    {
        if ($this->_getContainerName($path_from) != $this->_getContainerName($path_to)) {
            throw new Zend_Service_WindowsAzure_Exception('Container name can not be changed.');
        }

        if ($this->_getFileName($path_from) == $this->_getContainerName($path_to)) {
            return true;
        }

        $this->_getStorageClient($path_from)->copyBlob(
            $this->_getContainerName($path_from),
            $this->_getFileName($path_from),
            $this->_getContainerName($path_to),
            $this->_getFileName($path_to)
        );
        $this->_getStorageClient($path_from)->deleteBlob(
            $this->_getContainerName($path_from),
            $this->_getFileName($path_from)
        );
        return true;
    }

    /**
     * Return array of URL variables
     *
     * @param  string $path
     * @param  integer $flags
     * @return array
     */
    public function url_stat($path, $flags)
    {
        $stat = array();
        $stat['dev'] = 0;
        $stat['ino'] = 0;
        $stat['mode'] = 0;
        $stat['nlink'] = 0;
        $stat['uid'] = 0;
        $stat['gid'] = 0;
        $stat['rdev'] = 0;
        $stat['size'] = 0;
        $stat['atime'] = 0;
        $stat['mtime'] = 0;
        $stat['ctime'] = 0;
        $stat['blksize'] = 0;
        $stat['blocks'] = 0;

        $info = null;
        try {
            $info = $this->_getStorageClient($path)->getBlobInstance(
                        $this->_getContainerName($path),
                        $this->_getFileName($path)
                    );
        } catch (Zend_Service_WindowsAzure_Exception $ex) {
            // Unexisting file...
        }
        if (!is_null($info)) {
            $stat['size']  = $info->Size;
            $stat['atime'] = time();
        }

        return $stat;
    }

    /**
     * Create a new directory
     *
     * @param  string  $path
     * @param  integer $mode
     * @param  integer $options
     * @return boolean
     */
    public function mkdir($path, $mode, $options)
    {
        if ($this->_getContainerName($path) == $this->_getFileName($path)) {
            // Create container
            try {
                $this->_getStorageClient($path)->createContainer(
                    $this->_getContainerName($path)
                );
            } catch (Zend_Service_WindowsAzure_Exception $ex) {
                return false;
            }
        } else {
            throw new Zend_Service_WindowsAzure_Exception('mkdir() with multiple levels is not supported on Windows Azure Blob Storage.');
        }
    }

    /**
     * Remove a directory
     *
     * @param  string  $path
     * @param  integer $options
     * @return boolean
     */
    public function rmdir($path, $options)
    {
        if ($this->_getContainerName($path) == $this->_getFileName($path)) {
            // Delete container
            try {
                $this->_getStorageClient($path)->deleteContainer(
                    $this->_getContainerName($path)
                );
            } catch (Zend_Service_WindowsAzure_Exception $ex) {
                return false;
            }
        } else {
            throw new Zend_Service_WindowsAzure_Exception('rmdir() with multiple levels is not supported on Windows Azure Blob Storage.');
        }
    }

    /**
     * Attempt to open a directory
     *
     * @param  string $path
     * @param  integer $options
     * @return boolean
     */
    public function dir_opendir($path, $options)
    {
        $this->_blobs = $this->_getStorageClient($path)->listBlobs(
            $this->_getContainerName($path)
        );
        return is_array($this->_blobs);
    }

    /**
     * Return the next filename in the directory
     *
     * @return string
     */
    public function dir_readdir()
    {
        $object = current($this->_blobs);
        if ($object !== false) {
            next($this->_blobs);
            return $object->Name;
        }
        return false;
    }

    /**
     * Reset the directory pointer
     *
     * @return boolean True
     */
    public function dir_rewinddir()
    {
        reset($this->_blobs);
        return true;
    }

    /**
     * Close a directory
     *
     * @return boolean True
     */
    public function dir_closedir()
    {
        $this->_blobs = null;
        return true;
    }
}