text:
#include "condor_common.h"
#include "condor_debug.h"
#include "condor_config.h"
#include "condor_attributes.h"
#include "condor_state.h"
#include "Set.h"
#include "directory.h"
#include "view_server.h"
#include "extArray.h"

//-------------------------------------------------------------------

// about self

//-------------------------------------------------------------------

int ViewServer::HistoryInterval;
int ViewServer::MaxFileSize;
DataSetInfo ViewServer::DataSet[DataSetCount][HistoryLevels];
int ViewServer::TimeStamp;
int ViewServer::HistoryTimer;
MyString ViewServer::DataFormat[DataSetCount];
AccHash* ViewServer::GroupHash;
bool ViewServer::KeepHistory;
HashTable< MyString, int >* ViewServer::FileHash;
ExtArray< ExtIntArray* >* ViewServer::TimesArray;
ExtArray< ExtOffArray* >* ViewServer::OffsetsArray;

//-----------------------
// Constructor
//------------------------
ViewServer::ViewServer() {}

//-------------------------------------------------------------------
// Initialization
//-------------------------------------------------------------------

// main initialization code... the real main() is in DaemonCore
void ViewServer::Init()
{
	dprintf(D_ALWAYS, "In ViewServer::Init()\n");

	// Check operation mode

	KeepHistory = param_boolean_crufty("KEEP_POOL_HISTORY", false);

	// We can't do this check at compile time, but we'll except if
	// the startd states has changed and we haven't been updated
	// to match
	MSC_SUPPRESS_WARNING(6326) // warning comparing a constant to a constant.
	if ( (int)VIEW_STATE_MAX != (int)_machine_max_state ) {
		EXCEPT( "_max_state=%d (from condor_state.h) doesn't match "
				" VIEW_STATE_MAX=%d (from view_server.h)",
				(int)_machine_max_state, (int)VIEW_STATE_MAX );
	}

	// Initialize collector daemon

	CollectorDaemon::Init();
	if (!KeepHistory) return;

	// install command handlers for queries

    daemonCore->Register_Command(QUERY_HIST_STARTD,"QUERY_HIST_STARTD",
        (CommandHandler)ReceiveHistoryQuery,"ReceiveHistoryQuery",NULL,READ);
    daemonCore->Register_Command(QUERY_HIST_STARTD_LIST,"QUERY_HIST_STARTD_LIST",
        (CommandHandler)ReceiveHistoryQuery,"ReceiveHistoryQuery",NULL,READ);
    daemonCore->Register_Command(QUERY_HIST_SUBMITTOR,"QUERY_HIST_SUBMITTOR",
        (CommandHandler)ReceiveHistoryQuery,"ReceiveHistoryQuery",NULL,READ);
    daemonCore->Register_Command(QUERY_HIST_SUBMITTOR_LIST,"QUERY_HIST_SUBMITTOR_LIST",
        (CommandHandler)ReceiveHistoryQuery,"ReceiveHistoryQuery",NULL,READ);
    daemonCore->Register_Command(QUERY_HIST_SUBMITTORGROUPS,"QUERY_HIST_SUBMITTORGROUPS",
        (CommandHandler)ReceiveHistoryQuery,"ReceiveHistoryQuery",NULL,READ);
    daemonCore->Register_Command(QUERY_HIST_SUBMITTORGROUPS_LIST,"QUERY_HIST_SUBMITTORGROUPS_LIST",
        (CommandHandler)ReceiveHistoryQuery,"ReceiveHistoryQuery",NULL,READ);
    daemonCore->Register_Command(QUERY_HIST_GROUPS,"QUERY_HIST_GROUPS",
        (CommandHandler)ReceiveHistoryQuery,"ReceiveHistoryQuery",NULL,READ);
    daemonCore->Register_Command(QUERY_HIST_GROUPS_LIST,"QUERY_HIST_GROUPS_LIST",
        (CommandHandler)ReceiveHistoryQuery,"ReceiveHistoryQuery",NULL,READ);
    daemonCore->Register_Command(QUERY_HIST_CKPTSRVR,"QUERY_HIST_CKPTSRVR",
        (CommandHandler)ReceiveHistoryQuery,"ReceiveHistoryQuery",NULL,READ);
    daemonCore->Register_Command(QUERY_HIST_CKPTSRVR_LIST,"QUERY_HIST_CKPTSRVR_LIST",
        (CommandHandler)ReceiveHistoryQuery,"ReceiveHistoryQuery",NULL,READ);

	int InitialDelay=param_integer("UPDATE_INTERVAL",300);

	// Add View Server Flag to class ad
	ad->Insert("ViewServer = True");

	// Register timer for logging information to history files
	HistoryTimer = daemonCore->Register_Timer(InitialDelay,HistoryInterval,
		WriteHistory,"WriteHistory");

	// Initialize hash tables

	for (int i=0; i<DataSetCount; i++) {
		for (int j=0; j<HistoryLevels; j++) {
			DataSet[i][j].AccData=new AccHash(1000,MyStringHash);
		}
	}
	GroupHash = new AccHash(100,MyStringHash);
	FileHash = new HashTable< MyString, int >(100,MyStringHash);
	OffsetsArray = new ExtArray< ExtOffArray* >(30);
	TimesArray = new ExtArray< ExtIntArray* >(30);

	// File data format

	DataFormat[SubmittorData]="%d\t%s\t:\t%.0f\t%.0f\n";
	DataFormat[SubmittorGroupsData]="%d\t%s\t:\t%.0f\t%.0f\n";
	DataFormat[StartdData]="%d\t%s\t:\t%.0f\t%7.3f\t%.0f\n";
	DataFormat[GroupsData]="%d\t%s\t:\t%.1f\t%.1f\t%.1f\t%.1f\t%.1f\t%.1f\t%.1f\t%.1f\t%.1f\n";
	DataFormat[CkptData]="%d\t%s\t:\t%.3f\t%.3f\t%.3f\t%.3f\n";

	return;
}

//-------------------------------------------------------------------
// Read configuration
//-------------------------------------------------------------------

void ViewServer::Config()
{
	string history_dir_buf;
	char const *history_dir;
	char* tmp;
	dprintf(D_ALWAYS, "In ViewServer::Config()\n");

	// Configure Collector daemon

	CollectorDaemon::Config();
	if (!KeepHistory) return;

	// Specialized configuration

	HistoryInterval=param_integer("POOL_HISTORY_SAMPLING_INTERVAL",60);

	int MaxStorage=param_integer("POOL_HISTORY_MAX_STORAGE",10000000);

	MaxFileSize=MaxStorage/(HistoryLevels*DataSetCount*2);

	tmp=param("POOL_HISTORY_DIR");
	if (!tmp) {
		tmp=param("LOCAL_DIR");
		if (!tmp) {
			EXCEPT("No POOL_HISTORY_DIR or LOCAL_DIR directory specified in config file");
		}
		formatstr(history_dir_buf, "%s/ViewHist", tmp);
	}
	else {
		history_dir_buf = tmp;
	}
	history_dir = history_dir_buf.c_str();
	free(tmp);

	dprintf(D_ALWAYS, "Configuration: SAMPLING_INTERVAL=%d, MAX_STORAGE=%d, MaxFileSize=%d, POOL_HISTORY_DIR=%s\n",HistoryInterval,MaxStorage,MaxFileSize,history_dir);

	if(!IsDirectory(history_dir)) {
		EXCEPT("POOL_HISTORY_DIR (%s) does not exist.",history_dir);
	}

	for (int i=0; i<DataSetCount; i++) {
		for (int j=0; j<HistoryLevels; j++) {
			DataSet[i][j].MaxSamples=4*((int) pow((double)4,(double)j));
			DataSet[i][j].NumSamples=0;
			DataSet[i][j].OldFileName.formatstr("%s/viewhist%d.%d.old",history_dir,i,j);
			DataSet[i][j].OldStartTime=FindFileStartTime(DataSet[i][j].OldFileName.Value());
			DataSet[i][j].NewFileName.formatstr("%s/viewhist%d.%d.new",history_dir,i,j);
			DataSet[i][j].NewStartTime=FindFileStartTime(DataSet[i][j].NewFileName.Value());
		}
	}

	return;
}

//-------------------------------------------------------------------
// Fast shutdown
//-------------------------------------------------------------------

void ViewServer::Exit()
{
	CollectorDaemon::Exit();
	return;
}

//-------------------------------------------------------------------
// Gracefull shutdown
//-------------------------------------------------------------------

void ViewServer::Shutdown()
{
	CollectorDaemon::Shutdown();
	return;
}

//-------------------------------------------------------------------
// Receive the query parameters from the socket, then call
// HandleQuery to take care of replying to the query
//-------------------------------------------------------------------

int ViewServer::ReceiveHistoryQuery(Service* /*s*/, int command, Stream* sock)
{
	dprintf(D_ALWAYS,"Got history query %d\n",command);

	int FromDate, ToDate, Options;
	char *Line = NULL;

	// Read query parameters

	sock->decode();
	if (!sock->code(FromDate) ||
	    !sock->code(ToDate) ||
	    !sock->code(Options) ||
	    !sock->get(Line) ||
	    !sock->end_of_message()) {
		dprintf(D_ALWAYS,"Can't receive history query!\n");
		free( Line );
		return 1;
	}

	dprintf(D_ALWAYS, "Got history query: FromDate=%d, ToDate=%d, Type=%d, Arg=%s\n",FromDate,ToDate,command,Line);

	// Reply to query

	sock->encode();

	HandleQuery(sock,command,FromDate,ToDate,Options,Line);

	free( Line );

	if (!sock->put("") ||
	    !sock->end_of_message()) {
		dprintf(D_ALWAYS,"Can't send information to client!\n");
		return 1;
	}

	return 0;
}

//-------------------------------------------------------------------
// Decide which files to get the data from, and call the
// appropriate function to send the data
//-------------------------------------------------------------------

int ViewServer::HandleQuery(Stream* sock, int command, int FromDate, int ToDate, int Options, MyString Arg)
{
	int DataSetIdx=-1;
	int ListFlag=0;

	// Find out which data set type

	switch(command) {
		case QUERY_HIST_STARTD_LIST:			ListFlag=1;
		case QUERY_HIST_STARTD:					DataSetIdx=StartdData;
												break;
		case QUERY_HIST_SUBMITTOR_LIST: 		ListFlag=1;
		case QUERY_HIST_SUBMITTOR:				DataSetIdx=SubmittorData;
												break;
		case QUERY_HIST_SUBMITTORGROUPS_LIST:	ListFlag=1;
		case QUERY_HIST_SUBMITTORGROUPS:		DataSetIdx=SubmittorGroupsData;
												break;
		case QUERY_HIST_GROUPS_LIST:			ListFlag=1;
		case QUERY_HIST_GROUPS:					DataSetIdx=GroupsData;
												break;
		case QUERY_HIST_CKPTSRVR_LIST:			ListFlag=1;
		case QUERY_HIST_CKPTSRVR:				DataSetIdx=CkptData;
												break;
	}

	if (DataSetIdx==-1) return -1; // Illegal command

	// find out which level

	int HistoryLevel=-1;
	int OldFlag=1, NewFlag=1;

	for (int j=0; j<HistoryLevels; j++) {
		if (FromDate>=DataSet[DataSetIdx][j].NewStartTime && DataSet[DataSetIdx][j].NewStartTime!=-1) {
			HistoryLevel=j;
			OldFlag=0;
			break;
		}
		else if (FromDate>=DataSet[DataSetIdx][j].OldStartTime && DataSet[DataSetIdx][j].OldStartTime!=-1) {
			HistoryLevel=j;
			if (ToDate<DataSet[DataSetIdx][j].NewStartTime) NewFlag=0;
			break;
		}
	}

	if (HistoryLevel==-1) {
		int LevelStartTime;
		int MinStartTime=-1;
		for (int j=0; j<HistoryLevels; j++) {
			LevelStartTime=DataSet[DataSetIdx][j].OldStartTime;
			if (LevelStartTime==-1) LevelStartTime=DataSet[DataSetIdx][j].NewStartTime;
			if (LevelStartTime!=-1) {
				if (LevelStartTime<MinStartTime || MinStartTime==-1) {
					MinStartTime=LevelStartTime;
					HistoryLevel=j;
				}
			}
		}
	}

	dprintf(D_ALWAYS,"DataSetIdx=%d, HistoryLevel=%d, OldFlag=%d, NewFlag=%d\n",DataSetIdx,HistoryLevel,OldFlag,NewFlag);
	if (HistoryLevel==-1) return 0;
	dprintf(D_ALWAYS,"OldStartTime=%d , NewStartTime=%d\n",DataSet[DataSetIdx][HistoryLevel].OldStartTime,DataSet[DataSetIdx][HistoryLevel].NewStartTime);

	// Read file and send Data

	if (ListFlag) {
		Set<MyString> Names;
		if (OldFlag) SendListReply(sock, DataSet[DataSetIdx][HistoryLevel].OldFileName,FromDate,ToDate,Names);
		if (NewFlag) SendListReply(sock, DataSet[DataSetIdx][HistoryLevel].NewFileName,FromDate,ToDate,Names);
	} else {
		if (OldFlag) SendDataReply(sock, DataSet[DataSetIdx][HistoryLevel].OldFileName,FromDate,ToDate,Options,Arg);
		if (NewFlag) SendDataReply(sock, DataSet[DataSetIdx][HistoryLevel].NewFileName,FromDate,ToDate,Options,Arg);
	}

	return 0;
}

//---------------------------------------------------------------------
// Send the list of names from the specified file for the
// requested time range
//---------------------------------------------------------------------

int ViewServer::SendListReply(Stream* sock,const MyString& FileName, int FromDate, int ToDate, Set<MyString>& Names)
{
	char InpLine[200];
	char OutLine[200];
	char* OutLinePtr=OutLine;
	MyString Arg;
	int T = 0;
	int file_array_index;
	ExtIntArray* times_array = NULL;
	ExtOffArray* offsets = NULL;
	// dprintf(D_ALWAYS, "Caches found=%d, looking for correct one...\n", TimesArray->length());

		// first find out which ExtArray to use, by checking the hash
	if( FileHash->lookup( FileName, file_array_index ) == -1 ){

			// FileName was not found in the FileHash
			// Create the necessary arrays and set the index appropriately
		// dprintf(D_ALWAYS, "No cache found for this file, generating new one...\n");
		times_array = new ExtIntArray(100);
		offsets = new ExtOffArray(100);
		file_array_index = OffsetsArray->length();
		FileHash->insert( FileName, file_array_index );
		TimesArray->add( times_array );
		OffsetsArray->add( offsets );
	} else {

			// otherwise just get the appropriate array
		times_array = (TimesArray->getElementAt( file_array_index ));
		offsets = (OffsetsArray->getElementAt( file_array_index ));
		// dprintf(D_ALWAYS, "Cache found for this file, %d indices\n", offsets->length());
	}

	// dprintf(D_ALWAYS,"Filename=%s\n",(const char*)FileName);
	FILE* fp=safe_fopen_wrapper_follow(FileName.Value(),"r");
	if (!fp) return -1;

		//find the offset to search at
	fpos_t* search_offset = findOffset(fp, FromDate, ToDate, times_array, offsets);
	if(search_offset != NULL) {
			// set the seek to the correct spot and begin searching the file
		if(fsetpos(fp, search_offset) < 0) {
				// something failed, so get out of here
			fclose(fp);
			return -1;
		}
	}

	int new_offset_counter = 1;		// every fifty loops, mark an offset
	while(fgets(InpLine,sizeof(InpLine),fp)) {

		// dprintf(D_ALWAYS,"Line read: %s\n",InpLine);
		T=ReadTimeAndName(InpLine,Arg);
		// dprintf(D_ALWAYS,"T=%d\n",T);
		if( times_array->length() < offsets->length() ) {
				// a file offset was recorded before this line was read; now
				// store the time that was on the marked line
			// dprintf(D_ALWAYS, "Adding time=%d to the cache", T);
			times_array->add( T );
		}

		if (T>ToDate) break;
		if (T<FromDate) {
				// continue to the next loop; but first, if 50 times have been
				// checked, mark the position in the file and the time
			addNewOffset(fp, new_offset_counter, T, times_array, offsets);
			continue;
		}

		if (!Names.Exist(Arg)) {
			// dprintf(D_ALWAYS,"Adding Name=%s\n",Arg.Value());
			Names.Add(Arg);
			sprintf(OutLinePtr,"%s\n",Arg.Value());
			if (!sock->code(OutLinePtr)) {
				dprintf(D_ALWAYS,"Can't send information to client!\n");
				fclose(fp);
				return -1;
			}
		}
		addNewOffset(fp, new_offset_counter, T, times_array, offsets);
	}

	fclose(fp);
	return 0;
}

int ViewServer::SendDataReply(Stream* sock,const MyString& FileName, int FromDate, int ToDate, int Options, const MyString& Arg)
{
	char InpLine[200];
	char* InpLinePtr=InpLine;
	char OutLine[200];
	char* OutLinePtr=OutLine;
	char* tmp;
	int Status=0;
	int NewTime, OldTime;
	float OutTime;
	int T = 0;
	int file_array_index;
	ExtIntArray* times_array = NULL;
	ExtOffArray* offsets = NULL;
	// dprintf(D_ALWAYS, "Caches found=%d, looking for correct one...\n", TimesArray->length());

		// first find out which ExtArray to use, by checking the hash
	if( FileHash->lookup( FileName, file_array_index ) == -1 ){

			// FileName was not found in the FileHash
			// Create the necessary arrays and set the index appropriately
		// dprintf(D_ALWAYS, "No cache found for this file, generating new one...\n");
		times_array = new ExtIntArray(100);
		offsets = new ExtOffArray(100);
		file_array_index = OffsetsArray->length();
		FileHash->insert( FileName, file_array_index );
		TimesArray->add( times_array );
		OffsetsArray->add( offsets );
	} else {

			// otherwise just get the appropriate array
		times_array = (TimesArray->getElementAt( file_array_index ));
		offsets = (OffsetsArray->getElementAt( file_array_index ));
		// dprintf(D_ALWAYS, "Cache found for this file, %d indices\n", times_array->length());
	}

	OldTime = 0;
	FILE* fp=safe_fopen_wrapper_follow(FileName.Value(),"r");
	if (!fp) return -1;

		//find the offset to search at
	fpos_t* search_offset = findOffset(fp, FromDate, ToDate, times_array, offsets);
	if(search_offset != NULL) {
			// set the seek to the correct spot and begin searching the file
		if(fsetpos(fp, search_offset) < 0) {
				// something failed, so get out of here
			fclose(fp);
			return -1;
		}
	}

	int new_offset_counter = 1;		// every fifty loops, mark an offset
	while(fgets(InpLine,sizeof(InpLine),fp)) {

		// dprintf(D_ALWAYS,"Line read: %s\n",InpLine);
		T=ReadTimeChkName(InpLine,Arg);
		if( times_array->length() < offsets->length() ) {
				// a file offset was recorded before this line was read; now
				// store the time that was on the marked line
			// dprintf(D_ALWAYS, "Adding time=%d to the cache", T);
			times_array->add( T );
		}
		// dprintf(D_ALWAYS,"T=%d\n",T);

		if (T>ToDate) break;
		if (T<FromDate) {
				// continue to the next loop; but first, if 50 times have been
				// checked, mark the position in the file and the time
			addNewOffset(fp, new_offset_counter, T, times_array, offsets);
			continue;
		}

		if (Options) {
			if (!sock->code(InpLinePtr)) {
				dprintf(D_ALWAYS,"Can't send information to client!\n");
				Status=-1;
				break;
			}
		}
		else {
			tmp=strchr(InpLine,':');
			OutTime=float(T-FromDate)/float(ToDate-FromDate);
			NewTime=(int)rint(1000*OutTime);
			if (NewTime==OldTime) continue;
            OldTime=NewTime;
			sprintf(OutLinePtr,"%.2f%s",OutTime*100,tmp+1);
			if (!sock->code(OutLinePtr)) {
				dprintf(D_ALWAYS,"Can't send information to client!\n");
				Status=-1;
				break;
			}
		}
		addNewOffset(fp, new_offset_counter, T, times_array, offsets);
	}

	fclose(fp);
	return Status;
}

//*******************************************************************
// Utility files for recording offsets in the condor_stats files.
//*******************************************************************

//-------------------------------------------------------------------
// Increments the counter, and then if it's reached 50, adds the
// offset to the list.
//-------------------------------------------------------------------

void
ViewServer::addNewOffset(FILE* &fp, int &offset_ctr, int read_time, ExtIntArray* times_array, ExtOffArray* offsets) {
	if( ++offset_ctr == 50) {
		offset_ctr = 0;
		if(times_array->length() == 0 || read_time > times_array->getElementAt( times_array->getlast() )) {
				// mark the position in the file now, but wait to mark the time
				// until after the line is read
			// dprintf(D_ALWAYS, "Adding new offset to the cache\n");
			fpos_t *tmp_offset_ptr = new fpos_t;
			fgetpos(fp, tmp_offset_ptr);
			offsets->add(tmp_offset_ptr);
		} else {
			// dprintf(D_ALWAYS, "I would mark an offset, but it would most likely be a duplicate.\n");
		}
	}
}

//-------------------------------------------------------------------
// Sets the offset to the appropriate spot in the file to minimize
// linear searching of the file.
//-------------------------------------------------------------------

fpos_t*
ViewServer::findOffset(FILE* & /*fp*/, int FromDate, int ToDate, ExtIntArray* times_array, ExtOffArray* offsets) {
	fpos_t* search_offset_ptr = NULL;
	if( times_array->length() == 0 ) {

			// linear progression, return null to inform the rest of the code
			// to start at the beginning
		// dprintf(D_ALWAYS, "No cache, starting at the beginning of the file...\n");
		return NULL;

	} else if( times_array->getElementAt( 0 ) > FromDate ) {

		if( times_array->getElementAt( 0 ) > ToDate ) {
				// if this is the case then the record won't be found, so end
			// dprintf(D_ALWAYS, "Impossible request\n");
			return NULL;
		} else {
				// this file begins in the middle of the requested interval, so
				// start at the beginning of the file.
			// dprintf(D_ALWAYS, "Carrying over from previous file at the beginning\n");
			return NULL;
		}

	} else if( times_array->getElementAt( times_array->getlast() ) < FromDate ) {

			// linear progression, but start with the latest known offset
		// dprintf(D_ALWAYS, "Requesting time at the end of where the current cache knows\n");
		search_offset_ptr = offsets->getElementAt( offsets->getlast() );

	} else {

			// binary search through times_array[] for the latest time not
			// greater than FromDate
		// dprintf(D_ALWAYS, "Binary searching the cache table, request should be quick\n");
		int low = 0;
		int high = times_array->getlast();
		int mid;
		while( high - low > 1 ) {
			mid = (high - low) / 2 + low;
			if( times_array->getElementAt( mid ) < FromDate ) {
				low = mid;
			} else {
				high = mid;
			}
		}
			// now we've found the approximate spot in the array; time to find
			// the exact location and set the appropriate offset
		if( times_array->getElementAt( low + 1 ) < FromDate ) {
			search_offset_ptr = offsets->getElementAt( low + 1 );
		} else if( times_array->getElementAt( low ) < FromDate ) {
			search_offset_ptr = offsets->getElementAt( low );
		} else {
			return NULL;
		}
	}
	return search_offset_ptr;
}

//*******************************************************************
// Utility functions for reading the history files & data
//*******************************************************************

//-------------------------------------------------------------------
// Read the first entry to decide the time of the earliest entry
// in the file
//-------------------------------------------------------------------

int ViewServer::FindFileStartTime(const char *Name)
{
	char Line[200];
	int T=-1;
	FILE* fp=safe_fopen_wrapper_follow(Name,"r");
	if (fp) {
		if (fgets(Line,sizeof(Line),fp)) {
			T=ReadTime(Line);
		} else {
			T=-1; // fgets failed, return -1 instead of parsing uninit memory
			dprintf(D_ALWAYS, "Failed to parse first line of %s\n", Name);
		}
		fclose(fp);
	}
	dprintf(D_ALWAYS,"FileName=%s , StartTime=%d\n",Name,T);
	return T;
}

//-------------------------------------------------------------------
// Parse the entry time from the line
//-------------------------------------------------------------------

int ViewServer::ReadTime(char* Line)
{
	int t=-1;
	if (sscanf(Line,"%d",&t)!=1) return -1;
	return t;
}

//-------------------------------------------------------------------
// Parse the entry time and name from the line
//-------------------------------------------------------------------

int ViewServer::ReadTimeAndName(char* Line, MyString& Name)
{
	int t=-1;
	char tmp[100];
	if (sscanf(Line,"%d %s",&t,tmp)!=2) return -1;
	Name=tmp;
	return t;
}

//-------------------------------------------------------------------
// Parse the time and check for the specified name
//-------------------------------------------------------------------

int ViewServer::ReadTimeChkName(char* Line, const MyString& Name)
{
	int t=-1;
	char tmp[100];
	if (sscanf(Line,"%d %s",&t,tmp)!=2) return -1;
	if (Name!="*" && Name!=MyString(tmp)) return -1;
	return t;
}

//*********************************************************************
// History file writing functions
//*********************************************************************

//---------------------------------------------------------------------
// Scan function for submittor data
//---------------------------------------------------------------------

void ViewServer::WriteHistory()
{
	MyString Key;
	GeneralRecord* GenRec;
	FILE* DataFile;
	struct stat statbuf;
	char OutLine[200];

	// Accumulate data

	TimeStamp=time(0);

	dprintf(D_ALWAYS,"Accumulating data: Time=%d\n",TimeStamp);

	if (!collector.walkHashTable(SUBMITTOR_AD, SubmittorScanFunc)) {
		dprintf (D_ALWAYS, "Error accumulating data\n");
		return;
	}
	SubmittorTotalFunc();

	if (!collector.walkHashTable(STARTD_AD, StartdScanFunc)) {
		dprintf (D_ALWAYS, "Error accumulating data\n");
		return;
	}
	StartdTotalFunc();
	if (!collector.walkHashTable(CKPT_SRVR_AD, CkptScanFunc)) {
		dprintf (D_ALWAYS, "Error accumulating data\n");
		return;
	}

	// Write to history files

	for (int i=0; i<DataSetCount; i++) {

		for (int j=0; j<HistoryLevels; j++) {

			// Open files for writing

			DataSet[i][j].NumSamples++;
			if (DataSet[i][j].NumSamples<DataSet[i][j].MaxSamples) continue;
			DataSet[i][j].NumSamples=0;
			dprintf(D_FULLDEBUG,"Openning file %s\n",DataSet[i][j].NewFileName.Value());
			DataFile=safe_fopen_wrapper_follow(DataSet[i][j].NewFileName.Value(),"a");
			if (!DataFile) {
				dprintf(D_ALWAYS,"Could not open data file %s for appending!!! errno=%d\n",DataSet[i][j].NewFileName.Value(),errno);
				EXCEPT("Could not open data file appending!!!");
			}

			// Iterate through accumulated values

			DataSet[i][j].AccData->startIterations();
			while(DataSet[i][j].AccData->iterate(Key,GenRec)) {
				sprintf(OutLine,DataFormat[i].Value(),TimeStamp,Key.Value(),GenRec->Data[0],GenRec->Data[1],GenRec->Data[2],GenRec->Data[3],GenRec->Data[4],GenRec->Data[5],GenRec->Data[6], GenRec->Data[7], GenRec->Data[8]);
				delete GenRec;
				fputs(OutLine, DataFile);
			}

			// Clear accumulated values

			DataSet[i][j].AccData->clear();

			// close file

			fclose(DataFile);
			dprintf(D_FULLDEBUG,"Closing file %s\n",DataSet[i][j].NewFileName.Value());

			// Update file start time

			if (DataSet[i][j].NewStartTime==-1) DataSet[i][j].NewStartTime=TimeStamp;

			// Check for size limitation and take necessary action

			if (stat(DataSet[i][j].NewFileName.Value(),&statbuf)) {
				dprintf(D_ALWAYS,"Could not check data file %s size!!! errno=%d\n",DataSet[i][j].NewFileName.Value(),errno);
				EXCEPT("Could not check data file size!!!");
			}
			if (statbuf.st_size>MaxFileSize) {
				rename(DataSet[i][j].NewFileName.Value(),DataSet[i][j].OldFileName.Value());
				int newFileIndex = -1;
				int oldFileIndex = -1;
				if(FileHash->lookup(DataSet[i][j].OldFileName.Value(),
														oldFileIndex) != -1) {
						// get rid of the old arrays and make new ones
					delete (*TimesArray)[oldFileIndex];
					int iter;
					for(iter = 0; iter < (*(*OffsetsArray)[oldFileIndex]).length(); iter++) {
						delete (*(*OffsetsArray)[oldFileIndex])[iter];
					}
					delete (*OffsetsArray)[oldFileIndex];
					(*TimesArray)[oldFileIndex] = new ExtIntArray;
					(*OffsetsArray)[oldFileIndex] = new ExtOffArray;
					if(FileHash->lookup(DataSet[i][j].NewFileName.Value(),
														newFileIndex) != -1) {
							// switch the indices to avoid copying data
						FileHash->remove(DataSet[i][j].OldFileName.Value());
						FileHash->remove(DataSet[i][j].NewFileName.Value());
						FileHash->insert(DataSet[i][j].OldFileName.Value(),
															newFileIndex);
						FileHash->insert(DataSet[i][j].NewFileName.Value(),
															oldFileIndex);
					}
				}
				else if(FileHash->lookup(DataSet[i][j].NewFileName.Value(),
													newFileIndex) != -1) {
						// if no file got overwritten, then just add to the
						// hash and arrays
					FileHash->remove(DataSet[i][j].NewFileName.Value());
					FileHash->insert(DataSet[i][j].OldFileName.Value(),
															newFileIndex);
				}
				DataSet[i][j].OldStartTime=DataSet[i][j].NewStartTime;
				DataSet[i][j].NewStartTime=-1;
			}
		}
	}

	return;
}

//---------------------------------------------------------------------
// Scan function for the submittor data
//---------------------------------------------------------------------

int ViewServer::SubmittorScanFunc(ClassAd* cad)
{
	char Machine[200];
	char Name[200];
	int JobsRunning, JobsIdle;
	MyString GroupName;

	// Get Data From Class Ad

	if (cad->LookupString(ATTR_NAME,Name,sizeof(Name))<0) return 1;
	if (cad->LookupString(ATTR_MACHINE,Machine,sizeof(Machine))<0) return 1;
	GroupName=Name;
	strcat(Name,"/");
	strcat(Name,Machine);
	if (cad->LookupInteger(ATTR_RUNNING_JOBS,JobsRunning)<0) JobsRunning=0;
	if (cad->LookupInteger(ATTR_IDLE_JOBS,JobsIdle)<0) JobsIdle=0;

	// Add to group Totals

	GeneralRecord* GenRec=GetAccData(GroupHash,"Total");
	GenRec->Data[0]+=JobsRunning;
	GenRec->Data[1]+=JobsIdle;
	GenRec=GetAccData(GroupHash,GroupName);
	GenRec->Data[0]+=JobsRunning;
	GenRec->Data[1]+=JobsIdle;

	// Add to accumulated data

	int NumSamples;
	for (int j=0; j<HistoryLevels; j++) {
		GenRec=GetAccData(DataSet[SubmittorData][j].AccData, Name);
		NumSamples=DataSet[SubmittorData][j].NumSamples;
		GenRec->Data[0]=(GenRec->Data[0]*NumSamples+JobsRunning)/(NumSamples+1);
		GenRec->Data[1]=(GenRec->Data[1]*NumSamples+JobsIdle)/(NumSamples+1);
	}
	return 1;
}

//---------------------------------------------------------------------
// Accumulates the submittor data totals
//---------------------------------------------------------------------

int ViewServer::SubmittorTotalFunc(void)
{
	// Add to Accumulated Data

	MyString GroupName;
	GeneralRecord* CurValue;
	GeneralRecord* AccValue;
	int NumSamples;

	GroupHash->startIterations();
	while(GroupHash->iterate(GroupName,CurValue)) {
		for (int j=0; j<HistoryLevels; j++) {
			AccValue=GetAccData(DataSet[SubmittorGroupsData][j].AccData, GroupName);
			NumSamples=DataSet[SubmittorGroupsData][j].NumSamples;
			for (int k=0; k<2; k++) {
				AccValue->Data[k]=(AccValue->Data[k]*NumSamples+CurValue->Data[k])/(NumSamples+1);
			}
		}
		delete CurValue;
	}
	GroupHash->clear();

	return 1;
}

//---------------------------------------------------------------------
// Scan function for the startd data
//---------------------------------------------------------------------

int ViewServer::StartdScanFunc(ClassAd* cad)
{
	char Name[200] = "";
	char StateDesc[50];
	float LoadAvg;
	int KbdIdle;

	// Get Data From Class Ad

	if ( !cad->LookupString(ATTR_NAME,Name,sizeof(Name)) ) return 1;
	if ( !cad->LookupInteger(ATTR_KEYBOARD_IDLE,KbdIdle) ) KbdIdle=0;
	if ( !cad->LookupFloat(ATTR_LOAD_AVG,LoadAvg) ) LoadAvg=0;
	if ( !cad->LookupString(ATTR_STATE,StateDesc,sizeof(StateDesc)) ) strcpy(StateDesc,"");
	State StateEnum=string_to_state( StateDesc );

	// This block should be kept in sync with view_server.h and
	// condor_state.h.
	ViewStates st = VIEW_STATE_UNDEFINED;
	switch(StateEnum) {
	case owner_state:
		st=VIEW_STATE_OWNER;
		break;
	case preempting_state:
		st=VIEW_STATE_PREEMPTING;
		break;
	case claimed_state:
		st=VIEW_STATE_CLAIMED;
		break;
	case matched_state:
		st=VIEW_STATE_MATCHED;
		break;
	case unclaimed_state:
		st=VIEW_STATE_UNCLAIMED;
		break;
	case shutdown_state:
		st=VIEW_STATE_SHUTDOWN;
		break;
	case delete_state:
		st=VIEW_STATE_DELETE;
		break;
	case backfill_state:
		st=VIEW_STATE_BACKFILL;
		break;
	case drained_state:
		st=VIEW_STATE_DRAINED;
		break;
	default:
		dprintf( D_ALWAYS,
				 "WARNING: Unknown machine state %d from '%s' (ignoring)",
				 (int)StateEnum, Name );
		return 1;
	}

	// Get Group Name

	char tmp[200];
	if (cad->LookupString(ATTR_ARCH,tmp,sizeof(tmp))<0) strcpy(tmp,"Unknown");
	MyString GroupName=MyString(tmp)+"/";
	if (cad->LookupString(ATTR_OPSYS,tmp,sizeof(tmp))<0) strcpy(tmp,"Unknown");
	GroupName+=tmp;

	// Add to group Totals
	// NRL: I'm not sure exactly what this block of code does, but
	// now it at least does it safely.  It's obviously updating
	// the GroupHash <group name> and "Total" chunks.

	int group_index = (int)st - 1;
	if( group_index > (int)VIEW_STATE_MAX_OFFSET ) {
		EXCEPT( "Invalid group_index = %d (max %d)",
				group_index, (int)VIEW_STATE_MAX_OFFSET );
	}
	GeneralRecord* GenRec=GetAccData(GroupHash,"Total");
	ASSERT( GenRec );
	GenRec->Data[group_index] += 1.0;

	GenRec=GetAccData(GroupHash,GroupName);
	ASSERT( GenRec );
	GenRec->Data[group_index] += 1.0;

	// Add to accumulated data

	int NumSamples;
	for (int j=0; j<HistoryLevels; j++) {
		GenRec=GetAccData(DataSet[StartdData][j].AccData, Name);
		ASSERT( GenRec );

		NumSamples=DataSet[StartdData][j].NumSamples;
		GenRec->Data[0]=(GenRec->Data[0]*NumSamples+KbdIdle)/(NumSamples+1);
		GenRec->Data[1]=(GenRec->Data[1]*NumSamples+LoadAvg)/(NumSamples+1);
		GenRec->Data[2]=st;
	}

	return 1;
}

//---------------------------------------------------------------------
// Accumulates the startd data totals
//---------------------------------------------------------------------

int ViewServer::StartdTotalFunc(void)
{
	// Add to Accumulated Data

	MyString GroupName;
	GeneralRecord* CurValue;
	GeneralRecord* AccValue;
	int NumSamples;

	GroupHash->startIterations();
	while(GroupHash->iterate(GroupName,CurValue)) {
		for (int j=0; j<HistoryLevels; j++) {
			AccValue=GetAccData(DataSet[GroupsData][j].AccData, GroupName);
			NumSamples=DataSet[GroupsData][j].NumSamples;
			for (int k=0; k<(int)VIEW_STATE_MAX; k++) {
				AccValue->Data[k]=(AccValue->Data[k]*NumSamples+CurValue->Data[k])/(NumSamples+1);
			}
		}
		delete CurValue;
	}
	GroupHash->clear();

	return 1;
}

//---------------------------------------------------------------------
// Scan function for the checkpoint server
//---------------------------------------------------------------------

int ViewServer::CkptScanFunc(ClassAd* cad)
{
	char Name[200];
	int Bytes;
	float BytesReceived,BytesSent;
	float AvgReceiveBandwidth,AvgSendBandwidth;

	// Get Data From Class Ad

	if (cad->LookupString(ATTR_NAME,Name,sizeof(Name))<0) return 1;
	if (cad->LookupInteger("BytesReceived",Bytes)<0) Bytes=0;
	BytesReceived=float(Bytes)/(1024*1024);
	if (cad->LookupInteger("BytesSent",Bytes)<0) Bytes=0;
	BytesSent=float(Bytes)/(1024*1024);
	if (cad->LookupFloat("AvgReceiveBandwidth",AvgReceiveBandwidth)<0) AvgReceiveBandwidth=0;
	AvgReceiveBandwidth=AvgReceiveBandwidth/1024;
	if (cad->LookupFloat("AvgSendBandwidth",AvgSendBandwidth)<0) AvgSendBandwidth=0;
	AvgSendBandwidth=AvgSendBandwidth/1024;

	// Add to accumulated data

	int NumSamples;
	GeneralRecord* GenRec;
	for (int j=0; j<HistoryLevels; j++) {
		GenRec=GetAccData(DataSet[CkptData][j].AccData, Name);
		NumSamples=DataSet[CkptData][j].NumSamples;
		GenRec->Data[0]=(GenRec->Data[0]*NumSamples+BytesReceived)/(NumSamples+1);
		GenRec->Data[1]=(GenRec->Data[1]*NumSamples+BytesSent)/(NumSamples+1);
		GenRec->Data[2]=(GenRec->Data[2]*NumSamples+AvgReceiveBandwidth)/(NumSamples+1);
		GenRec->Data[3]=(GenRec->Data[3]*NumSamples+AvgSendBandwidth)/(NumSamples+1);
	}

	return 1;
}

//---------------------------------------------------------------------
// Insert or update data accumulated entry
//---------------------------------------------------------------------

GeneralRecord* ViewServer::GetAccData(AccHash* AccData,const MyString& Key)
{
	GeneralRecord* GenRec = NULL;
	int rval;

	rval = AccData->lookup( Key, GenRec );
	if ( ( rval < 0 ) || ( GenRec == NULL ) ) {
		if ( rval >= 0 ) {
			dprintf( D_ALWAYS,
					 "Hash %p lookup returned %d, but NULL record!\n",
					 AccData, rval );
			EXCEPT( "Bad lookup" );
		}
		GenRec=new GeneralRecord;
		if ( GenRec == NULL ) {
			EXCEPT( "Failed to allocate a GeneralRecord" );
		}
		if ( AccData->insert(Key,GenRec) < 0 ) {
			EXCEPT( "Insert failed: Key=%s", Key.Value() );
		}
	}
	return GenRec;
}


text:
import React from 'react';
import PropTypes from 'prop-types';
import { H6 } from '@ui/typography';

const Label = ({ route }) => {
  const labelText = route.title;
  return <H6>{labelText}</H6>;
};

Label.propTypes = { route: PropTypes.shape({ title: PropTypes.string }) };

export default Label;

redpajama_set_name: RedPajamaGithub


text:
import { createHashHistory } from "history";

export default createHashHistory();


text:
"use strict";
; (function($, window, document, undefined) {
    var methods = {
        init: function(options) {
            options = $.extend({
                maxLength: 250,
                endString: "...",
                moreText: "show more",
                lessText: "show less",
                showMoreCallback: $.noop,
                showLessCallback: $.noop
            }, options || {});

            var splitNodes = function(root) {
                var length = 0,
                result = [],
                max = options.maxLength,
                endString = options.endString,
                splitChildNodes = function(nodes) {
                    var i = 0, clone;
                    if (length >= max) {
                        return;
                    }
                    for (; i < nodes.length; i++) {
                        if (length >= max) {
                            return;
                        }
                        var node = nodes[i];
                        if (node.nodeType === 1) { //element node
                            clone = node.cloneNode(false);
                            result[result.length - 1].appendChild(clone);
                            result.push(clone);
                            splitChildNodes(node.childNodes);
                            result.pop();
                        } else if (node.nodeType === 3) { //text node
                            if (length + node.length < max) {
                                result[result.length - 1].appendChild(node.cloneNode(false));
                                length += node.length;
                            } else { // we're over the max, so summarize it
                                var text = $(node).text();
                                var lastIndex = Math.min(max - length, text.substring(0, max - length).lastIndexOf(' '));
                                text = text.substring(0, lastIndex) + endString;
                                result[result.length - 1].appendChild(document.createTextNode(text));
                                length += node.length;
                                return;
                            }
                        }
                    }
                };
                result.push(root.cloneNode(false));
                splitChildNodes(root.childNodes);
                return $(result.pop().childNodes);
            };

            function showMore($this, $clone) {
                $this.show();
                $clone.hide();
                options.showMoreCallback($this, $clone);
            }

            function showLess($this, $clone) {
                $this.hide();
                $clone.show();
                options.showLessCallback($this, $clone);
            }

            return this.each(function() {
                var $this = $(this), $wrapper, nodes, $clone;

                //if it's been summarized once, don't do it again.
                if ($this.closest('.pf-summarize-wrapper').length) {
                    $this.trigger('pf.showSummary');
                    return;
                }

                $wrapper = $('
');
                $this.wrap($wrapper);

                nodes = splitNodes(this); //split the nodes and get back the summarized version
                $clone = $this.clone(); //clone it
                $this.hide(); //keep original, but hide it
                $clone.empty()
                    .append(nodes)
                    .addClass('pf-summarize')
                    .append($("" + options.moreText + "").on('click.pfsummarize', function(event) {
                        showMore($this, $clone);
                    }))
                    .insertAfter($this);

                $this.append($("" + options.lessText + "").on('click.pfsummarize', function(event) {
                     showLess($this, $clone);
                }));

                //bindings to control show more and less
                $this.bind('pf.showSummary', function() {
                    showMore($this, $clone);
                });

                $this.bind('pf.hideSummary', function() {
                    showLess($this, $clone);
                });

            });
        },

        destroy: function() {
            return this.each(function() {
                var $this = $(this),
                    $wrapper = $this.closest('.pf-summarize-wrapper');
                if ($wrapper.length) {
                    $this.insertBefore($wrapper).show()
                        .find('.pf-show-less').remove();
                    $wrapper.remove();
                }
            });
        }
    }

    $.fn.pfsummarize = function(method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            Sys.Debug.trace('Method ' + method + ' does not exist on pfsummarize');
        }

    };

})(jQuery, window, document);


text:
'use strict';

var AWS = require("aws-sdk");
AWS.config.update({
  region: "eu-central-1"
});

let cmisBootstrapService = require('./cmis-bootstrap-service.js');

let context = {};
let event = {
  "resource": "/bootstrap",
  "path": "/bootstrap",
  "httpMethod": "POST",
  "headers": null,
  "queryStringParameters": null,
  "pathParameters": null,
  "stageVariables": null,
  "requestContext": {
    "accountId": "0123456789",
    "resourceId": "abcd9876",
    "stage": "test-invoke-stage",
    "requestId": "test-invoke-request",
    "identity": {
      "cognitoIdentityPoolId": null,
      "accountId": "0123456789",
      "cognitoIdentityId": null,
      "caller": "ABCDEFGHIJ",
      "apiKey": "test-invoke-api-key",
      "sourceIp": "test-invoke-source-ip",
      "accessKey": "ABCDEFGHIJ",
      "cognitoAuthenticationType": null,
      "cognitoAuthenticationProvider": null,
      "userArn": "arn:aws:iam::0123456789:user/adminuser",
      "userAgent": "Apache-HttpClient/4.5.x (Java/1.8.0_102)",
      "user": "ABCDEFGHIJ"
    },
    "resourcePath": "/bootstrap",
    "httpMethod": "POST",
    "apiId": "xyz1234"
  },
  "body": "{\n    \"repositoryId\": \"default\"\n}",
  "isBase64Encoded": false
};

// run the tests
console.log("Running bootstrap tests...");

// bootstrap
cmisBootstrapService.handler(event, context, function(error, result) {
  if (error) {
    console.error("Failed to bootstrap: " + JSON.stringify(error, null, 2));
  } else {
    // TODO: test the response is as expected
    console.log("Result: " + JSON.stringify(result, null, 2));
  }
});


text:
$script:DSCModuleName = 'cDayZeroDeploy'
$script:DSCResourceName = 'cDeployWindowsDataCenter'

#region Header
Clear-Host
$ModuleRoot = Split-Path -Path $Script:MyInvocation.MyCommand.Path -Parent | Split-Path -Parent | Split-Path -Parent

if (
    (-not (Test-Path -Path (Join-Path -Path $script:ModuleRoot -ChildPath 'DSCResource.Tests') -PathType Container)) -or
    (-not (Test-Path -Path (Join-Path -Path $script:ModuleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -PathType Leaf))
)
{
    (& git @('clone', 'https://github.com/PowerShell/DscResource.Tests.git', (Join-Path -Path $ModuleRoot -ChildPath 'DSCResource.Tests'))) 2> $null
}
else
{
    & git @('-C', (Join-Path -Path $ModuleRoot -ChildPath 'DSCResource.Tests'), 'pull')
}

Import-Module -Name (Join-Path -Path $ModuleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force

$TestEnvironment = Initialize-TestEnvironment -DSCModuleName $script:DSCModuleName -DSCResourceName $script:DSCResourceName -TestType Integration

Import-Module -Name 'cDayZeroDeploy' -Force

#endregion

# Begin Testing
try
{
    #region Integration Tests

    $ConfigFile = Join-Path -Path $PSScriptRoot -ChildPath "$($script:DSCResourceName).Config.ps1"
    . $ConfigFile

    Describe "$($script:DSCResourceName)_Integration - Ensure is set to Enabled" {
        BeforeAll {

            $DomainNetBIOSName = 'MINIONS'
            $DomainAdminName = $DomainNetBIOSName + '\Administrator'
            $DomainAdminPassword = 'Minions8675309'

            $DomainAdminSecurePassword = ConvertTo-SecureString $DomainAdminPassword -AsPlainText -Force
            $DomainAdminCreds = New-Object System.Management.Automation.PSCredential ($DomainAdminName, $DomainAdminSecurePassword)

            $SafeModeAdminCreds = New-Object System.Management.Automation.PSCredential ('SafeMode', $DomainAdminSecurePassword)

            $configData = @{
                AllNodes = @(
                    @{
                        NodeName                    = 'AD1'
                        Roles                       = @('WindowsServer', 'ActiveDirectory', 'PrimaryAD')
                        VMName                      = 'MinionsAD1'
                        VHDPath                     = (Join-Path -Path $Env:TEMP -ChildPath 'minionsad1.vhdx')
                        UnattendXmlPath             = (Join-Path -Path $Env:TEMP -ChildPath 'minionsad1unattend.xml')
                        IPAddress                   = '10.1.0.220'
                        DNSServers                   = @('8.8.8.8')
                        PsDscAllowPlainTextPassword = $true
                        PSDscAllowDomainUser        = $true
                    },

                    @{
                        NodeName                    = 'CARoot'
                        Roles                       = @('WindowsServer', 'CertificateServer', 'RootCA')
                        VMName                      = 'MinionsRootCA'
                        VHDPath                     = (Join-Path -Path $Env:TEMP -ChildPath 'minionsrootca.vhdx')
                        UnattendXmlPath             = (Join-Path -Path $Env:TEMP -ChildPath 'minionsrootcaunattend.xml')
                        IPAddress                   = '10.1.0.221'
                        DNSServers                  = '10.1.0.220'
                        PsDscAllowPlainTextPassword = $true
                        PSDscAllowDomainUser        = $true
                    }
                )

                DomainInformation = @{
                    BaseWindowsVHD                  = (Join-Path -Path $Env:TEMP -ChildPath 'testwindowsvhd.vhdx')
                    SubnetLength                    = 24
                    DefaultGateway                  = '10.1.0.1'
                    ADDomain                        = 'minions.org'
                    SwitchName                      = 'DemoLabSwitch'
                    LocalAdministratorPassword      = $DomainAdminPassword
                    RegisteredOwner                 = 'Bob'
                    RegisteredOrganization          = 'Minions will take over Inc.'
                    DomainAdministratorCredential   = $DomainAdminCreds
                    SafeModeAdministratorPassword   = $SafeModeAdminCreds
                    DomainNetBIOSName               = $DomainNetBIOSName
                }
            }

            foreach($node in $configData.AllNodes) {
                try {
                    $vm = Get-VM -Name ($node.VMName) -ErrorAction SilentlyContinue
                    if($null -ne $vm) {
                        Stop-VM -VM $vm -Force -TurnOff
                        $vm.ConfigurationLocation
                        Remove-VM -VM $vm -Force -Confirm:$false
                    }
                } catch {}

                If (Test-Path -Path $node.VHDPath) {
                    Remove-Item -Path $node.VHDPath -Force
                }

                If (Test-Path -Path $node.UnattendXmlPath) {
                    Remove-Item -Path $node.UnattendXmlPath -Force
                }
            }
        }

        Context 'InitialTest' {
            #region DEFAULT TESTS
            It 'Should compile and apply the MOF without throwing' {
                {
                    Write-Host $TestDrive
                    Write-Host "$configData"
                    Write-Host "$($script:DSCResourceName)_Config"
                    & "$($script:DSCResourceName)_Config" `
                        -OutputPath $TestDrive `
                        -ConfigurationData $configData `
                        -ComputerName localhost `
                        -MOFPath $TestDrive

                    Start-DscConfiguration -Path $TestDrive -ComputerName localhost -Wait -Verbose -Force
                } | Should Not Throw
            }

#            It 'Should be able to call Get-DscConfiguration without throwing' {
#                { Get-DscConfiguration -Verbose -ErrorAction Stop } | Should Not Throw
#            }
            #endregion
        }

        AfterAll {
#           try {
#               $vm = Get-VM -Name ($configData.AllNodes[0].VMName)
#               if($null -ne $vm) {
#                   Stop-VM -VM $vm -Force -TurnOff
#                   $vm.ConfigurationLocation
#                   Remove-VM -VM $vm -Force -Confirm:$false
#               }
#           } catch {}
#            If (Test-Path -Path $configData.AllNodes[0].VHDPath) {
#                Remove-Item -Path $configData.AllNodes[0].VHDPath -Force
#            }
#            If (Test-Path -Path $configData.AllNodes[0].UnattendXmlPath) {
#                Remove-Item -Path $configData.AllNodes[0].UnattendXmlPath -Force
#            }
        }
    }
    #endregion
}
finally
{
    #region Footer

    Restore-TestEnvironment -TestEnvironment $TestEnvironment

    #endregion
}


text:
"use strict";

var
  request = require('request'),
  requestSync = require('sync-request'),
  querystring = require('querystring');

var actionTypeEnum = {
  LIKE: 1,
  WAS_LIKED: 2,
  BOOKMARK: 3,
  NEW_TOPIC: 4,
  REPLY: 5,
  RESPONSE: 6,
  MENTION: 7,
  QUOTE: 9,
  STAR: 10,
  EDIT: 11,
  NEW_PRIVATE_MESSAGE: 12,
  GOT_PRIVATE_MESSAGE: 13
};

var Discourse = function(url, api_key, api_username) {

  this.url = url;
  this.api_key = api_key;
  this.api_username = api_username;

};

require('./categories')(Discourse, actionTypeEnum);
require('./groups')(Discourse, actionTypeEnum);
require('./pms')(Discourse, actionTypeEnum);
require('./search')(Discourse, actionTypeEnum);
require('./topics')(Discourse, actionTypeEnum);
require('./users')(Discourse, actionTypeEnum);

//////////////////////////////

Discourse.prototype.get = function(url, parameters, callback) {

  var getUrl = this.url + '/' + url +
    '?api_key=' + this.api_key +
    '&api_username=' + this.api_username +
    '&' + querystring.stringify(parameters);

  request.get({
      url: getUrl
    },
    function(error, response, body) {

      if (error) {
        callback(error, {}, 500);
      }
      else if (!error && !!body.status && body.status !== 'OK'){
        error = new Error(body.description || body.error_message);
      }

      callback(error, body || {}, response != null ? response.statusCode : null);

    }
  );
};

Discourse.prototype.getSync = function(url, parameters, auth) {

  var qs = auth? {
    api_key: this.api_key,
    api_username: this.api_username
  } : {};
  for (var p in parameters) qs[p] = parameters[p];

  var getUrl = this.url + '/' + url;

  return requestSync('GET', getUrl, {qs: qs});

};

Discourse.prototype.post = function(url, parameters, callback) {

  var postUrl = this.url + '/' + url + '?api_key=' + this.api_key + '&api_username=' + this.api_username;

  request({
      uri: postUrl,
      method: 'POST',
      form: parameters
    },
    function (error, response, body) {

      if (!error && !!body.status && body.status !== 'OK') {
        error = new Error(body.description || body.error_message);
      }

      callback(error, body || {}, response != null ? response.statusCode : null);

    });

};

Discourse.prototype.postSync = function(url, parameters) {
  var postUrl = this.url + '/' + url + '?api_key=' + this.api_key + '&api_username=' + this.api_username;

  return requestSync('POST', postUrl, {
    headers: {
      'content-type': 'application/json'
    },
    body: JSON.stringify(parameters)
  });

};

Discourse.prototype.put = function(url, parameters, callback) {

  var putUrl = this.url + '/' + url + '?api_key=' + this.api_key + '&api_username=' + this.api_username;

  request({
      uri: putUrl,
      method: 'PUT',
      form: parameters
    },
    function (error, response, body) {

      if (!error && !!body.status && body.status !== 'OK') {
        error = new Error(body.description || body.error_message);
      }

      callback(error, body || {}, response != null ? response.statusCode : null);

    });

};

Discourse.prototype.putSync = function(url, parameters, callback) {

  var putUrl = this.url + '/' + url + '?api_key=' + this.api_key + '&api_username=' + this.api_username;

  return requestSync('PUT', putUrl, {
    headers: {
      'content-type': 'application/json'
    },
    body: JSON.stringify(parameters)
  });

};

Discourse.prototype.delete = function(url, parameters, callback) {

  var deleteUrl = this.url + '/' + url + '?api_key=' + this.api_key + '&api_username=' + this.api_username;

  request({
      uri: deleteUrl,
      method: 'DELETE',
      form: parameters
    },
    function (error, response, body) {

      if (!error && !!body.status && body.status !== 'OK') {
        error = new Error(body.description || body.error_message);
      }

      callback(error, body || {}, response != null ? response.statusCode : null);

    });

};

Discourse.prototype.deleteSync = function (url, parameters, callback) {

  var deleteUrl = this.url + '/' + url;
  var qs = {
    api_key: this.api_key,
    api_username: this.api_username
  };
  for (var p in parameters) qs[p] = parameters[p];

  return requestSync('DELETE', deleteUrl, {
    headers: {
      'content-type': 'application/json'
    },
    qs: qs
  });
};

//////////////////////////////

module.exports = Discourse;


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: tensorflow/core/util/event.proto

package org.tensorflow.proto.util;

/**
 *

 * Indicates the behavior of the worker when an internal error or shutdown
 * signal is received.
 *

 *
 * Protobuf enum {@code tensorflow.WorkerShutdownMode}
 */
public enum WorkerShutdownMode
    implements com.google.protobuf.ProtocolMessageEnum {
  /**
   * DEFAULT = 0;
   */
  DEFAULT(0),
  /**
   * NOT_CONFIGURED = 1;
   */
  NOT_CONFIGURED(1),
  /**
   * WAIT_FOR_COORDINATOR = 2;
   */
  WAIT_FOR_COORDINATOR(2),
  /**
   * SHUTDOWN_AFTER_TIMEOUT = 3;
   */
  SHUTDOWN_AFTER_TIMEOUT(3),
  UNRECOGNIZED(-1),
  ;

  /**
   * DEFAULT = 0;
   */
  public static final int DEFAULT_VALUE = 0;
  /**
   * NOT_CONFIGURED = 1;
   */
  public static final int NOT_CONFIGURED_VALUE = 1;
  /**
   * WAIT_FOR_COORDINATOR = 2;
   */
  public static final int WAIT_FOR_COORDINATOR_VALUE = 2;
  /**
   * SHUTDOWN_AFTER_TIMEOUT = 3;
   */
  public static final int SHUTDOWN_AFTER_TIMEOUT_VALUE = 3;

  public final int getNumber() {
    if (this == UNRECOGNIZED) {
      throw new java.lang.IllegalArgumentException(
          "Can't get the number of an unknown enum value.");
    }
    return value;
  }

  /**
   * @deprecated Use {@link #forNumber(int)} instead.
   */
  @java.lang.Deprecated
  public static WorkerShutdownMode valueOf(int value) {
    return forNumber(value);
  }

  public static WorkerShutdownMode forNumber(int value) {
    switch (value) {
      case 0: return DEFAULT;
      case 1: return NOT_CONFIGURED;
      case 2: return WAIT_FOR_COORDINATOR;
      case 3: return SHUTDOWN_AFTER_TIMEOUT;
      default: return null;
    }
  }

  public static com.google.protobuf.Internal.EnumLiteMap<WorkerShutdownMode>
      internalGetValueMap() {
    return internalValueMap;
  }
  private static final com.google.protobuf.Internal.EnumLiteMap<
      WorkerShutdownMode> internalValueMap =
        new com.google.protobuf.Internal.EnumLiteMap<WorkerShutdownMode>() {
          public WorkerShutdownMode findValueByNumber(int number) {
            return WorkerShutdownMode.forNumber(number);
          }
        };

  public final com.google.protobuf.Descriptors.EnumValueDescriptor
      getValueDescriptor() {
    return getDescriptor().getValues().get(ordinal());
  }
  public final com.google.protobuf.Descriptors.EnumDescriptor
      getDescriptorForType() {
    return getDescriptor();
  }
  public static final com.google.protobuf.Descriptors.EnumDescriptor
      getDescriptor() {
    return org.tensorflow.proto.util.EventProtos.getDescriptor().getEnumTypes().get(1);
  }

  private static final WorkerShutdownMode[] VALUES = values();

  public static WorkerShutdownMode valueOf(
      com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
    if (desc.getType() != getDescriptor()) {
      throw new java.lang.IllegalArgumentException(
        "EnumValueDescriptor is not for this type.");
    }
    if (desc.getIndex() == -1) {
      return UNRECOGNIZED;
    }
    return VALUES[desc.getIndex()];
  }

  private final int value;

  private WorkerShutdownMode(int value) {
    this.value = value;
  }

  // @@protoc_insertion_point(enum_scope:tensorflow.WorkerShutdownMode)
}


text:
@charset "utf-8";
table{
border-collapse:collapse;
}
table td{
empty-cells:show;
font-size:12px;
color:#666;
}

.box{ width:100%; margin:0 auto;}
/* CSS Document */
.ctop{ width:100%;margin:0 auto; background:url(../../../Images/images/topbg.jpg) repeat-x left top; height:152px; z-index:200}
.top_con{ width:1200px; margin:0 auto;}
.top_ctext{ padding-left:14px; line-height:31px; float:left; color:#666666; font-size:12px; font-family:"宋体";  }
#top_ctextys{  color:#1488e3; font-size:12px; font-family:"宋体";  }
.top_ctext1{ width:500px; padding-left:11px;  float:left; padding-top:4px; }
.subbmit{ width:45px; height:22px; border:none; line-height:22px; color:#fff; font-size:12px; font-family:"宋体"; background:url(../../../Images/images/btn.jpg) no-repeat left top; cursor:pointer; text-align:center;}
.top_ctext2{ width:380px; float:right;  line-height:31px; height:31px; color:#666666; font-size:12px; font-family:"宋体";}
.top_ctext2 .ys1{  float:left; line-height:31px; height:31px; color:#666666; font-size:12px; font-family:"宋体";}
.top_ctext2 .ys2{  float:left; padding-top:8px; height:22px; padding-left:8px; width:24px;}
.top_ctext2 .ys3{  float:left; line-height:31px; height:31px; color:#666666; font-size:12px; font-family:"宋体";}
.top_logo{ width:1200px; margin:0 auto; height:121px;}
.fonys{color:#FF0000; font-size:14px; font-family:Arial, Helvetica, sans-serif; font-weight:bold;}

/*============================logo和搜索框===================================*/

.topf{ width:1200px; float:left; height:121px; z-index:200; position:relative;}
.logo{ width:670px; float:left;   padding-top:23px;}
.logo01{ width:230px;  float:left; padding-left:30px; padding-top:2px;}
.logo02{ width:150px; padding-left:14px; float:left; padding-top:3px; line-height:55px; }
.ht{ color:#2791e3; font-size:32px;  font-family:"微软雅黑"; float:left;}
.ht1{ padding-left:0px; padding-top:0px;}
.htbtn{ width:70px; height:14px; text-align:left; color:#ababab; font-size:12px; border:none; background:#fff; cursor:pointer;}
.shopcart{ width:582px; height:42px; float:left; position:absolute; top:43px; right:0px;  background:url(../../../Images/images/shopcart11.jpg) no-repeat left top; line-height:42px; font-size:16px;  font-family:"微软雅黑";}
.shopcart h1{ width:180px;  float:left; padding-left:38px; color:#666666;}
.shopcart h2{ width:201px;  float:left;  color:#666666;}
.shopcart h3{   float:left;   color:#fffefe;}
#fy{   width:492px;  height:260px; overflow-y:scroll; overflow-x:hidden; margin-top:5px; padding-bottom:5px; float:left;}
#fy1{  color:#5199cd; text-decoration:none; font-size:14px; font-family:"宋体"; font-weight:normal;  width:476px; padding-top:15px; padding-left:16px; float:left; }
#fy1 span{   width:72px; height:27px; background:url(../pro_dropdown_2/a8.jpg) no-repeat left top; line-height:27px; float:left; text-align:center;   font-size:14px; font-family:"宋体"; color:#6a6a6a; display:block; margin-right:5px; display:inline;}
#fy1 a{ width:48px; float:left; height:27px; line-height:27px; text-align:center; display:block; color:#2c91e1; text-decoration:none; font-size:14px; font-family:"宋体"; font-weight:normal;}
#fy1 a:hover{ color:#2c91e1; text-decoration:underline; font-size:14px; font-family:"宋体"; font-weight:normal;}
#fy2{ float:left; height:10px; width:400px;}
/*============================logo旁边的弹出层===================================*/
.logo03{ width:84px; float:left; position:relative; padding-left:10px;}
#tys{width:84px; height:18px; line-height:18px; font-size:14px;  color:#2c91e1; font-family:'宋体'; text-align:center;  margin-top:18px; float:left; height:18px;}
#tys1{  display:block; font-weight:normal;  width:84px; line-height:20px; font-size:14px; color:#bbbdbf; font-family:"宋体"; text-align:center; cursor:pointer;}
.fba{ position:absolute; top:0; left:0; width:494px;  height:270px; z-index:-1;}
.tanlay{position:absolute; top:55px; left:15px;z-index:9999; display:none;}
.tanlay01{width:494px;  height:270px;  background:url(../../../Images/images/bg3.gif) no-repeat left top;}

/*============================收获人地址===================================*/

.content{ width:1200px; margin:0 auto; overflow:hidden;}
.orderpay{ width:1200px; float:left; padding-top:25px; overflow:hidden;}
.orderpay01{  float:left; padding-left:257px; width:800px; }
.orderpay01_text{  float:left; width:800px; padding-bottom:29px;}
.orderpay01_text h1{  float:left; padding-left:5px; padding-right:27px;}
.orderpay01_text h2{  float:left; line-height:36px; color:#666666; font-size:24px;  font-family:"微软雅黑";}
.orderpay01_text2{  float:left; width:800px;  line-height:30px;}
.orderpay01_text2 span{  float:left; font-weight:bold;}
.orderpay01_text2 samp{  float:left; font-weight:bold; color:#e41215; font-family:"宋体"; font-size:14px;}
.orderpay1{ float:left; margin-left:45px; width:1110px; display:inline; border-top:#f5f5f5 solid 1px; margin-top:10px;}
.orderpay1_content{  float:left; padding-left:211px; width:730px; padding-top:15px;}
.orderpay1_title{  float:left;  width:700px; font-size:14px; font-weight:bold;}
.orderpay1_title h1{ float:left; line-height:48px; text-align:left; font-size:12px; font-weight:bold;}
.orderpay1_title h2{ background: url("../../../Images/images/shopcart6.jpg") no-repeat scroll left top transparent;  width:154px; float:left; height:48px;  margin-right:5px; display:inline; padding-left:15px; padding-top:7px;}
.orderpay1_title h2 img{ width:125px; height:34px;}
.orderpay1_title h3{ float:left; line-height:48px; text-align:left; color:#0a7cd4;}
.orderpay1_title h3 a{ color:#0a7cd4; text-decoration:none;}
.orderpay1_title h3 a:hover{ color:#0a7cd4; text-decoration:underline;}
.orderpay1_title1{  float:left;  width:700px; padding-left:5px; font-size:14px; font-weight:bold; margin-top:15px;}
.orderpay1_title2{  float:left;  width:700px; margin-top:15px;}
.orderpay1btn{ width:104px; height:29px; background:url(../../../Images/images/shopcart14.jpg) no-repeat left top; border:none; cursor:pointer;}

/*============================支付订单的弹出层===================================*/

.ordersPaylayer{ width:478px; height:317px; float:left; background:#fff; position: absolute; top: 15%; left: 30%; z-index: 1002; }
.ordersPaylayer01{ width:478px; height:45px; float:left; border-bottom:#2791e3 solid 2px; position:relative;}
.ordersPaylayer01 h1{ float:left; margin-left:15px; display:inline; color:#2791e3; font-size:18px; font-family:"微软雅黑"; padding-top:12px; height:33px;background:url(../../../Images/images/a14.jpg) no-repeat center bottom;}
.ordersPaylayer01 h2{ position:absolute; right:17px; top:20px;}
.ordersPaylayer01 h2 span{ color:#2791e3; font-size:12px; padding-right:5px; float:left; padding-top:2px;}
.ordersPaylayer01 h2 span a{ color:#2791e3; font-size:12px; text-decoration:none;}
.ordersPaylayer01 h2 span a:hover{ color:#2791e3; font-size:12px; text-decoration:underline;}
.ordersPaylayer01 h2 samp{ float:left;}
.Popuplogin01btn{ width:14px; height:14px; background:url(../../../Images/images/pop2.jpg) no-repeat left top; border:none; cursor:pointer;}
.ordersPaylayer02{ width:430px; float:left; padding-left:24px;}
.ordersPaylayer02_text{ width:430px; float:left; padding-top:33px; height:54px; background:url(../../../Images/images/lay6.jpg) repeat-x left bottom;}
.ordersPaylayer02_text h1{ width:44px; float:left; padding-left:47px;}
.ordersPaylayer02_text h2{ float:left; padding-top:4px; font-family:"微软雅黑"; font-size:20px;}
.ordersPaylayer02_text1{ width:323px; float:left; padding-top:16px;  padding-left:107px;}
.ordersPaylayer02_text1 h1{width:323px; float:left; height:56px; line-height:22px;}
.ordersPaylayer02_text1 h2{width:323px; float:left; height:63px;}
.ordersPaylayer02_text1 h2 span{ float:left; padding-right:22px;}
.ordersPaylayer02_text1 h3{width:323px; float:left; color:#2791e3; font-size:12px;}
.ordersPaylayer02_text1 h3 a{color:#2791e3; font-size:12px; text-decoration:none;}
.ordersPaylayer02_text1 h3 a:hover{color:#2791e3; font-size:12px; text-decoration:underline;}
.personlayer020301{width:79px; height:26px; background:#2791e3; color:#fff; font-size:12px; line-height:26px; font-family:"宋体"; text-decoration:none; display:block; text-align:center;}
.personlayer020301:hover{width:79px; height:26px; background:#2791e3; color:#fff; font-size:12px; line-height:26px; font-family:"宋体"; text-decoration:none; display:block; text-align:center;}
.personlayer020302{width:92px; height:26px; background:#fe9f43; color:#fff; font-size:12px; line-height:26px; font-family:"宋体"; text-decoration:none; display:block; text-align:center;}
.personlayer020302:hover{width:92px; height:26px; background:#fe9f43; color:#fff; font-size:12px; line-height:26px; font-family:"宋体"; text-decoration:none; display:block; text-align:center;}


text:
USING_NS_CC;

Scene* HelloWorld::createScene()
{
    // 'scene' is an autorelease object
    auto scene = Scene::createWithPhysics();
    scene->getPhysicsWorld()->setGravity(Vect(0,0));
//    scene->getPhysicsWorld()->setDebugDrawMask(PhysicsWorld::DEBUGDRAW_ALL);

    cout << "dabendan" << endl;
    // 'layer' is an autorelease object
    auto layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{

    if ( !Layer::init() )
    {
        return false;
    }

    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

    Sprite *backgroundSprite = Sprite::create("background.png");
    backgroundSprite->setPosition(Vec2(visibleSize.width/2,visibleSize.height/2));
    this->addChild(backgroundSprite);

    scoreLabel = Label::createWithTTF("Score:0", "fonts/Marker Felt.ttf",48);

    scoreLabel->setColor(Color3B::WHITE);
    scoreLabel->setPosition(Vec2(origin.x+visibleSize.width - scoreLabel ->getContentSize().width,
                            origin.y+visibleSize.height - scoreLabel->getContentSize().height));
    this->addChild(scoreLabel);

    glClearColor(1.0, 1.0, 1.0, 1.0);

    _player = Sprite::create("player-hd.png");
    _player->setPosition(visibleSize.width/8,visibleSize.height/2);
    this->addChild(_player);

    this->schedule(schedule_selector(HelloWorld::addMonster), 1);

    touch_listener = EventListenerTouchOneByOne::create();
    touch_listener->setSwallowTouches(false);
    touch_listener->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan, this);
    touch_listener->onTouchMoved = CC_CALLBACK_2(HelloWorld::onTouchMoved, this);
    touch_listener->onTouchEnded = CC_CALLBACK_2(HelloWorld::onTouchEnded, this);
    touch_listener->onTouchCancelled = CC_CALLBACK_2(HelloWorld::onTouchCancelled, this);
    _eventDispatcher->addEventListenerWithSceneGraphPriority(touch_listener, this);

    EventListenerPhysicsContact *contactListener = EventListenerPhysicsContact::create();
    contactListener->onContactBegin = CC_CALLBACK_1(HelloWorld::onContactBegin, this);
    _eventDispatcher->addEventListenerWithSceneGraphPriority(contactListener, this);

    return true;
}

static int j = 0;

bool HelloWorld::onTouchBegan(Touch* pTouch, Event* pEvent)
{
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Point touchLocation = pTouch->getLocationInView();
    touchLocation = Director::getInstance()->convertToGL(touchLocation);
    Sprite* projectileExmaple = Sprite::create("projectile-hd.png");
    j+=1;
    auto OneBody = PhysicsBody::createBox(projectileExmaple->getContentSize());
    OneBody->setContactTestBitmask(0x04);

    OneBody->setTag(-1);

    projectileExmaple->setPhysicsBody(OneBody);
    projectileExmaple->setPosition(visibleSize.width/8,visibleSize.height/2);
    projectile.push_back(projectileExmaple);
    this->addChild(projectile.back(),j);
    Point offset    = ccpSub(touchLocation, _player->getPosition());
    float ratio     = offset.y/offset.x;
    int targetX   = _player->getContentSize().width/2 + visibleSize.width;
    int targetY   = (targetX*ratio) + _player->getPosition().y;
    Vec2 targetPosition = Vec2(targetX,targetY);
    MoveTo* Move = MoveTo::create(2, targetPosition);
    projectile.back()->runAction(Move);
    return true;

}
void HelloWorld::onTouchMoved(Touch* pTouch, Event* pEvent)
{
}
void HelloWorld::onTouchEnded(Touch* pTouch, Event* pEvent)
{
}

static int i = 0;
void HelloWorld::addMonster(float dt){
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Sprite* MonsterExample = Sprite::create("monster-hd.png");
    i = i+1;
    auto OneBody = PhysicsBody::createBox(MonsterExample->getContentSize());
    OneBody->setContactTestBitmask(0x08);

    OneBody->setTag(1);

    MonsterExample->setPhysicsBody(OneBody);
    MonsterExample->setPosition(
                                visibleSize.width + MonsterExample->getContentSize().width,
                                MonsterExample->getContentSize().height/2+CCRANDOM_0_1()*(visibleSize.height - MonsterExample->getContentSize().height/2));
    monster.push_back(MonsterExample);
    this->addChild(monster.back(),i);
    MoveTo* Move = MoveTo::create(3, Vec2(-monster.back()->getContentSize().width/2,monster.back()->getPosition().y));
    monster.back()->runAction(Move);

}

static int score = 0;

bool HelloWorld::onContactBegin(const cocos2d::PhysicsContact& contact){

    PhysicsBody* a = contact.getShapeA()->getBody();
    PhysicsBody* b = contact.getShapeB()->getBody();

    if (a->getTag()+b->getTag()==0) {
        HelloWorld::updateScoreLabel(++score);
    }

    this->removeChild(a->getNode());
    this->removeChild(b->getNode());
    return true;

}

void HelloWorld::updateScoreLabel(int score){
    std::stringstream ss;
    ss << "Score:" << score;
    scoreLabel->setString(ss.str());

}


text:
package eu.mosaic_cloud.platform.implementation.v2.connectors.tests;

import eu.mosaic_cloud.drivers.kvstore.riak.interop.KeyValueStub;
import eu.mosaic_cloud.platform.implementation.v2.configuration.PropertyTypeConfiguration;
import eu.mosaic_cloud.platform.implementation.v2.connectors.core.ConnectorConfiguration;
import eu.mosaic_cloud.platform.implementation.v2.connectors.kvstore.generic.GenericKvStoreConnector;
import eu.mosaic_cloud.platform.implementation.v2.serialization.PlainTextDataEncoder;
import eu.mosaic_cloud.platform.interop.specs.kvstore.KeyValueSession;
import eu.mosaic_cloud.platform.v2.configuration.Configuration;

import org.junit.AfterClass;
import org.junit.BeforeClass;

@SuppressWarnings ("boxing")
public class RiakKvStoreConnectorTest
			extends BaseKvStoreConnectorTest<GenericKvStoreConnector<String>>
{
	@Override
	public void setUp () {
		this.scenario = RiakKvStoreConnectorTest.scenario_;
		final ConnectorConfiguration configuration = ConnectorConfiguration.create (this.scenario.getConfiguration (), this.scenario.getEnvironment ());
		this.connector = GenericKvStoreConnector.create (configuration, PlainTextDataEncoder.DEFAULT_INSTANCE);
	}

	@BeforeClass
	public static void setUpBeforeClass () {
		final String host = System.getProperty (RiakKvStoreConnectorTest.MOSAIC_RIAK_HOST, RiakKvStoreConnectorTest.MOSAIC_RIAK_HOST_DEFAULT);
		final Integer port = Integer.valueOf (System.getProperty (RiakKvStoreConnectorTest.MOSAIC_RIAK_PORT, RiakKvStoreConnectorTest.MOSAIC_RIAK_PORT_DEFAULT));
		final Configuration configuration = PropertyTypeConfiguration.create ();
		configuration.addParameter ("interop.driver.endpoint", "inproc://fb012d6b-c238-4b31-b889-4121a318b2cb");
		configuration.addParameter ("interop.driver.identity", "fb012d6b-c238-4b31-b889-4121a318b2cb");
		configuration.addParameter ("kvstore.host", host);
		configuration.addParameter ("kvstore.port", port);
		configuration.addParameter ("kvstore.driver_name", "RIAKREST");
		configuration.addParameter ("kvstore.driver_threads", 1);
		configuration.addParameter ("kvstore.bucket", "tests");
		final Scenario scenario = new Scenario (RiakKvStoreConnectorTest.class, configuration);
		scenario.registerDriverRole (KeyValueSession.DRIVER);
		BaseConnectorTest.driverStub = KeyValueStub.createDetached (configuration, scenario.getThreading (), scenario.getDriverChannel ());
		RiakKvStoreConnectorTest.scenario_ = scenario;
	}

	@AfterClass
	public static void tearDownAfterClass () {
		BaseConnectorTest.tearDownScenario (RiakKvStoreConnectorTest.scenario_);
	}

	private static final String MOSAIC_RIAK_HOST = "mosaic.tests.resources.riak.host";
	private static final String MOSAIC_RIAK_HOST_DEFAULT = "127.0.0.1";
	private static final String MOSAIC_RIAK_PORT = "mosaic.tests.resources.riakrest.port";
	private static final String MOSAIC_RIAK_PORT_DEFAULT = "24637";
	private static Scenario scenario_;
}


text:
/**
 * Namespace for activity widget.
 * @namespace activity_widget
 */

requirejs([
    'jqueryui',
    'lodash',
    'require',
    'iwcw',
    'operations/non_ot/EntitySelectOperation',
    'operations/non_ot/GuidanceStrategyOperation',
    'operations/ot/NodeAddOperation',
    'operations/ot/EdgeAddOperation',
    'operations/ot/NodeDeleteOperation',
    'operations/ot/EdgeDeleteOperation',
    'operations/ot/ValueChangeOperation',
    'operations/ot/NodeMoveOperation',
    'operations/ot/NodeMoveZOperation',
    'operations/ot/NodeResizeOperation',
    'guidance_widget/NoStrategy',
    'guidance_widget/AvoidConflictsStrategy',
    'guidance_widget/CollaborationStrategy',
    'promise!LogicalGuidanceRepresentation',
    'promise!Space',
    'bootstrap'
],function ($, _, require, IWCW, EntitySelectOperation, GuidanceStrategyOperation, NodeAddOperation, EdgeAddOperation, NodeDeleteOperation, EdgeDeleteOperation, ValueChangeOperation, NodeMoveOperation, NodeMoveZOperation, NodeResizeOperation, NoStrategy, AvoidConflictsStrategy, CollaborationStrategy, LogicalGuidanceRepresentation, Space) {
    var iwc = IWCW.getInstance(CONFIG.WIDGET.NAME.GUIDANCE);
    var strategies = [
        NoStrategy,
        AvoidConflictsStrategy,
        CollaborationStrategy
    ];
    var selectedStrategy = new strategies[0](LogicalGuidanceRepresentation, Space);
    selectedStrategy.buildUi();

    var $strategies = $("#guidanceSelect");

    for(var i = 0; i < strategies.length; i++){
        var strategy = strategies[i];
        var $strategy = $(_.template("
${name}
")({name: strategy.NAME, icon: strategy.ICON}));
        $strategy.find("a").val(i);
        $strategies.append($strategy);
    }
    $strategies.find("a").click(function(){
        var index = $(this).val();
        initStrategy(index);
    });

    var operationCallback = function(operation){
        if(operation instanceof EntitySelectOperation){
            selectedStrategy.onEntitySelect(operation.getSelectedEntityId(), operation.getSelectedEntityType());
        }
        else if(operation instanceof NodeAddOperation){
            selectedStrategy.onNodeAdd(operation.getEntityId(), operation.getType());
        }
        else if (operation instanceof EdgeAddOperation){
            selectedStrategy.onEdgeAdd(operation.getEntityId(), operation.getType());
        }
        else if (operation instanceof NodeDeleteOperation){
            selectedStrategy.onNodeDelete(operation.getEntityId(), operation.getType());
        }
        else if (operation instanceof EdgeDeleteOperation){
            selectedStrategy.onEdgeDelete(operation.getEntityId(), operation.getType());
        }
        else if (operation instanceof ValueChangeOperation){
            selectedStrategy.onValueChange(operation.getEntityId(), operation.getValue(), operation.getType(), operation.getPosition());
        }
        else if (operation instanceof NodeMoveOperation){
            selectedStrategy.onNodeMove(operation.getEntityId(), operation.getOffsetX(), operation.getOffsetY());
        }
        else if (operation instanceof NodeMoveZOperation){
            selectedStrategy.onNodeMoveZ(operation.getEntityId(), operation.getOffsetZ());
        }
        else if (operation instanceof NodeResizeOperation){
            selectedStrategy.onNodeResize(operation.getEntityId(), operation.getOffsetX(), operation.getOffsetY());
        }
        else if(operation instanceof GuidanceStrategyOperation){
            selectedStrategy.onGuidanceOperation(operation.getData());
        }
    };

    var sendGuidanceStrategyOperation = function(data){
        var operation = new GuidanceStrategyOperation(data);
        iwc.sendLocalNonOTOperation(CONFIG.WIDGET.NAME.MAIN,operation.toNonOTOperation());
    }

    var initStrategy = function(index){
        selectedStrategy = new strategies[index](LogicalGuidanceRepresentation, Space);
        selectedStrategy.sendGuidanceStrategyOperation = sendGuidanceStrategyOperation;
        $("#guidance-strategy-ui").empty();
        $("#guidance-strategy-ui").append(selectedStrategy.buildUi());
        $("#strategyButton").text(strategies[index].NAME);
    }

    var registerCallbacks = function(){
        iwc.registerOnDataReceivedCallback(operationCallback);
    };

    registerCallbacks();
});


text:
package cz.muni.physics.pdr.swasp;

import cz.muni.physics.pdr.java.Plugin;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;

/**
 * @author Michal Krajčovič
 * @version 1.0
 * @since 12/04/16
 */
public class Main {
    public static void main(String[] args) throws IOException {
        URL u = null;
        Document doc;
        if (args.length == 1) {
            String objName = args[0];
            u = new URL("http://wasp.cerit-sc.cz/json?type=CSV&object=" + URLEncoder.encode(objName, "UTF-8"));
            doc = Jsoup.connect("https://wasp.cerit-sc.cz/search")
                    .data("objid", objName)
                    .data("limit", "1")
                    .data("radius", "1")
                    .data("radiusUnit", "min")
                    .post();
        } else if (args.length == 2) {
            String ra = args[0];
            String dec = args[1];
            String resultURL = "https://wasp.cerit-sc.cz/search?ra=" + ra + "&dec=" + dec + "&radius=1&radiusUnit=min&limit=1";
            doc = Jsoup.connect(resultURL).get();
        } else {
            return;
        }

        for (Element a : doc.getElementsByTag("a")) {
            if (a.ownText().equals("CSV")) {
                u = new URL(a.attr("abs:href"));
                break;
            }
        }

        if (u == null) return;
        Plugin plugin = new SwaspPlugin();
        plugin.getDataFromUrl(u.toString()).forEach(d -> System.out.println(d.toCsv()));
    }
}


text:
package org.avantssar.aslanpp;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class MockTransition {

	private final String name;
	private final List<String> commentLines = new ArrayList<String>();
	private final List<String> conditions = new ArrayList<String>();
	private final List<String> lhsItems = new ArrayList<String>();
	private final List<String> rhsItems = new ArrayList<String>();
	private final List<String> parameters = new ArrayList<String>();
	private final List<String> freshVars = new ArrayList<String>();

	public MockTransition(String name) {
		this.name = name;
	}

	public MockTransition addCommentLine(String s) {
		commentLines.add(s);
		Collections.sort(commentLines);
		return this;
	}

	public MockTransition addCondition(String name, String[] args) {
		conditions.add(renderFunction(name, args));
		Collections.sort(conditions);
		return this;
	}

	public MockTransition addNegatedCondition(String name, String[] args) {
		conditions.add(renderFunction("not", new String[] { renderFunction(name, args) }));
		Collections.sort(conditions);
		return this;
	}

	public MockTransition addLhsItem(String name, String[] args) {
		lhsItems.add(renderFunction(name, args));
		Collections.sort(lhsItems);
		return this;
	}

	public MockTransition addLhsStateItem(String name, String[] args) {
		lhsItems.add(renderFunction("state_" + name, args));
		Collections.sort(lhsItems);
		return this;
	}

	public MockTransition addNegatedLhsItem(String name, String[] args) {
		lhsItems.add(renderFunction("not", new String[] { renderFunction(name, args) }));
		Collections.sort(lhsItems);
		return this;
	}

	public MockTransition addRhsItem(String name, String[] args) {
		rhsItems.add(renderFunction(name, args));
		Collections.sort(rhsItems);
		return this;
	}

	public MockTransition addRhsStateItem(String name, String[] args) {
		rhsItems.add(renderFunction("state_" + name, args));
		Collections.sort(rhsItems);
		return this;
	}

	public MockTransition addNegatedRhsItem(String name, String[] args) {
		rhsItems.add(renderFunction("not", new String[] { renderFunction(name, args) }));
		Collections.sort(rhsItems);
		return this;
	}

	public MockTransition addParameter(String s) {
		parameters.add(s);
		Collections.sort(parameters);
		return this;
	}

	public MockTransition addParameters(String[] pars) {
		for (String s : pars) {
			addParameter(s);
		}
		return this;
	}

	public MockTransition addFreshVar(String s) {
		freshVars.add(s);
		Collections.sort(freshVars);
		return this;
	}

	public MockTransition addFreshVars(String[] vars) {
		for (String s : vars) {
			addFreshVar(s);
		}
		return this;
	}

	public static String renderFunction(String name, String[] args) {
		StringBuffer sb = new StringBuffer();
		sb.append(name).append("(");
		boolean first = true;
		for (String s : args) {
			if (!first) {
				sb.append(", ");
			}
			sb.append(s);
			first = false;
		}
		sb.append(")");
		return sb.toString();
	}

	public Collection<String> getCommentLines() {
		return commentLines;
	}

	public Collection<String> getConditions() {
		return conditions;
	}

	public Collection<String> getExistsVarNames() {
		return freshVars;
	}

	public Collection<String> getLhsItems() {
		return lhsItems;
	}

	public String getName() {
		return name;
	}

	public Collection<String> getParameters() {
		return parameters;
	}

	public Collection<String> getRhsItems() {
		return rhsItems;
	}

	@Override
	public String toString() {
		return getRepresentation();
	}

	public String getRepresentation() {
		boolean first = true;
		StringBuffer sb = new StringBuffer();
		// if (t.getCommentLines() != null && t.getCommentLines().size() > 0) {
		// for (String s : t.getCommentLines()) {
		// sb.append("% ").append(s).append("\n");
		// }
		// }
		sb.append("\nstep ").append(getName());
		first = true;
		if (getParameters() != null && getParameters().size() > 0) {
			sb.append("(");
			for (String s : getParameters()) {
				if (!first) {
					sb.append(", ");
				}
				sb.append(s);
				first = false;
			}
			sb.append(")");
		}
		sb.append(" :=\n");
		first = true;
		if (getLhsItems() != null && getLhsItems().size() > 0) {
			for (String s : getLhsItems()) {
				if (!first) {
					sb.append(".\n");
				}
				sb.append("\t").append(s);
				first = false;
			}
		}
		if (getConditions() != null && getConditions().size() > 0) {
			for (String s : getConditions()) {
				if (!first) {
					sb.append(" &\n");
				}
				sb.append("\t").append(s);
				first = false;
			}
		}
		sb.append("\n\t=");
		first = true;
		if (getExistsVarNames() != null && getExistsVarNames().size() > 0) {
			sb.append("[exists ");
			for (String s : getExistsVarNames()) {
				if (!first) {
					sb.append(", ");
				}
				sb.append(s);
				first = false;
			}
			sb.append("]=");
		}
		sb.append(">\n");
		first = true;
		if (getRhsItems() != null && getRhsItems().size() > 0) {
			for (String s : getRhsItems()) {
				if (!first) {
					sb.append(".\n");
				}
				first = false;
				sb.append("\t").append(s);
			}
		}
		sb.append("\n");
		return sb.toString();
	}
}


text:
<?php require 'form.php'; ?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="apple-touch-icon" href="apple-touch-icon.png">

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

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/style.css">
        <link rel="stylesheet" href="css/contact.css">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
                  Toggle navigation

                </button>

About The Game

Contact Us

FAQ

Book Now!

FAQ

What is an "Escape Room" game ?

Participants are placed in an environment to solve a real-life quest within 60 minutes. They must work together to find hidden clues, solve puzzles using strategy, creativity, and logic to win the game!

Why we are different:

The focus on our game is not escaping a room but saving Christmas, and it's more suitable for all ages. From the most experienced player to a complete noviceWe are an experience that enjoyed by all ages and surpasses the limits of DzEscaping a Roomdzto make the participants the heroes of their own story. You don't just Dzescapedz you save the day.

What is the puzzle?

Children and adults must help Santa Claus save Christmas by convincing a grumpy elf that the Christmas spirit is alive and well. Parents can help children win the game or watch the game progress while enjoying a drink in The Back Stage Lounge.

How does the game work?

Arrive 10 minutes earlier to your scheduled game time to be welcomed at thelounge. Confirm the name of the person who made your reservation, and when everybody is gathered we will start a brief explanation of the game and how everything works. You don`t have to bring anything with you, just your wits and curiosity.

Can I take pictures/notes/use my smart phone?

Sure! While the puzzles aren't designed to require the use of a smart phone or taking notes, do whatever makes you feel confident. We ask that you do be careful what pictures you post to social media so as to not accidentally spoil the puzzles for future players, but otherwise have fun and share your experience!

What happens when the game starts?

Once the game begins and the timer starts counting down, everything is on you and your teammates. Figure out how to save Christmas!

There is no physical strength needed for any of our games. Just explore your environment and solve the puzzles. If you need help, hints can be asked for by the Game Master. There's no limit of hints you can request, but hints will be recorded to the leader board, so try and solve the game using as few as possible!

Do I need to make a reservation?

Yes, games are usually booked days in advance so we may not be able to accommodate your group without one.

Can I make a reservation the same day?

Yes, just check the availability online.

Can I bring kids along to Save Christmas?

Of course! But remember, children under 10 need to be an accommodated by an adult because otherwise they may not be able to solve the puzzles on their own.

What happens if I show up late for the game?

Please note that our games are live games and in session with a set time schedule. Unfortunately, if you are late, we cannot extend your game time because we have to get the room ready for the next appointment. We recommend using the remaining time in your session and a generous use of available hints!

Can I change or cancel my reservation?

We can change your reservation, depending upon our availability. You must contact us at least 48 hours prior to game time to change your reservation.

Can I make a corporate team-building reservation?

Yes! Please email us for special corporate team-building sessions.

Can I make a reservation for a special occasion or for a large group?

Yes! We are available to help you with private parties, including catering options.

Is your location wheelchair accessible?

Yes, we are fully wheelchair accessible.

Can I come alone?

Yes, but we recommend having at least two people, otherwise puzzles can be too challenging to overcome in the hour. Plus, Christmas is a season for sharing after all!

Santa Puzzle Room

About The Game

Contact Us

FAQ

Book Now


text:
"""Code to build STL-10 dataset."""

import os

import numpy as np
from tensorflow_datasets.core.utils.lazy_imports_utils import tensorflow as tf
import tensorflow_datasets.public_api as tfds

_CITATION = """
@inproceedings{coates2011stl10,
  title={{An Analysis of Single Layer Networks in Unsupervised Feature Learning}},
  author={Coates, Adam and Ng, Andrew and Lee, Honglak},
  booktitle={AISTATS},
  year={2011},
  note = {\\url{https://cs.stanford.edu/~acoates/papers/coatesleeng_aistats_2011.pdf}},
}
"""

_DESCRIPTION = """\
The STL-10 dataset is an image recognition dataset for developing unsupervised
feature learning, deep learning, self-taught learning algorithms. It is inspired
by the CIFAR-10 dataset but with some modifications. In particular, each class
has fewer labeled training examples than in CIFAR-10, but a very large set of
unlabeled examples is provided to learn image models prior to supervised
training. The primary challenge is to make use of the unlabeled data (which
comes from a similar but different distribution from the labeled data) to build
a useful prior. All images were acquired from labeled examples on ImageNet.
"""

URL = "http://ai.stanford.edu/~acoates/stl10/stl10_binary.tar.gz"
UNLABELLED = tfds.Split("unlabelled")

class Stl10(tfds.core.GeneratorBasedBuilder):
  """STL-10 dataset."""

  VERSION = tfds.core.Version("1.0.0")

  def _info(self):
    return tfds.core.DatasetInfo(
        builder=self,
        description=_DESCRIPTION,
        features=tfds.features.FeaturesDict({
            "image": tfds.features.Image(shape=(96, 96, 3)),
            "label": tfds.features.ClassLabel(num_classes=10),
        }),
        supervised_keys=("image", "label"),
        homepage="http://ai.stanford.edu/~acoates/stl10/",
        citation=_CITATION,
    )

  def _split_generators(self, dl_manager):
    """Returns SplitGenerators."""
    train_files = ["train_X.bin", "train_y.bin"]
    test_files = ["test_X.bin", "test_y.bin"]
    unlabeled_files = ["unlabeled_X.bin"]

    stl10_path = dl_manager.download_and_extract(URL)
    stl10_path = os.path.join(stl10_path, "stl10_binary/")

    def gen_filenames(filenames):
      for f in filenames:
        yield os.path.join(stl10_path, f)

    # Adds the class names to the feature description.
    with tf.io.gfile.GFile(next(gen_filenames(["class_names.txt"])), "r") as f:
      class_names = [l.strip("\n") for l in f]
    self.info.features["label"].names = class_names

    # Define the splits
    splits = [
        tfds.core.SplitGenerator(
            name=tfds.Split.TRAIN,
            gen_kwargs={"filepaths": gen_filenames(train_files)}),
        tfds.core.SplitGenerator(
            name=tfds.Split.TEST,
            gen_kwargs={"filepaths": gen_filenames(test_files)}),
        tfds.core.SplitGenerator(
            name=UNLABELLED,
            gen_kwargs={"filepaths": gen_filenames(unlabeled_files)}),
    ]

    return splits

  def _generate_examples(self, filepaths):
    """Generate STL-10 examples as dicts.

    Args:
      filepaths (list[str]): The files to use to generate the data.

    Yields:
      The STL-10 examples, as defined in the dataset info features.
    """
    filepaths = list(filepaths)
    image_path = filepaths[0]
    label_path = filepaths[1] if len(filepaths) > 1 else None

    with tf.io.gfile.GFile(image_path, "rb") as f:
      images = np.frombuffer(f.read(), dtype=np.uint8)
      images = np.reshape(images, (-1, 3, 96, 96))
      images = np.transpose(images, (0, 3, 2, 1))

    if label_path:
      with tf.io.gfile.GFile(label_path, "rb") as f:
        labels = np.copy(np.frombuffer(f.read(), dtype=np.uint8))
        # Switch to zero-based indexing.
        labels -= 1
    else:
      labels = None

    for index, image in enumerate(images):
      yield index, {
          "image": image,
          "label": labels[index] if labels is not None else -1,
      }


text:
package net.jini.print.attribute.standard;

import java.util.Set;
import javax.print.attribute.Attribute;
import javax.print.attribute.SupportedValuesAttribute;
import net.jini.print.attribute.CollectionSyntax;
import net.jini.print.attribute.Dimension;
import net.jini.print.attribute.Dimension.UNIT;
import net.jini.print.attribute.OneSetOfSyntax;

/**
 * Indicates the sizes supported by the Printer. A requested media size
 * dimension matches a supported media dimension if it is within an
 * implementation-defined tolerance. For example, PostScript [redbook] specifies
 * a tolerance of 5 points (5/72 of an inch = 1.7 mm) of a supported dimension,
 * i.e., within 176 units of the value of the dimension.
 *
 * @see MediaSize
 */
public class MediaSizeSupported extends OneSetOfSyntax implements SupportedValuesAttribute {

    public MediaSizeSupported(Set<MediaSizeTolerances> supported) {
	super(supported);
    }

    @Override
    public Class<? extends Attribute> getCategory() {
	return MediaSizeSupported.class;
    }

    @Override
    public String getName() {
	return "media-size-supported";
    }

    public static class MediaSizeTolerances extends CollectionSyntax {

	private final ToleranceRange xtol;
	private final ToleranceRange ytol;

	public MediaSizeTolerances(XdimensionTolerance xtol, YdimensionTolerance ytol) {
	    this(notNull(xtol), notNull(ytol));
	}

	private static ToleranceRange notNull(ToleranceRange range){
	    if (range == null) throw new NullPointerException ("tolerance cannot be null");
	    return range;
	}

	private MediaSizeTolerances(ToleranceRange xtol, ToleranceRange ytol){
	    this.xtol = xtol;
	    this.ytol = ytol;
	}

	@Override
	protected Attribute[] getAttributes() {
	    return new Attribute[]{xtol, ytol};
	}

	public boolean supports(MediaSize size){
	    return xtol.within(size.getXdimension()) && ytol.within(size.getYdimension());
	}

    }

    /**
     * Indicates the size of the media in hundredths of a millimeter along the
     * bottom edge of the media. This is equivalent to 1/2540 th of an inch
     * resolution. The rangeOfInteger attribute syntax accommodated variable
     * size implementations, such as printers supporting adjustable input trays
     * and web printers. See section 2.4 regarding the coordinate system and
     * section 5.1 regarding user-define media sizes.
     */
    public static class XdimensionTolerance extends ToleranceRange {

	/**
	 *
	 * @param min
	 * @param max
	 * @param units
	 */
	public XdimensionTolerance(int min, int max, UNIT units) {
	    super(new Dim(min, units), new Dim(max, units));
	}

	public XdimensionTolerance(UNIT units, int value, int plusMinus) {
	    super(new Dim(value - plusMinus, units), new Dim(value + plusMinus, units));
	}

	public XdimensionTolerance(int dim, UNIT units) {
	    super(new Dim(dim, units), null);
	}

	/**
	 *
	 * @return XdimensionTolerance.class
	 */
	@Override
	public Class<? extends Attribute> getCategory() {
	    return XdimensionTolerance.class;
	}

	/**
	 *
	 * @return "x-dimension"
	 */
	@Override
	public String getName() {
	    return "x-dimension";
	}
    }

    /**
     * Indicates the size of the media in hundredths of a millimeter along the
     * left edge of the media. This is equivalent to 1/2540 th of an inch
     * resolution. The rangeOfInteger attribute syntax accommodated variable
     * size implementations, such as printers supporting adjustable input trays
     * and web printers. See section 2.4 regarding the coordinate system and
     * section 5.1 regarding user-defined media sizes.
     */
    public static class YdimensionTolerance extends ToleranceRange {

	public YdimensionTolerance(int min, int max, UNIT units) {
	    super(new Dim(min, units), new Dim(max, units));
	}

	public YdimensionTolerance(UNIT units, int value, int plusMinus) {
	    super(new Dim(value - plusMinus, units), new Dim(value + plusMinus, units));
	}

	public YdimensionTolerance(int dim, UNIT units) {
	    super(new Dim(dim, units), null);
	}

	/**
	 *
	 * @return YdimensionTolerance.class
	 */
	@Override
	public Class<? extends Attribute> getCategory() {
	    return YdimensionTolerance.class;
	}

	/**
	 *
	 * @return "y-dimension"
	 */
	@Override
	public String getName() {
	    return "y-dimension";
	}
    }

    private static class Dim extends Dimension {

	public Dim(int i, UNIT unit) {
	    super(i, unit);
	}

    }

    private static abstract class ToleranceRange implements Attribute {

	private final Dim min;
	private final Dim max;

	private ToleranceRange(Dim min, Dim max) {
	    this.min = min;
	    this.max = max;
	}

	boolean within(int value){
	    return (value > min.getValue()) && (value < max.getValue());
	}

	@Override
	public String toString() {
	    StringBuilder sb = new StringBuilder();
	    sb.append(min);
	    if (max != null) {
		sb.append('-').append(max);
	    }
	    return sb.toString();
	}
    }

}


text:
"use strict";

var ignoredTypes = [{
    nodeType: "node",
    type: "ExperimentalSpreadProperty"
}, {
    nodeType: "value",
    type: "FunctionExpression",
    flag: "ignoreMethods"
}];

/**
 * Checks node whether a certain type should be ignored or not.
 * @param {Node} curr: Current node.
 * @param {Node} prev: Previous node.
 * @param {object} flags: Only ignores a type if its corresponding {flag:xxx} property found in this `flags` object
 * @returns {Boolean} true/false value
 */
module.exports = function checkIgnoredType(curr, prev, flags) {
    for (var i = 0, length = ignoredTypes.length; i < length; i++) {
        var ignoredType = ignoredTypes[i];
        var type = ignoredType.type;
        var flag = ignoredType.flag;

        if (flags && flag && !flags[flag]) {
            continue;
        }

        var node = {};
        if (ignoredType.nodeType === "node") {
            node.curr = curr;
            node.prev = prev;
        } else if (ignoredType.nodeType === "key") {
            node.curr = curr.key;
            node.prev = prev.key;
        } else if (ignoredType.nodeType === "value") {
            node.curr = curr.value;
            node.prev = prev.value;
        } else {
            continue;
        }

        if (type === node.curr.type) {
            return true;
        }
        if (type === node.prev.type) {
            return true;
        }
    }
    return false;
};


text:
(function() {
  'use strict';

  /**
   * Initialization of badgeFrontend.core.interceptors module.
   *
   * @namespace Modules
   */
  angular
    .module('badgeFrontend.core.interceptors', []);
}());


text:
<?php

declare(strict_types=1);

namespace Mwop\Github;

use JsonSerializable;
use Stringable;

use function preg_match;
use function sprintf;

class AtomEntry implements JsonSerializable, Stringable
{
    private const TEMPLATE = '
%s
';

    /** @var null|non-empty-string */
    public readonly ?string $link;

    /** @param non-empty-string $link */
    public function __construct(
        string $link,
        /** @var non-empty-string */
        public readonly string $title,
        /** @var non-empty-string */
        public readonly string $content,
    ) {
        $this->link = preg_match('#weierophinney/#', $link) ? null : $link;
    }

    public function __toString(): string
    {
        return sprintf(self::TEMPLATE, $this->link, $this->title);
    }

    public function jsonSerialize(): array
    {
        return [
            'link'    => $this->link,
            'title'   => $this->title,
            'content' => $this->content,
        ];
    }
}


text:
<?php

namespace Pms\Api;

use Silex\Application as SilexApplication;
use Pms\Api\Provider\Login\LoginBuilder;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class Application extends SilexApplication
{
    public function __construct(array $values = [])
    {
        parent::__construct($values);

        LoginBuilder::mountProviderIntoApplication('/auth', $this);

        $this->after(function (Request $request, Response $response) {
            $response->headers->set('Access-Control-Allow-Origin', '*');
        });
    }
}