Exemple #1
0
/**
 Save to file structures at step tmpStep
 @version 2.0
 @param string tmpSavingPath Saving files path
 @param environment *tmpEnvironment environment instance reference
 @param tmpSim Current simulation
 @param acs_int Current step
 @date 2013/07/13
 */
void saveToFile(string tmpSavingPath, environment *tmpEnvironment, acs_int tmpGen, acs_int tmpSim, acs_int tmpStep)
{
	// SAVE TO FILE INITIAL CONDITIONS
	if(!tmpEnvironment->saveSpeciesStructureSTD(tmpGen, tmpSim, tmpStep, tmpSavingPath))
		ExitWithError("saveSpeciesStructure", "PROBLEM WITH SAVING SPECIES STRUCTURE TO FILE");
	if(!tmpEnvironment->saveReactionsStructureSTD(tmpGen, tmpSim, tmpStep, tmpSavingPath))
		ExitWithError("saveReactionsStructure", "PROBLEM WITH SAVING REACTIONS STRUCTURE TO FILE");
	if(!tmpEnvironment->saveCatalysisStructureSTD(tmpGen, tmpSim, tmpStep, tmpSavingPath))
		ExitWithError("saveCatalysisStructure", "PROBLEM WITH SAVING CATALYSIS STRUCTURE TO FILE");	
}
Exemple #2
0
int
main(int argc, char **argv)
{ char *home, *path;
  int pathsize;

  if (argc != 3) usage(argv[0]);
  ContentType = argv[1];
  FileName=argv[2];

  pathsize = strlen(STDPATH);
  home = getenv("HOME");
  if (home) {
    pathsize += strlen(home) + strlen("/.mailcap:");
  }
  path = malloc(1+pathsize);
  if (!path) ExitWithError(nomem);

  if (home) {
    strcat(path, home); strcat(path, "/.mailcap:");
  }
  strcat(path, STDPATH);

  if (ProcessMailcapFiles(path) &&
      BuildCommand(mc.command, FileName)) {
    puts(Command);
    return 0;
  } else {
    return 1;
  }
}
Exemple #3
0
void species::resetToInitConc(acs_double tmpVolumeBeforeDivision, acs_double tmpVolume, bool tmpRndConcentration, acs_double tmpTheta, acs_int tmpStochDivision, MTRand& tmp_rndDoubleGen){

	if(tmpTheta == 0) // IF division is not considered
	{
		concentration=firstConcentration;
		concToNum(tmpVolume, tmp_rndDoubleGen);
		if(tmpRndConcentration){amount = random_poisson(acs_double(amount),tmp_rndDoubleGen);}
		numToConc(tmpVolume);
	}else{
		if(!concentrationFixed)
		{
			if (amount >= 1)
			{
				if(tmpStochDivision==1) // IF stochastic division
				{
					amount = random_poisson(acs_double(amount/(tmpVolumeBeforeDivision/tmpVolume)),tmp_rndDoubleGen);
					numToConc(tmpVolume);
				}else{
					if(amount > 1){amount = acsround((acs_double)amount/(tmpVolumeBeforeDivision/tmpVolume),tmp_rndDoubleGen);}
					else{if(tmp_rndDoubleGen() < (tmpVolume/tmpVolumeBeforeDivision)){amount = 1;}else{amount = 0;}}
					numToConc(tmpVolume);
				}
			}else{
				if(amount != 0){
					ExitWithError("species::resetToInitConc","FATAl ERROR: The amount the molecules should be 0!!!");
				}
			}
		}else{
			concToNum(tmpVolume,tmp_rndDoubleGen);
		}
	}
}
Exemple #4
0
int LYTestMailcapCommand( char *testcommand, char *params )
{
  int eax;
  int result;
  char TmpFileName[256];
  HTChunk *expanded = 0;
  if ( LYMailcapUsesPctS( testcommand ) & 255 )
  {
    if ( LYOpenTemp( TmpFileName, ".html", "w" ) == 0 )
    {
      ExitWithError( gettext( "Can't open temporary file!" ) );
    }
    LYCloseTemp( TmpFileName );
  }
  else
    TmpFileName[0] = 0;
  expanded = HTChunkCreate( 1024 );
  result = BuildCommand( expanded, testcommand, TmpFileName, params );
  if ( result )
  {
    result = 1;
    if ( WWW_TraceFlag == 0 || ( WWW_TraceMask & 8 ) == 0 )
    {
      HTChunkFree( expanded );
      LYRemoveTemp( TmpFileName );
      return result;
    }
    fprintf( TraceFP( ), "PassesTest: Deferring test command: %s\n", &expanded->data );
  }
  else
  {
    if ( WWW_TraceFlag && ( WWW_TraceMask & 8 ) )
    {
      fprintf( TraceFP( ), "PassesTest: Executing test command: %s\n", &expanded->data );
    }
    result = LYSystem( &expanded->data );
    if ( result )
    {
      result = -1;
      if ( WWW_TraceFlag == 0 || ( WWW_TraceMask & 8 ) == 0 )
      {
        HTChunkFree( expanded );
        LYRemoveTemp( TmpFileName );
        return result;
      }
      fprintf( TraceFP( ), "PassesTest: Test failed!\n" );
    }
    else
    {
      if ( WWW_TraceFlag == 0 || ( WWW_TraceMask & 8 ) == 0 )
      {
        HTChunkFree( expanded );
        LYRemoveTemp( TmpFileName );
        return result;
      }
      fprintf( TraceFP( ), "PassesTest: Test passed!\n" );
    }
  }
}
Exemple #5
0
void TryDirectory(struct ORACLEALLINONE *oraAllInOne, char* pDirectory)
{
	sb1 vFlag;
	char* ptr;

	struct BINDVARIABLE bindVariablesTryDirectory[] =
	{
		{ 0, SQLT_STR, ":directory", pDirectory, ORA_IDENTIFIER_SIZE + 1 },
		{ 0 }
	};

	struct ORACLEDEFINE oraDefinesTryDirectory[] =
	{
		{ 0, SQLT_INT, &vFlag, sizeof(vFlag), 0 },
                { 0 }
        };

	struct ORACLESTATEMENT oraStmtTryDirectory = { "\
SELECT MIN(DECODE(directory_name, :directory, 1, 2))\n\
  FROM all_directories\n\
 WHERE directory_name IN (:directory, UPPER(:directory))\
",
	       0, bindVariablesTryDirectory, oraDefinesTryDirectory };

        PrepareStmtAndBind(oraAllInOne, &oraStmtTryDirectory);

        if (ExecuteStmt(oraAllInOne))
                ExitWithError(oraAllInOne, RET_ORA, ERROR_OCI, "Failed to get an Oracle Directory\n");

        ReleaseStmt(oraAllInOne);

	switch (vFlag)
	{
	case 1:
		break;
	case 2:
		ExitWithError(oraAllInOne, RET_DONOTEXIT, ERROR_NONE, "WARNING: directory \"%s\" not found, converting to uppercase\n", pDirectory);
		for (ptr = pDirectory; *ptr; ptr++)
			*ptr = toupper(*ptr);
		break;
	default:
		ExitWithError(oraAllInOne, RET_ORA, ERROR_NONE, "Directory \"%s\" does not exist\n", pDirectory);
	}
}
Exemple #6
0
/* Handle client request */
void * HandleRequest(void *args) {
  char str[BUFSIZE];
  TSocket cliSock;

  /* Extract socket file descriptor from argument */
  cliSock = ((struct TArgs *) args) -> cliSock;
  free(args);  /* deallocate memory for argument */

  for(;;) {
    /* Receive the request */
    if (ReadLine(cliSock, str, BUFSIZE-1) < 0) { 
      ExitWithError("ReadLine() failed"); 
    } else {
      executa(str);
    }
 
    /* Send the response */
    if (WriteN(cliSock, str, strlen(str)) <= 0)  
      { ExitWithError("WriteN() failed"); }  
  }
}
Exemple #7
0
int main(int argc, char *argv[]) {
  TSocket sock;
  char *servIP;                /* server IP */
  unsigned short servPort;     /* server port */
  char str[100];
  int n;

  if (argc != 3) {
    ExitWithError("Usage: client <remote server IP> <remote server Port>");    
  }

  servIP = argv[1];
  servPort = atoi(argv[2]);

  /* Create a connection */
  sock = ConnectToServer(servIP, servPort);

  for(;;) {
   /* Write msg */
   scanf("%99[^\n]%*c",str);
   n = strlen(str);
   str[n] = '\n';
   if (WriteN(sock, str, ++n) <= 0)
     { ExitWithError("WriteN() failed"); }
   if (strncmp(str, "quit", 4) == 0) break;

   /* Receive the response */
   if (ReadLine(sock, str, 99) < 0)
    { ExitWithError("ReadLine() failed");
   } else printf("%s",str);
   
  }

  close(sock);
  return 0;
}
Exemple #8
0
char *GetCommand( char *s, char **t )
{
  char *s2;
  int quoted = 0;
  s = LYSkipBlanks( s );
  s2 = malloc( ( ( strlen( s ) * 2 ) + 1 ) * sizeof( char ) );
  if ( s2 == 0 )
  {
    ExitWithError( gettext( "Memory exhausted!  Program aborted!" ) );
  }
  t[0] = s2;
  while ( s && s[0] )
  {
    if ( quoted )
    {
      if ( s[0] == '%' )
      {
        s2[0] = '%';
        s2++;
      }
      s2[0] = s[0];
      s2++;
      s++;
      quoted = 0;
    }
    else
    if ( s[0] == ';' )
    {
      s2[0] = 0;
      s++;
      return s;
    }
    if ( s[0] == '\\' )
    {
      quoted = 1;
      s++;
    }
    else
    {
      s2[0] = s[0];
      s2++;
      s++;
    }
  }
  s2[0] = 0;
  return 0;
}
Exemple #9
0
VirtualCamera::VirtualCamera(MicroDisplayInit& mdi, string imgname)
{
	BufferLength = mdi.MaxPics;
	WIDTH = mdi.width;
	stringstream ss;
	ss << "virtualcameras/" << imgname;
	ss >> imgname;
	if (mdi.colorType == MicroDisplayInit::GRAY)
		buffer = cv::imread(imgname, 0);
	else
		buffer = cv::imread(imgname, 1);
	if (buffer.cols == 0 || buffer.rows == 0)
	{
		ss << "£ºÐéÄâÏà»úµ×Ƭ²»´æÔÚ£¡";
		ExitWithError(ss.str());
	}
	if (buffer.cols != WIDTH || buffer.rows < BufferLength)
	{
		cv::resize(buffer, buffer, cv::Size(WIDTH, BufferLength));
	}
	cv::Mat t = buffer;
}
Exemple #10
0
/**
 * 
 * @update	gess 01/04/99
 * @param 
 * @return
 */
void initializeSettings(int argc,char* argv[]){
  bool theURLFileIsValid=false;
  ComputeEXEDirectory(argv[0],gMTBFDirectory);
  sprintf(gReportPath,"%s%s",gMTBFDirectory,gReportFilename);
  sprintf(gURLPath,"%s%s",gMTBFDirectory,gURLFilename);

  for(int i=0;i<argc;i++){
    if(0==strnicmp(argv[i],"-f",2)){
      //determine which url file to use...
      strcpy(gURLPath, argv[i+1]);
      fstream in(gURLPath,ios::in);
      char buf[500];
      buf[0]=0;
      in>>buf;
      if(!buf[0]){
        ExitWithError("Unable to read the given URL file",gURLPath);
      }
      else {
	theURLFileIsValid=true;
      }
      
    }
    else if(0==strnicmp(argv[i],"-r",2)){
Exemple #11
0
char *
GetCommand(char *s, char **t)
/* Extract a command
 *   On entry-
 *     s points to the input string
 *   On exit-
 *     GetCommand points to the string following the command
 *       (which may be null)
 *     *t points to the command string
 ***/
{ char *s2;
  int quoted = 0;

  while (s && *s && isspace((unsigned char) *s)) ++s;
  s2 = malloc(strlen(s)*2+1); /* absolute max, if all % signs */
  if (!s2) ExitWithError(nomem);
  *t = s2;
  while (s && *s) {
    if (quoted) {
      *s2++ = *s++;
      quoted = 0;
    } else {
      if (*s == ';') {
        *s2 = 0;
	return(++s);
      }
      if (*s == '\\') {
        quoted = 1;
	++s;
      } else {
	*s2++ = *s++;
      }
    }
  }
  *s2 = 0;
  return(NULL);
}	
Exemple #12
0
int
CtypeMatch(void)
/* Verify the content type
 *   On entry-
 *     ContentType is the desired content type
 *     mc contains a decoded mailcap entry
 *   If the mailcap entry denotes the desired content type then on exit-
 *     CtypeMatch=1
 *   Else on exit-
 *     CtypeMatch=0
 ***/
{ int len, retcode = 0;
  char *pat = mc.contenttype, *pat2 = NULL;

  if (!lc2strcmp(ContentType, pat)) { /* exact match, case-insensitive */
    return(1);
  }
  if (index(pat, '/') == NULL) { /* implicit wildcard */
    pat2 = malloc(3 + strlen(pat));
    if (!pat2) ExitWithError(nomem);
    strcpy(pat2, pat);
    strcat(pat2, "/*");
    pat = pat2;
  }
  len = strlen(pat);
  if ((pat[--len] == '*') &&
      (pat[--len] == '/') &&
      (!lc2strncmp(ContentType, pat, len)) &&
      ((ContentType[len] == '/') || (ContentType[len] == '\0'))) {
    retcode = 1;
  } else {
    retcode = 0;
  }
  if (pat2) free(pat2);
  return retcode;
}
Exemple #13
0
/**
 Save to file all the INITIAL structures
 @version 2.0
 @param string tmpSavingPath Saving files path
 @param environment *tmpEnvironment environment instance reference
 @param tmpSim Current simulation
 @param acs_int Current step
 @date 2013/07/03
 */
void saveInitialConditionsToFile(string tmpSavingPath, environment *tmpEnvironment, acs_int tmpGen, acs_int tmpSim, acs_int tmpStep)
{
	// SAVE TO FILE INITIAL CONDITIONS
	if(!tmpEnvironment->saveConfigurationFileSTD(tmpSavingPath))
		ExitWithError("saveConfigurationFile", "PROBLEM WITH SAVING CONFIGURATION FILE");	
	if (tmpEnvironment->getInflux() > 0)
	{
		if(!tmpEnvironment->saveInfluxStructureSTD(tmpSavingPath))
			ExitWithError("saveInfluxStructure", "PROBLM WITH SAVING SPECIES INFLUX FILE");
	}
	if(tmpEnvironment->getEnergy() <= 1)
	{
		if(!tmpEnvironment->saveNrgBoolFncStructureSTD(tmpSavingPath))
			ExitWithError("saveNrgBoolFncStructure", "PROBLM WITH SAVING ENERGY BOOLEAN FUNCTIONS FILE");
	}
	if(!tmpEnvironment->saveSpeciesStructureSTD(tmpGen, tmpSim, tmpStep, tmpSavingPath))
		ExitWithError("saveSpeciesStructure", "PROBLEM WITH SAVING INITIAL SPECIES STRUCTURE TO FILE");
	if(!tmpEnvironment->saveReactionsStructureSTD(tmpGen, tmpSim, tmpStep, tmpSavingPath))
		ExitWithError("saveReactionsStructure", "PROBLEM WITH SAVING INITIAL REACTIONS STRUCTURE TO FILE");
	if(!tmpEnvironment->saveCatalysisStructureSTD(tmpGen, tmpSim, tmpStep, tmpSavingPath))
		ExitWithError("saveCatalysisStructure", "PROBLEM WITH SAVING INITIAL CATALYSIS STRUCTURE TO FILE");
}
Exemple #14
0
int main (int argc, char *argv[]) {

	setlocale(LC_NUMERIC,"en_US"); //TR Check whether or not it can be removed when C++ standard

	MTRand rndDoubleGen; /// double random number generator

	/*---------------\
    |                |
	| INITIALIZATION |
    |       		 |
	\ --------------*/ 

	/*----------------
		CREATE ENVIRONMENT
		-----------------*/ 

	// Declare and inizialize the environment
	environment* puddle = new environment(argv[1]);

	//INITIZIALIZE PSEUDO RANDOM NUMBER GENERATOR
	rndDoubleGen.seed(puddle->getRandomSeed());

	/*----------------------------------
		CREATE INITIAL MOLECULE POPULATION
		----------------------------------*/

	//LOAD SPECIES FROM FILE
	if(!puddle->createInitialMoleculesPopulationFromFileSTD(argv[3], rndDoubleGen))
		ExitWithError("createInitialMoleculesPopulationFromFile", "Problem with the species STANDARD loading process");
	// LOAD INFLUX LAYERS FROM FILE (if the system is open with a simulated flux)

	if((puddle->getSysArch() == PROTOCELLFLUXFINITE) || (puddle->getSysArch() == CSTRSYSTEM))
	{
		if(!puddle->createInfluxLayersFromFileSTD(argv[3]))
			ExitWithError("CreateInfluxLayersFromFile", "Problem with influx layers loading process");
	}

	// LOAD BOOLEAN FUNCTION CONCERNING THE ENERGY CONFIGURATION
	if(puddle->getEnergy() <= 1)
	{
		//if(!puddle->createNrgBooleanFunctionsFromFile(a.arguments().at(3)))
		if(!puddle->createNrgBooleanFunctionsFromFileSTD(argv[3]))
			ExitWithError("createNrgBooleanFunctionsFromFile", "Problem with rct Bool fncs loading process");
	}
	//LOAD REACTIONS STRUCTURE FROM FILE (standard C++ libraries)
	if(!puddle->createInitialReactionsLayerFromFileSTD(argv[3]))
		ExitWithError("createInitialReactionLayerFromFile", "Problem with the reactions loading process");

	//LOAD CATALYSIS STRUCTURE FROM FILE (catalysis links species with reactions catalyzed)
	if(!puddle->createInitialCatalysisLayerFromFileSTD(argv[3]))
		ExitWithError("createInitialCatalysisLayerFromFile", "Problem with the catalysis loading process");

	if(puddle->getDebugLevel() >= MEDIUM_DEBUG){puddle->printInitialCondition();}

	// SAVE TO FILE INITIAL CONDITIONS
	saveInitialConditionsToFile(argv[2], puddle, 0, 0, 0);

	if(!puddle->structureCoherenceCheckUp())
	{
		cout << endl;
		ExitWithError("structureCoherenceCheckUp", "PROBLEM WITH STRUCTURE COHERENCE... THE SIMULATION WILL BE ABORTED!!!");
	}


	// - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - 

	/*------------\
	|            |
	| SIMULATION |
	|            |
	\ ----------*/

	//STORE INITIAL STRUCTURES DATA IN ORDER TO REINITIALIZE THE STRUCTURE AFTER EACH SIMULATION
	puddle->storeInitialStructures();

	Timer timer;
	acs_double timeElapsed;

	if(puddle->getDebugLevel() >= RUNNING_VERSION)
	{
		cout << endl;
		cout << "*** SIMULATION START ***" << endl;
		cout << endl;
	}

	// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+
	// SIMULATIONS
	// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+

	acs_int totalNumberOfSimulations = puddle->getNsim(); // Simulation counter
	acs_int totalNumberOfGenerations = puddle->getNgen(); // generation are not used now (it will be usefull with protocell division)
	acs_int actSTEP; // declare simulation step
	acs_int previousStepLastStructuresSaving; // declare previousStep
	acs_int previousStepLastTimesSaving; // declare previousStep
	acs_int previousStepLastAmountSaving; // declare previousStep
	acs_int previousStepLastBufferTimesSaving; // declare previousStep
	acs_int previousStepLastBufferRctSaving; // declare previousStep
	acs_int previousStepLastBufferAmountSaving; // declare previousStep
	bool growing = false; // This variable is used to stop the growth of the protocell

	for(acs_int actSIM = 1; actSIM <= puddle->getNsim(); actSIM++)
	{
		if(puddle->getDebugLevel() >= RUNNING_VERSION){cout << "\n|- - - - - - - - - - - - - - - " << endl;}
		if(puddle->getDebugLevel() >= RUNNING_VERSION){cout << "|- SIMULATION NUMBER " << actSIM << endl;}
		if(puddle->getDebugLevel() >= RUNNING_VERSION){cout << "|- - - - - - - - - - - - - - - \n" << endl;}


		// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+
		// GENERATIONS PER SIMULATIONS
		// +-+-+-+-+-+-+-+-+-+-+-+-+-+-


		for(acs_int actGEN = 1; actGEN <= totalNumberOfGenerations; actGEN++)
		{
			if(puddle->getVolumeGrowth()) growing = true;
			// IF THE ATTEMPTS ARE MORE THAN THE MAX NUMBER THIS SIMULATION IS STOPPED
			if((puddle->getCurrentAttempts() <= puddle->getMAXattempts()) || (puddle->getMAXattempts() == 0))
			{
				if(actGEN > 1)
				{
					// Reset structures stats and set concentrations to initial values
					puddle->resetConcentrationToInitialConditions(rndDoubleGen);
					puddle->clearGilScores();
					saveToFile(argv[2], puddle, actGEN, actSIM, 0);

				}
				acs_double dataStoredCounter = 0;
				acs_double TimesStoredCounter = 0;
				acs_double AmountsStoredCounter = 0;
				acs_int bufferTimesCountRow = 0;
				acs_int bufferSpeciesCountRow = 0;
				if(puddle->getDebugLevel() >= MINIMAL_PROMPT)
				{
					cout << "|- GEN NUMBER " << actGEN << " OF " << puddle->getNgen()
                         << " - SIM NUMBER " << actSIM << " OF " << totalNumberOfSimulations << endl;
				}

				// start timer
				timer.start();
				actSTEP = 1;
				previousStepLastStructuresSaving = 1;
				previousStepLastTimesSaving = 1;
				previousStepLastAmountSaving = 1;
				previousStepLastBufferTimesSaving = 1;
				previousStepLastBufferRctSaving = 1;
				previousStepLastBufferAmountSaving = 1;

				// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
				// SECONDS / REACTIONS PER GENERATION
				// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-

				while(((puddle->getActualTime() <= puddle->getNseconds()) & (actSTEP <= puddle->getNreactions()) & (puddle->getVolumeGrowth() == 0))
						||
						growing)
				{
					timer.stop();
					timeElapsed = timer.getElapsedTimeInMilliSec();
					// IF PROTOCELL CHECK THE OVERALL CONCENTRATION. If the concentration is greater than a threshold, we assume that the protocell is going to be a stone and
					// the simulaiton is stopped.
					// double(puddle->getMols()+puddle->getNcpxMols())/(puddle->getVolume()*AVO)
					if(puddle->getTheta() > 0){

						if(double(puddle->getMols()+puddle->getNcpxMols())/(puddle->getVolume()*AVO) > MAXALLOWCONCENTRATION){
							cout << endl << endl <<  "-----------------------------------------------------------------------" << endl;
							cout << "| WARNING :: The protocell is going to be a stone, simulation will be stopped   |" << endl;
							cout << "-----------------------------------------------------------------------" << endl;
							ExitWithError("warning in overall concentration in protocell","main");
						}

					}

					// IF NUMBER OF MILLISECONDS IS LESS THAN THE MAX NUMBER
					if(( timeElapsed < (puddle->getMAXhours()*60*60)) || (puddle->getMAXhours() == 0))
					{
						//GILLESPIE COMPUTATION (CORE OF THE SOFTWARE)
						if(puddle->getDebugLevel() == SMALL_DEBUG)cout << "Step " << actSTEP << endl;
						try{
							// IF the system can expand its structures, se the old gillespie algorithm must be used
							if(puddle->getSystemExpFlag())
							{
								if(!puddle->performOPTGillespieComputation(rndDoubleGen, timer, actGEN, actSIM, actSTEP, argv[2]))
									ExitWithError("performGillespieComputation", "Problems with the Gillespie computation");
							}else{ // If structures are fixed new optimized Gillespie algorithm can be used
								if(!puddle->perform_FIXED_GillespieComputation(rndDoubleGen, timer, actGEN, actSIM, actSTEP, argv[2]))
									ExitWithError("performGillespieComputation", "Problems with the Gillespie computation");
							}
						}catch(exception&e){
							cout << "Source Code Line: " << __LINE__ << endl;
							cerr << "exceptioncaught:" << e.what() << endl;
							ExitWithError("MAIN function __ Gillespie computation","exceptionerrorthrown");
						}
						if(puddle->getDebugLevel() == SMALL_DEBUG)
							puddle->showGillEngagementInSpecies();

						// DISPLAY SIMULATION CONTROL VARIABLES
						if(puddle->getDebugLevel() >= RUNNING_VERSION)
						{
							if((actSTEP % PROMPT_TIME == 0) || (actSTEP == 1) ||
									(puddle->getMols() == puddle->getOverallLoadedMolsCounter()))
							{
								timer.stop();
								cout<< "--------------------------------------------------------------------" << endl
										<< "G: "<< actGEN << "/" << totalNumberOfGenerations
										<< " - S: " << actSIM << "/" << totalNumberOfSimulations
										<< " - T: " << puddle->getActualTime() << "/" << puddle->getNseconds()
										<< " - R: " << actSTEP // << "/" << puddle->getNreactions()
										<< " - CT (seconds): " << timer.getElapsedTimeInSec()
										<< " - Gill: " << puddle->getNumberOfGillespieCOPYpossibleRcts() << endl
										<< "\t- ENVIRONMENT" << endl
										<< "\t\t|- Volume: " << puddle->getVolume()
										<< " - Surface: " << puddle->getSurface()
										<< " - Lipids: " << puddle->getLipids() << endl
										<< "\t\t|- S: " << puddle->getNspecies()
										<< " - NS: " << puddle->getNnewSpecies()
										<< " - M: " << puddle->getMols()
										<< " - NM: " << puddle->getNewMols() << endl
										<< "\t\t|- Cp: " << puddle->getNcpx()
										<< " - #Cp: " << puddle->getNcpxMols() << endl
										<< "\t\t|- M: " << puddle->getTotalNumberOfMonomers()
										<< " - Mols+Complex: " << puddle->getMols() + puddle->getNcpxMols()
										<< " - Tot Conc: " << double(puddle->getMols()+puddle->getNcpxMols())/(puddle->getVolume()*AVO) << endl
										<< "\t- ENERGY" << endl
										<< "\t\t|- Loaded Mols: " << puddle->getOverallLoadedMolsCounter()
										<< " - Loaded (second Method): " << puddle->getTotNumberOfChargedMols() << endl
										<< "\t- GILLESPIE INFO" << endl
										<< "\t\t|- Gil Mean: " << puddle->getGillespieMean()
										<< " - Gil SD: " << puddle->getgillespieSD()
										<< " - Gil Entropy: " << puddle->getgillespieEntropy() << endl
										<< "\t\t|- Gil NS ratio: " << puddle->getRatioBetweenNewGillTotGill()
										<< " - Back and Forw Ratio: " << puddle->getRatioBetweenBackandForw() << endl
										<< "\t- REACTIONS COUNTERS" << endl
										<< "\t\t|- Theoretical Average Connectivity:" << (double)puddle->getNumberOfCatalysis() / puddle->getTotalNumberOfPossibleCatalysts() << endl
										<< "\t\t|- Cond: " << puddle->getCondensationCounter()
										<< " - Endo Cond: " << puddle->getEndoCondensationCounter() << endl
										<< "\t\t|- Cleav: " << puddle->getCleavageCounter()
										<< " - Endo Cleav: " << puddle->getEndoCleavageCounter() << endl
										<< "\t\t|- Spont Cleav: " << puddle->getSpontDissCounter()
										<< " - Spont Cond: "<< puddle->getSpontAssCounter() << endl
										<< "\t\t|- Cpx: " << puddle->getCpxFormCounter()
										<< " - Cpx Diss: " << puddle->getCpxDissCounter() << endl;

							}
						}

						// SAVE STRUCTURES TO FILE EVERY puddle->getTimeStructuresSavingInterval() SECONDS
						if(puddle->getActualTime() >= (puddle->getTimeStructuresSavingInterval() + dataStoredCounter) &&
								(puddle->getTimeStructuresSavingInterval() >= 0))
						{
							saveToFile(argv[2], puddle, actGEN, actSIM, actSTEP);
							dataStoredCounter = dataStoredCounter + puddle->getTimeStructuresSavingInterval();
							previousStepLastStructuresSaving = actSTEP; // save last step moment
						}

						// STORE ON FILE TIMES EVERY fileTimesSaveInterval seconds (if at least something happen)
						if(((puddle->getActualTime() >= (puddle->getFileTimesSavingInterval() + TimesStoredCounter)) ||
								(puddle->getActualTime() == 0) || (puddle->getFileTimesSavingInterval() == 0)) &&
								(puddle->getFileTimesSavingInterval() >= 0))
						{
							//cout << puddle->getActualTime() << " " << puddle->getFileTimesSavingInterval() << " " << TimesStoredCounter << endl;
							puddle->saveTimesSTD(actSTEP);
							if(puddle->getActualTime() > 0)
							{
								TimesStoredCounter = TimesStoredCounter + puddle->getFileTimesSavingInterval();
								previousStepLastTimesSaving = actSTEP;
							}
							bufferTimesCountRow++;
						}

						// STORE SPECIES AMOUNTS
						if(((puddle->getActualTime() > (puddle->getFileAmountSavingInterval() + AmountsStoredCounter)) ||
						   (puddle->getActualTime() == 0) ||  (puddle->getFileAmountSavingInterval() == 0)) &&
						   (puddle->getFileAmountSavingInterval() >= 0))
						{
							//saveLivingSpeciesIDSTD(tmp_ActGEN, tmp_ActSIM, tmp_ActSTEP, tmp_StoringPath);
							//saveLivingSpeciesAmountSTD(tmp_ActGEN, tmp_ActSIM, tmp_StoringPath);
							//saveLivingSpeciesConcentrationSTD(tmp_ActGEN, tmp_ActSIM, tmp_StoringPath);
							puddle->saveTimeSpeciesAmountSTD(actSTEP);
							if(puddle->getActualTime() > 0) {
								AmountsStoredCounter += puddle->getFileAmountSavingInterval();
								previousStepLastAmountSaving = actSTEP;
							}
							bufferSpeciesCountRow++;
						}

						//write times and reactions parameter to files
						if(bufferTimesCountRow == N_BUFFER) {
							//save data buffers to file
							puddle->saveTimeReactionBuffersToFile(actGEN, actSIM, argv[2]);
							previousStepLastBufferTimesSaving = actSTEP;
							bufferTimesCountRow = 0;
						}

						//write reactions parameter to files getBufferRctsCountRow
						if(puddle->getBufferRctsCountRow() == N_BUFFER) {
							//save data buffers to file
							puddle->saveReactionBuffersToFile(actGEN, actSIM, argv[2]);
							previousStepLastBufferRctSaving = actSTEP;
							puddle->setBufferRctsCountRow(0);
						}

						//write timeSpeciesAmount to files
						if(bufferSpeciesCountRow == N_BUFFER) {
							//save data buffers to file
							puddle->saveAmountBuffersToFile(actGEN, actSIM, argv[2]);
							previousStepLastBufferAmountSaving = actSTEP;
							bufferSpeciesCountRow = 0;
						}

						actSTEP++; // step update

					}else{ // if(( (((float)clock() - tStart) / CLOCKS_PER_SEC) < (puddle->getMAXhours()*60*60)) || (puddle->getMAXhours() == 0))
						// Increase number of attempts
						puddle->increaseAttempts();
						puddle->resetConcentrationToInitialConditions(rndDoubleGen);
						puddle->clearGilScores();
						// STOP WHILE
						actGEN = actGEN - 1;
						break;

					}
					// If necessary, check the volume condition
					if(puddle->getTheta() > 0)
					{
						//if(puddle->getInitVolume()*puddle->getTheta() < puddle->getVolume()){growing = false;}
						if(puddle->getInitLipids()*puddle->getTheta() < puddle->getLipids()){growing = false;}
					}
				} // while((puddle->getActualTime() <= puddle->getNseconds()) & (actSTEP <= puddle->getNreactions()) & growing)

				// Final species ages update
				puddle->updateSpeciesAges();

				// SAVE FINAL STRUCTURES TO FILE if actSTEP is different from the previous one
				if(previousStepLastStructuresSaving < actSTEP-1)
					saveToFile(argv[2], puddle, actGEN, actSIM, actSTEP);

				if(previousStepLastTimesSaving < actSTEP-1)
					puddle->saveTimesSTD(actSTEP);

				if(previousStepLastAmountSaving < actSTEP-1)
					puddle->saveTimeSpeciesAmountSTD(actSTEP);

				if(previousStepLastBufferTimesSaving < actSTEP-1)
					puddle->saveTimeReactionBuffersToFile(actGEN, actSIM, argv[2]);

				if((previousStepLastBufferRctSaving < actSTEP-1) && puddle->getsaveReactionParameters())
					puddle->saveReactionBuffersToFile(actGEN, actSIM, argv[2]);

				if(previousStepLastBufferAmountSaving < actSTEP-1)
					puddle->saveAmountBuffersToFile(actGEN, actSIM, argv[2]);


				//CHECK STRUCTURES, THE COHERENCE OF THE INTERNAL STRUCTURES ARE CONTROLLED
				if(!puddle->structureCoherenceCheckUp())
				{
					cout << endl;
					ExitWithError("structureCoherenceCheckUp", "PROBLEM WITH STRCTURE COHERENCE... BE CARE TO THE SIMULATION OUTCOMES!!!");
				}
			}else{ // for if(puddle->getCurrentAttempts() <= puddle->getMAXattempts())
				// SIMULATION IS STOPPED
				ExitWithError("MAIN", "FATAL ERROR: The number of MAXIMUM attempts has been exceeded!!!");
				break;

			}
		} // end for(acs_int actGEN = 1; actGEN <= puddle->getNgen(); actGEN++)
		// RESET STRUCTURES and TIME TO THE INITIAL VALUES FOR THE NEXT SIMULATION
		puddle->clearAllStructures();
		puddle->clearGilScores();
	} // end for(acs_int actSIM = 1; actSIM <= puddle->getNsim(); actSIM++)

	//DELETE ALL MAIN HEAP OBJECTS
	delete puddle;
	return 0;
}
Exemple #15
0
void DownloadFileWithCompression(struct ORACLEALLINONE *oraAllInOne, char* pDirectory,
                                 int compressionLevel, char* pRemoteFile, char* pLocalFile,
                                 int isKeepPartial, int isResume)
{
	FILE *fp;
	sword ociResult;
	ub4 vCompressionLevel;
	ub8 vSkipBytes;
	char blobBuffer[ORA_BLOB_BUFFER_SIZE];
	oraub8 vSize;
	int zRet;
	z_stream zStrm;
	unsigned char zOut[ORA_BLOB_BUFFER_SIZE];
#ifndef _WIN32
	int showProgress;
	char progressLine[MAX_FMT_SIZE];
#endif
	int isStdUsed;
	off_t cnt;
	off_t sourceSize;
        struct stat fileStat;

	struct BINDVARIABLE oraBindsDownload[] =
	{
		{ 0, SQLT_STR,  ":directory",         pDirectory,         ORA_IDENTIFIER_SIZE + 1   },
		{ 0, SQLT_INT,  ":compression_level", &vCompressionLevel, sizeof(vCompressionLevel) },
		{ 0, SQLT_STR,  ":filename",          pRemoteFile,        MAX_FMT_SIZE              },
		{ 0, SQLT_BLOB, ":blob",              &oraAllInOne->blob, sizeof(oraAllInOne->blob) },
		{ 0, SQLT_INT,  ":skipbytes",         &vSkipBytes,        sizeof(vSkipBytes)        },
		{ 0 }
	};

	struct ORACLESTATEMENT oraStmtDownload = {
#include "downloadcompr.text"
,
		0, oraBindsDownload, NO_ORACLE_DEFINES };

	vCompressionLevel = compressionLevel;
	isStdUsed = !strcmp(pLocalFile, "-");
	if (isStdUsed)
	{
		isResume = 0;
		isKeepPartial = 1;
	}

	SetSessionAction(oraAllInOne, "GZIP_AND_DOWNLOAD: GZIP");
	if (OCIDescriptorAlloc(oraAllInOne->envhp, (void**)&oraAllInOne->blob, OCI_DTYPE_LOB, 0, 0))
	{
		ExitWithError(oraAllInOne, RET_OCIINIT, ERROR_NONE, "Failed to allocate BLOB\n");
	}

	cnt = 0;
	vSkipBytes = 0;
	if (isResume)
	{
		if (!stat(pLocalFile, &fileStat))
			vSkipBytes = cnt = fileStat.st_size;
		if (!cnt)
			isResume = 0;
	}

#ifndef _WIN32
	showProgress = 1;
	if (!isatty(STDOUT_FILENO) || isStdUsed)
		showProgress = 0;

	if (showProgress)
		start_longops_meter(oraAllInOne, 0, 1);
#endif

	PrepareStmtAndBind(oraAllInOne, &oraStmtDownload);
	ociResult = ExecuteStmt(oraAllInOne);
#ifndef _WIN32
	if (showProgress)
		stop_longops_meter();
#endif

	if (ociResult)
		ExitWithError(oraAllInOne, RET_ORA, ERROR_OCI, "Failed to compress file in oracle directory\n");

#ifndef _WIN32
	if (showProgress)
	{
		if (OCILobGetLength2(oraAllInOne->svchp[0], oraAllInOne->errhp, oraAllInOne->blob, (oraub8*)&sourceSize))
			ExitWithError(oraAllInOne, RET_ORA, ERROR_OCI, "Error getting BLOB length\n");
		strcpy(progressLine, "TRANSFER & GUNZIP: ");
		strncat(progressLine, basename(pLocalFile), MAX_FMT_SIZE - 1 - strlen(progressLine));
		start_progress_meter(progressLine, sourceSize, &cnt);
	}
#endif

	SetSessionAction(oraAllInOne, "GZIP_AND_DOWNLOAD: DOWNLOAD");
	if (!isStdUsed && (fp = fopen(pLocalFile, isResume ? "ab" : "wb")) == NULL)
	{
		ExitWithError(oraAllInOne, RET_FS, ERROR_OS, "Error opening a local file for writing\n");
	}
	if (isStdUsed)
		fp = stdout;

	zStrm.zalloc = Z_NULL;
	zStrm.zfree = Z_NULL;
	zStrm.opaque = Z_NULL;
	zStrm.avail_in = 0;
	zStrm.next_in = Z_NULL;
	zRet = inflateInit2(&zStrm, 16+MAX_WBITS);
	if (zRet != Z_OK)
	{
		if (!isStdUsed)
			fclose(fp);
		ExitWithError(oraAllInOne, RET_ZLIB, ERROR_NONE, "ZLIB initialization failed\n");
	}

	vSize = 0;
	ociResult = OCILobRead2(oraAllInOne->svchp[0], oraAllInOne->errhp, oraAllInOne->blob, &vSize, 0, 1, blobBuffer, ORA_BLOB_BUFFER_SIZE, OCI_FIRST_PIECE, 0, 0, 0, 0);
	while (ociResult == OCI_NEED_DATA || ociResult == OCI_SUCCESS)
	{
		cnt += vSize;
		zStrm.avail_in = vSize;
		zStrm.next_in = blobBuffer;
		do
		{
			zStrm.avail_out = ORA_BLOB_BUFFER_SIZE;
			zStrm.next_out = zOut;
			zRet = inflate(&zStrm, Z_NO_FLUSH);
			switch (zRet)
			{
            case Z_STREAM_ERROR:
			case Z_NEED_DICT:
			case Z_DATA_ERROR:
			case Z_MEM_ERROR:
				(void)inflateEnd(&zStrm);
				if (!isStdUsed)
					fclose(fp);
				ExitWithError(oraAllInOne, RET_ZLIB, ERROR_NONE, "ZLIB inflate failed: %d, size %d\n", zRet, vSize);
			}

			fwrite(zOut, sizeof(unsigned char), ORA_BLOB_BUFFER_SIZE - zStrm.avail_out, fp);
			if (ferror(fp))
			{
				(void)inflateEnd(&zStrm);
				if (!isStdUsed)
					fclose(fp);
				ExitWithError(oraAllInOne, RET_DONOTEXIT, ERROR_OS, "Error writing to a local file\n");
				if (!isKeepPartial)
				{
					if (unlink(pLocalFile))
						ExitWithError(oraAllInOne, RET_FS, ERROR_OS, "Could not remove partial file %s\n", pLocalFile);
				}
				ExitWithError(oraAllInOne, RET_FS, ERROR_NONE, 0);
			}
		}
		while (zStrm.avail_out == 0);

		if (ociResult == OCI_SUCCESS)
			break;
		ociResult = OCILobRead2(oraAllInOne->svchp[0], oraAllInOne->errhp, oraAllInOne->blob, &vSize, 0, 1, blobBuffer, ORA_BLOB_BUFFER_SIZE, OCI_NEXT_PIECE, 0, 0, 0, 0);
	}

#ifndef _WIN32
	if (showProgress)
		stop_progress_meter();
#endif
	inflateEnd(&zStrm);
	if (!isStdUsed)
		fclose(fp);

	if (ociResult != OCI_SUCCESS)
	{
		ExitWithError(oraAllInOne, RET_ORA, ERROR_OCI, "Error reading BLOB\n");
	}

	ReleaseStmt(oraAllInOne);
	SetSessionAction(oraAllInOne, 0);

	OCILobFreeTemporary(oraAllInOne->svchp[0], oraAllInOne->errhp, oraAllInOne->blob);

	if (OCIDescriptorFree(oraAllInOne->blob, OCI_DTYPE_LOB))
	{
		ExitWithError(oraAllInOne, RET_OCIINIT, ERROR_NONE, "Failed to free BLOB\n");
	}
	oraAllInOne->blob = 0;
}

void UploadFileWithCompression(struct ORACLEALLINONE *oraAllInOne, char* pDirectory,
                               int compressionLevel, char* pRemoteFile, char* pLocalFile,
                               int isKeepPartial, int isResume)
{
	FILE *fp;
	sword ociResult;
	char blobBuffer[ORA_BLOB_BUFFER_SIZE];
	oraub8 vSize;
	ub8 vSkippedBytes;
	char vOpenMode[3];
	ub1 piece;
	int zRet, zFlush;
	z_stream zStrm;
	unsigned char zIn[ORA_BLOB_BUFFER_SIZE];
#ifndef _WIN32
	int showProgress;
	char progressLine[MAX_FMT_SIZE];
#endif
	int isStdUsed;
	off_t cnt;
	off_t sourceSize;
	struct stat fileStat;
	int isError;
	struct ORACLEFILEATTR oracleFileAttr;

	struct BINDVARIABLE oraBindsUpload[] =
	{
		{ 0, SQLT_STR,  ":directory", pDirectory,         ORA_IDENTIFIER_SIZE + 1   },
		{ 0, SQLT_STR,  ":filename",  pRemoteFile,        MAX_FMT_SIZE              },
		{ 0, SQLT_STR,  ":openmode",  vOpenMode,          sizeof(vOpenMode)         },
		{ 0, SQLT_INT,  ":file_size", &sourceSize,        sizeof(sourceSize)        },
		{ 0, SQLT_INT,  ":skipped",   &vSkippedBytes,     sizeof(vSkippedBytes)     },
		{ 0, SQLT_BLOB, ":blob",      &oraAllInOne->blob, sizeof(oraAllInOne->blob) },
		{ 0 }
	};

	struct ORACLESTATEMENT oraStmtUpload = {
#include "uploadcompr.text"
,
		0, oraBindsUpload, NO_ORACLE_DEFINES };

	isStdUsed = !strcmp(pLocalFile, "-");
	if (isStdUsed)
		isResume = 0;

	SetSessionAction(oraAllInOne, "UPLOAD_AND_GUNZIP: UPLOAD");
	if (OCIDescriptorAlloc(oraAllInOne->envhp, (void**)&oraAllInOne->blob, OCI_DTYPE_LOB, 0, 0))
	{
		ExitWithError(oraAllInOne, RET_OCIINIT, ERROR_NONE, "Failed to allocate BLOB\n");
	}

	if (OCILobCreateTemporary(oraAllInOne->svchp[0], oraAllInOne->errhp, oraAllInOne->blob, OCI_DEFAULT, 0, OCI_TEMP_BLOB, TRUE/*cache*/, OCI_DURATION_SESSION))
	{
		ExitWithError(oraAllInOne, RET_ORA, ERROR_OCI, "Failed to create temporary BLOB\n");
	}

	piece = OCI_FIRST_PIECE;

#ifndef _WIN32
	showProgress = 1;
	if (!isatty(STDOUT_FILENO) || isStdUsed)
		showProgress = 0;
#endif

	cnt = vSkippedBytes = 0;
	if (isResume)
	{
		GetOracleFileAttr(oraAllInOne, pDirectory, pRemoteFile, &oracleFileAttr);
		if (oracleFileAttr.bExists)
			cnt = vSkippedBytes = oracleFileAttr.length;
		if (!cnt)
			isResume = 0;
	}

#ifndef _WIN32
	if (showProgress)
	{
		stat(pLocalFile, &fileStat);
		sourceSize = fileStat.st_size;
		strcpy(progressLine, "GZIP & TRANSFER: ");
		strncat(progressLine, basename(pLocalFile), MAX_FMT_SIZE - 1 - strlen(progressLine));
		start_progress_meter(progressLine, sourceSize, &cnt);
	}
#endif

	if (!isStdUsed && (fp = fopen(pLocalFile, "rb")) == NULL)
	{
		ExitWithError(oraAllInOne, RET_FS, ERROR_OS, "Error opening a local file for reading\n");
	}
	if (isStdUsed)
		fp = stdin;

	if (cnt > 0)
	{
		if (fseek(fp, cnt, SEEK_SET))
		{
			fclose(fp);
			ExitWithError(oraAllInOne, RET_FS, ERROR_OS, "Error setting reading position in a local file\n");
		}
	}

	zStrm.zalloc = Z_NULL;
	zStrm.zfree = Z_NULL;
	zStrm.opaque = Z_NULL;

	zRet = deflateInit2(&zStrm, compressionLevel ? compressionLevel : Z_DEFAULT_COMPRESSION, Z_DEFLATED, 16+MAX_WBITS, 8, Z_DEFAULT_STRATEGY);
	if (zRet != Z_OK)
	{
		if (!isStdUsed)
			fclose(fp);
		ExitWithError(oraAllInOne, RET_ZLIB, ERROR_NONE, "ZLIB initialization failed\n");
	}

	while (!feof(fp))
	{
		zStrm.avail_in = fread(zIn, sizeof(unsigned char), sizeof(zIn), fp);
		cnt += zStrm.avail_in;
		if (ferror(fp))
		{
			(void)deflateEnd(&zStrm);
			if (!isStdUsed)
				fclose(fp);
			ExitWithError(oraAllInOne, RET_FS, ERROR_OS, "Error reading from a local file\n");
		}

		zFlush = feof(fp) ? Z_FINISH : Z_NO_FLUSH;
		zStrm.next_in = zIn;

		do
		{
			zStrm.avail_out = ORA_BLOB_BUFFER_SIZE;
			zStrm.next_out = blobBuffer;
			zRet = deflate(&zStrm, zFlush);
			if (zRet != Z_OK && zRet != Z_STREAM_END && zRet != Z_BUF_ERROR)
			{
				(void)deflateEnd(&zStrm);
				if (!isStdUsed)
					fclose(fp);
				ExitWithError(oraAllInOne, RET_ZLIB, ERROR_NONE, "ZLIB deflate failed: %d, size %d\n", zRet, zStrm.avail_in);
			}

			if (zRet == Z_STREAM_END)
				piece = (piece == OCI_FIRST_PIECE) ? OCI_ONE_PIECE : OCI_LAST_PIECE;

			vSize = (piece == OCI_ONE_PIECE) ? ORA_BLOB_BUFFER_SIZE - zStrm.avail_out : 0;
			if (zStrm.avail_out == ORA_BLOB_BUFFER_SIZE)
				continue;
			ociResult = OCILobWrite2(oraAllInOne->svchp[0], oraAllInOne->errhp, oraAllInOne->blob, &vSize, 0, 1, blobBuffer, ORA_BLOB_BUFFER_SIZE - zStrm.avail_out, piece, 0, 0, 0, 0);
			if (ociResult != OCI_NEED_DATA && ociResult)
			{
				(void)deflateEnd(&zStrm);
				if (!isStdUsed)
					fclose(fp);
				ExitWithError(oraAllInOne, RET_ORA, ERROR_OCI, "Error writing to BLOB\n");
			}
			if (piece == OCI_FIRST_PIECE)
				piece = OCI_NEXT_PIECE;
		}
		while (zStrm.avail_out == 0);
	}

#ifndef _WIN32
	if (showProgress)
		stop_progress_meter();
#endif
	deflateEnd(&zStrm);
	if (!isStdUsed)
		fclose(fp);

	isError = 0;
        strcpy(vOpenMode, isResume ? "ab" : "wb");
	SetSessionAction(oraAllInOne, "UPLOAD_AND_GUNZIP: GUNZIP");

#ifndef _WIN32
	if (showProgress)
		start_longops_meter(oraAllInOne, 0, 1);
#endif

	PrepareStmtAndBind(oraAllInOne, &oraStmtUpload);
	ociResult = ExecuteStmt(oraAllInOne);
#ifndef _WIN32
	if (showProgress)
		stop_longops_meter();
#endif
	if (ociResult)
	{
		ExitWithError(oraAllInOne, RET_DONOTEXIT, ERROR_OCI, "Failed to decompress file in oracle directory\n");
		isError = 1;
	}
	else
		ReleaseStmt(oraAllInOne);
	SetSessionAction(oraAllInOne, 0);

	OCILobFreeTemporary(oraAllInOne->svchp[0], oraAllInOne->errhp, oraAllInOne->blob);

	if (OCIDescriptorFree(oraAllInOne->blob, OCI_DTYPE_LOB))
	{
		if (!isError)
			ExitWithError(oraAllInOne, RET_DONOTEXIT, ERROR_NONE, "Failed to free BLOB\n");
		isError = 1;
	}
	oraAllInOne->blob = 0;

	if (isError)
	{
		if (!isKeepPartial)
			Rm(oraAllInOne, pDirectory, pRemoteFile);
		ExitWithError(oraAllInOne, RET_ORA, ERROR_NONE, 0);
	}
}
Exemple #16
0
int main(int argc, char *argv[]) {
  TSocket srvSock, cliSock;        /* server and client sockets */
  struct TArgs *args;              /* argument structure for thread */
  pthread_t threads[NTHREADS];
  int tid = 0;
  fd_set set;  /* file description set */
  int ret, i;
  char str[BUFSIZE];

  if (argc == 1) { ExitWithError("Usage: server <local port>"); }

  /* Create a passive-mode listener endpoint */  
  srvSock = CreateServer(atoi(argv[1]));

  printf("Server read!\n");
  /* Run forever */
  for (;;) { 
    /* Initialize the file descriptor set */
    FD_ZERO(&set);
    /* Include stdin into the file descriptor set */
    FD_SET(STDIN_FILENO, &set);
    /* Include srvSock into the file descriptor set */
    FD_SET(srvSock, &set);

    /* Select returns 1 if input available, -1 if error */
    ret = select (FD_SETSIZE, &set, NULL, NULL, NULL);
    if (ret<0) {
       WriteError("select() failed"); 
       break;
    }

    /* Read from stdin */
    if (FD_ISSET(STDIN_FILENO, &set)) {
      scanf("%99[^\n]%*c", str);
      if (strncmp(str, "FIM", 3) == 0) {
        close(srvSock);
        break;
      }
    }

    /* Read from srvSock */
    if (FD_ISSET(srvSock, &set)) {
      if (tid == NTHREADS) { 
        WriteError("number of threads is over"); 
        break; 
      }
      
      /* Spawn off separate thread for each client */
      cliSock = AcceptConnection(srvSock);

      /* Create separate memory for client argument */
      if ((args = (struct TArgs *) malloc(sizeof(struct TArgs))) == NULL) { 
        WriteError("malloc() failed"); 
        break;
      }
      args->cliSock = cliSock;

      /* Create a new thread to handle the client requests */
      if (pthread_create(&threads[tid++], NULL, HandleRequest, (void *) args)) { 
        WriteError("pthread_create() failed"); 
      }
    }
  }
  
  printf("Server will wait for the active threads and terminate!\n");
  /* Wait for all threads to terminate */
  for(i=0; i<tid; i++) {
    pthread_join(threads[i], NULL);
  }
  return 0;
}
Exemple #17
0
int ProcessMailcapEntry( FILE *fp, struct MailcapEntry *mc, AcceptMedia media )
{
  size_t rawentryalloc = 2000;
  size_t len;
  size_t need;
  char *rawentry, *s, *t;
  char *LineBuf = 0;
  rawentry = malloc( ( rawentryalloc ) * sizeof( char ) );
  if ( rawentry == 0 )
  {
    ExitWithError( gettext( "Memory exhausted!  Program aborted!" ) );
  }
  rawentry[0] = 0;
  while ( LYSafeGets( &LineBuf, fp ) == 0 )
  {
    LYTrimNewline( LineBuf );
    if ( LineBuf[0] != '#' && LineBuf[0] )
    {
      len = strlen( LineBuf );
      need = len + strlen( rawentry ) + 1;
      if ( rawentryalloc < need )
      {
        rawentryalloc = rawentryalloc + need + 2000;
        rawentry = realloc( rawentry, ( rawentryalloc ) * sizeof( char ) );
        if ( rawentry == 0 )
        {
          ExitWithError( gettext( "Memory exhausted!  Program aborted!" ) );
        }
      }
      if ( len && LineBuf[ len + -1 ] == '\\' )
      {
        LineBuf[ len + -1 ] = 0;
        strcat( rawentry, LineBuf );
      }
      else
      {
        strcat( rawentry, LineBuf );
        break;
      }
    }
  }
  if ( LineBuf )
  {
    free( LineBuf );
    LineBuf = 0;
  }
  t = s = LYSkipBlanks( rawentry );
  if ( s[0] == 0 )
  {
    if ( rawentry )
    {
      free( rawentry );
      rawentry = 0;
    }
    return 0;
  }
  else
  {
    s = strchr( rawentry, ';' );
    if ( s == 0 )
    {
      if ( WWW_TraceFlag && ( WWW_TraceMask & 8 ) )
      {
        fprintf( TraceFP( ), "ProcessMailcapEntry: Ignoring invalid mailcap entry: %s\n", rawentry );
      }
      if ( rawentry )
      {
        free( rawentry );
        rawentry = 0;
      }
      return 0;
    }
    else
    {
      s[0] = 0;
      s++;
      if ( strncasecomp( t, "text/html", 9 ) == 0 || strncasecomp( t, "text/plain", 10 ) == 0 )
      {
        s = &s[ -1 ];
        s[0] = ';';
        if ( WWW_TraceFlag && ( WWW_TraceMask & 8 ) )
        {
          fprintf( TraceFP( ), "ProcessMailcapEntry: Ignoring mailcap entry: %s\n", rawentry );
        }
        if ( rawentry )
        {
          free( rawentry );
          rawentry = 0;
        }
        return 0;
      }
      else
      {
        LYRemoveBlanks( rawentry );
        LYLowerCase( rawentry );
        *(int*)&mc->needsterminal = 0;
        *(int*)&mc->copiousoutput = 0;
        *(int*)&mc->needtofree = 1;
        *(int*)&mc->testcommand = 0;
        *(int*)&mc->label = 0;
        *(int*)&mc->printcommand = 0;
        *(int*)&mc->contenttype[0] = 0;
        HTSACopy( &mc->contenttype, rawentry );
        *(int*)&mc->quality = 0x3f800000;
        *(int*)&mc->maxbytes = 0;
        t = GetCommand( s, &mc->command );
        if ( t )
        {
          s = LYSkipBlanks( t );
          for ( ; s;  )
          {
            char *arg, *eq, *mallocd_string;
            t = GetCommand( s, &mallocd_string );
            arg = mallocd_string;
            eq = strchr( arg, '=' );
            if ( eq )
            {
              eq[0] = 0;
              eq++;
              eq = LYSkipBlanks( eq );
            }
            if ( arg && arg[0] )
            {
              arg = Cleanse( arg );
              if ( strcmp( arg, "needsterminal" ) == 0 )
                *(int*)&mc->needsterminal = 1;
              else
              {
                if ( strcmp( arg, "copiousoutput" ) == 0 )
                  *(int*)&mc->copiousoutput = 1;
                else
                if ( eq && strcmp( arg, "test" ) == 0 )
                {
                  *(int*)&mc->testcommand = 0;
                  HTSACopy( &mc->testcommand, eq );
                  TrimCommand( &mc->testcommand );
                  if ( WWW_TraceFlag && ( WWW_TraceMask & 8 ) )
                  {
                    fprintf( TraceFP( ), "ProcessMailcapEntry: Found testcommand:%s\n", &mc->testcommand );
                  }
                }
                else
                if ( eq && strcmp( arg, "description" ) == 0 )
                  mc->label = eq;
                else
                if ( eq && strcmp( arg, "label" ) == 0 )
                  mc->label = eq;
                else
                if ( eq && strcmp( arg, "print" ) == 0 )
                  mc->printcommand = eq;
                else
                if ( eq == 0 || strcmp( arg, "textualnewlines" ) )
                {
                  if ( eq && strcmp( arg, "q" ) == 0 )
                  {
                    mc->quality = atof( eq );
                    if ( mc->quality > 0 && mc->quality < 0.001000000000 )
                      *(int*)&mc->quality = 0x3a83126f;
                  }
                  else
                  if ( eq && strcmp( arg, "mxb" ) == 0 )
                  {
                    mc->maxbytes = atol( eq );
                    if ( mc->maxbytes < 0 )
                      *(int*)&mc->maxbytes = 0;
                  }
                  else
                  {
                    if ( strcmp( arg, "notes" ) && arg[0] && WWW_TraceFlag && ( WWW_TraceMask & 8 ) )
                    {
                      fprintf( TraceFP( ), "ProcessMailcapEntry: Ignoring mailcap flag '%s'.\n", arg );
                    }
                  }
                }
              }
            }
            if ( mallocd_string )
            {
              free( mallocd_string );
              mallocd_string = 0;
            }
            s = t;
          }
        }
        if ( rawentry )
        {
          free( rawentry );
          rawentry = 0;
        }
        if ( PassesTest( mc ) )
        {
          if ( WWW_TraceFlag && ( WWW_TraceMask & 8 ) )
          {
            fprintf( TraceFP( ), "ProcessMailcapEntry Setting up conversion %s : %s\n", &mc->contenttype[0], &mc->command );
          }
          HTSetPresentation( &mc->contenttype[0], &mc->command, &mc->testcommand, mc->quality, 3.000000000000, 0.000000000000, mc->maxbytes, media );
        }
        if ( mc->command )
        {
          free( &mc->command );
          *(int*)&mc->command = 0;
        }
        if ( mc->testcommand )
        {
          free( &mc->testcommand );
          *(int*)&mc->testcommand = 0;
        }
        if ( mc->contenttype[0] )
        {
          free( &mc->contenttype[0] );
          *(int*)&mc->contenttype[0] = 0;
        }
        return 1;
      }
    }
  }
}
Exemple #18
0
void
usage(char *name)
{
    fprintf(stderr, "Usage: %s content-type file\n", name);
    ExitWithError(NULL);
}
Exemple #19
0
void Compress(struct ORACLEALLINONE *oraAllInOne, char* pDirectory, int compressionLevel, int isKeep,
              char* pOriginalFileName, char* pCompressedFileName)
{
	ub4 vCompressionLevel;
	sword ociResult;
#ifndef _WIN32
	int showProgress;
#endif

	struct BINDVARIABLE oraBindsCompress[] =
	{
		{ 0, SQLT_STR, ":directory",           pDirectory,          ORA_IDENTIFIER_SIZE + 1   },
		{ 0, SQLT_INT, ":compression_level",   &vCompressionLevel,  sizeof(vCompressionLevel) },
		{ 0, SQLT_INT, ":keep",                &isKeep,             sizeof(isKeep)            },
		{ 0, SQLT_STR, ":original_filename"  , pOriginalFileName,   MAX_FMT_SIZE              },
		{ 0, SQLT_STR, ":compressed_filename", pCompressedFileName, MAX_FMT_SIZE              },
		{ 0 }
	};

	struct ORACLESTATEMENT oraStmtCompress = {
#include "compress.text"
,
		0, oraBindsCompress, NO_ORACLE_DEFINES };

	vCompressionLevel = compressionLevel;

	SetSessionAction(oraAllInOne, "GZIP");

#ifndef _WIN32
	showProgress = 1;
	if (!isatty(STDOUT_FILENO))
		showProgress = 0;

	if (showProgress)
		start_longops_meter(oraAllInOne, 0, 1);
#endif
	PrepareStmtAndBind(oraAllInOne, &oraStmtCompress);
	ociResult = ExecuteStmt(oraAllInOne);
#ifndef _WIN32
	if (showProgress)
		stop_longops_meter();
#endif

	if (ociResult)
		ExitWithError(oraAllInOne, RET_ORA, ERROR_OCI, "Failed to compress file in oracle directory\n");

	ReleaseStmt(oraAllInOne);
	SetSessionAction(oraAllInOne, 0);
}

void Uncompress(struct ORACLEALLINONE *oraAllInOne, char* pDirectory, int isKeep,
                char* pOriginalFileName, char* pUncompressedFileName)
{
	sword ociResult;
#ifndef _WIN32
	int showProgress;
#endif

	struct BINDVARIABLE oraBindsUncompress[] =
	{
		{ 0, SQLT_STR, ":directory",             pDirectory,            ORA_IDENTIFIER_SIZE + 1 },
		{ 0, SQLT_INT, ":keep",                  &isKeep,               sizeof(isKeep)          },
		{ 0, SQLT_STR, ":original_filename"  ,   pOriginalFileName,     MAX_FMT_SIZE            },
		{ 0, SQLT_STR, ":uncompressed_filename", pUncompressedFileName, MAX_FMT_SIZE            },
		{ 0 }
	};

	struct ORACLESTATEMENT oraStmtUncompress = {
#include "uncompress.text"
,
		0, oraBindsUncompress, NO_ORACLE_DEFINES };

	SetSessionAction(oraAllInOne, "GUNZIP");

#ifndef _WIN32
	showProgress = 1;
	if (!isatty(STDOUT_FILENO))
		showProgress = 0;

	if (showProgress)
		start_longops_meter(oraAllInOne, 0, 1);
#endif
	PrepareStmtAndBind(oraAllInOne, &oraStmtUncompress);
	ociResult = ExecuteStmt(oraAllInOne);
#ifndef _WIN32
	if (showProgress)
		stop_longops_meter();
#endif

	if (ociResult)
		ExitWithError(oraAllInOne, RET_ORA, ERROR_OCI, "Failed to uncompress file in oracle directory\n");

	ReleaseStmt(oraAllInOne);	
	SetSessionAction(oraAllInOne, 0);
}

void SubmitCompressJob(struct ORACLEALLINONE *oraAllInOne, char* pDirectory, int compressionLevel, int isKeep,
                       char* pOriginalFileName, char* pCompressedFileName)
{
	ub4 vCompressionLevel;
	char vJobName[ORA_IDENTIFIER_SIZE + 1];

	struct BINDVARIABLE oraBindsCompress[] =
	{
		{ 0, SQLT_STR, ":job_name",            vJobName,            ORA_IDENTIFIER_SIZE + 1   },
		{ 0, SQLT_STR, ":directory",           pDirectory,          ORA_IDENTIFIER_SIZE + 1   },
		{ 0, SQLT_INT, ":compression_level",   &vCompressionLevel,  sizeof(vCompressionLevel) },
		{ 0, SQLT_INT, ":keep",                &isKeep,             sizeof(isKeep)            },
		{ 0, SQLT_STR, ":original_filename",   pOriginalFileName,   MAX_FMT_SIZE              },
		{ 0, SQLT_STR, ":compressed_filename", pCompressedFileName, MAX_FMT_SIZE              },
		{ 0 }
	};

	struct ORACLESTATEMENT oraStmtCompress = {
#include "compress_bg.text"
,
	       0, oraBindsCompress, NO_ORACLE_DEFINES };

	vCompressionLevel = compressionLevel;

	PrepareStmtAndBind(oraAllInOne, &oraStmtCompress);

	if (ExecuteStmt(oraAllInOne))
		ExitWithError(oraAllInOne, RET_ORA, ERROR_OCI, "Failed to submit a compression job\n");

	printf("Submitted a job %s\n", vJobName);
	ReleaseStmt(oraAllInOne);
}

void SubmitUncompressJob(struct ORACLEALLINONE *oraAllInOne, char* pDirectory, int isKeep,
                         char* pOriginalFileName, char* pUncompressedFileName)
{
	char vJobName[ORA_IDENTIFIER_SIZE + 1];

	struct BINDVARIABLE oraBindsUncompress[] =
	{
		{ 0, SQLT_STR, ":job_name",              vJobName,              ORA_IDENTIFIER_SIZE + 1 },
		{ 0, SQLT_STR, ":directory",             pDirectory,            ORA_IDENTIFIER_SIZE + 1 },
		{ 0, SQLT_INT, ":keep",                  &isKeep,               sizeof(isKeep)          },
		{ 0, SQLT_STR, ":original_filename"  ,   pOriginalFileName,     MAX_FMT_SIZE            },
		{ 0, SQLT_STR, ":uncompressed_filename", pUncompressedFileName, MAX_FMT_SIZE            },
		{ 0 }
	};

	struct ORACLESTATEMENT oraStmtUncompress = {
#include "uncompress_bg.text"
,
	       0, oraBindsUncompress, NO_ORACLE_DEFINES };

	PrepareStmtAndBind(oraAllInOne, &oraStmtUncompress);

	if (ExecuteStmt(oraAllInOne))
		ExitWithError(oraAllInOne, RET_ORA, ERROR_OCI, "Failed to submit a decompression job\n");

	printf("Submitted a job %s\n", vJobName);
	ReleaseStmt(oraAllInOne);
}
Exemple #20
0
int
GetMailcapEntry(FILE *fp)
/* Parse a mailcap entry
 *   On entry-
 *     fp=mailcap file being read
 *   If a valid mailcap entry is found then on exit-
 *     GetMailcapEntry=1
 *     mc holds the decoded entry
 *   Else on exit-
 *     GetMailcapEntry=0
 *     The content of mc is undefined
 ***/
{ int rawentryalloc = 2000, len;
  char *rawentry, *s, *t, *LineBuf;

  LineBuf = malloc(LINE_BUF_SIZE);
  if (!LineBuf) ExitWithError(nomem);
  rawentry = malloc(1 + rawentryalloc);
  if (!rawentry) ExitWithError(nomem);
  *rawentry = 0;
  while (fgets(LineBuf, LINE_BUF_SIZE, fp)) {
    if (LineBuf[0] == '#') continue;
    len = strlen(LineBuf);
    if (len == 0) continue;
    if (LineBuf[len-1] == '\n') LineBuf[--len] = 0;
    if ((len + strlen(rawentry)) > rawentryalloc) {
      rawentryalloc += 2000;
      rawentry = realloc(rawentry, rawentryalloc+1);
      if (!rawentry) ExitWithError(nomem);
    }
    if (LineBuf[len-1] == '\\') {
      LineBuf[len-1] = 0;
      strcat(rawentry, LineBuf);
    } else {
      strcat(rawentry, LineBuf);
      break;
    }
  }
  free(LineBuf);
  for (s=rawentry; *s && isspace((unsigned char) *s); ++s) ;
  if (!*s) { /* totally blank entry -- quietly ignore */
    free(rawentry);
    return(0);
  }
  s = index(rawentry, ';');
  if (!s) { /* ignore invalid entries unless debugging */
    if (DoDebug)
      fprintf(stderr, "Invalid mailcap entry: %s\n", rawentry);
    free(rawentry);
    return(0);
  }
  *s++ = 0;	/* Terminate the content type and point to the remainder */

  mc.needsterminal = 0;
  mc.copiousoutput = 0;
  mc.testcommand = NULL;
  mc.label = NULL;
  mc.printcommand = NULL;

  StripTrailingSpace(rawentry);
  mc.contenttype = malloc(1+strlen(rawentry));
  if (!mc.contenttype) ExitWithError(nomem);
  strcpy(mc.contenttype, rawentry);

  t = GetCommand(s, &mc.command);
  if (!t) { /* There are no parameters */
    free(rawentry);
    return(1);
  }
  s = t;
  while (s) {
    char *arg, *eq;

    t = GetCommand(s, &arg);
    eq = index(arg, '=');
    if (eq) *eq++ = 0;
    if (*arg) {
      arg = Cleanse(arg);
      if (!strcmp(arg, "needsterminal")) {
	mc.needsterminal = 1;
      } else if (!strcmp(arg, "copiousoutput")) {
	mc.copiousoutput = 1;
      } else if (eq && !strcmp(arg, "test")) {
	mc.testcommand = eq;
      } else if (eq && !strcmp(arg, "description")) {
	mc.label = eq;
      } else if (eq && !strcmp(arg, "label")) { 
	mc.label = eq; /* bogus old name for description */
      } else if (eq && !strcmp(arg, "print")) {
	mc.printcommand = eq;
      } else if (eq && !strcmp(arg, "textualnewlines")) {
	/* ExceptionalNewline(mc.contenttype, atoi(eq)); */
      } else if (strcmp(arg, "notes")) { /* IGNORE notes field */
      } else if (*arg && DoDebug) {
        fprintf(stderr, "ignoring mailcap flag: %s\n", arg);
      }
    }
    s = t;
  }
  free(rawentry);
  return(1);
}