Ejemplo n.º 1
0
	void Profiler::writeData() const
	{
		outStream.open(fileName, std::ios::trunc);

		// Write category headers
		for (uint i = 0; i < numUsedCategories; i++)
		{
			outStream << categories[i].name;
			outStream << getDelimiter(i);
		}

		uint endIndex;
		uint startIndex;

		if (wrapped())
		{
			endIndex = frameIndex % MAX_FRAME_SAMPLES;
			startIndex = (endIndex + 1) % MAX_FRAME_SAMPLES;
			while (startIndex != endIndex)
			{
				writeFrame(startIndex);
				startIndex = (startIndex + 1) % MAX_FRAME_SAMPLES;
			}
			if (currentFrameComplete())
				writeFrame(startIndex);
		}
		else
		{
			uint numActualFrames = frameIndex;
			if (currentFrameComplete())
				numActualFrames++;
			startIndex = 0;
			endIndex = numActualFrames;
			while (startIndex < endIndex)
				writeFrame(startIndex++);
		}
		outStream.close();
	}
Ejemplo n.º 2
0
bool FileSystem::rawopen
	(
	std::ofstream& out,			// Output stream to open.
	const string &fname,			// May be converted to upper-case.
	bool is_text				// Should the file be opened in text mode
	)
{
	string name = fname;
	if (!rewrite_virtual_path(name)) {
		con.Print_err(MM_MAJOR_WARN, "Illegal file access\n");
		return false;
	}

#if defined(MACOS) || (__GNUG__ > 2)
	std::ios_base::openmode mode = std::ios::out | std::ios::trunc;
	if (!is_text) mode |= std::ios::binary;
#elif defined(UNIX)
	int mode = std::ios::out | std::ios::trunc;
#else
	int mode = std::ios::out | std::ios::trunc;
	if (!is_text) mode |= std::ios::binary;
#endif
	switch_slashes(name);

	// We first "clear" the stream object. This is done to prevent
	// problems when re-using stream objects
	out.clear();

	int uppercasecount = 0;
	do {
		out.open(name.c_str(), mode);		// Try to open
		if (out.good()) return true;		// found it!
		out.clear();						// Forget ye not
	} while (base_to_uppercase(name, ++uppercasecount));

	// file not found.
	return false;
}
Ejemplo n.º 3
0
      void OpenFile()
      {
         //std::cout << "LogManager try to open file to " << sLogFileName << std::endl;
         if (logFile.is_open())
         {
            logFile << "Change to log file: "<< sLogFileName<< std::endl;
            TimeTag();
            EndFile();
            logFile.close();
         }

         //First attempt to create the log file.
         std::ostringstream filename;
         filename << "results/logs/" << theApp->getStartTimeString() << "-eventLog";
         if (mSide == RED) {
         	filename << "Red";
         } else if (mSide == BLUE) {
         	filename << "Blue";
         }
         filename << ".txt";
         logFile.open(filename.str().c_str());
         //logFile.open(sLogFileName);
         if (!logFile.is_open())
         {
            std::cout << "could not open file \""<<filename.str()<<"\"" << std::endl;
            return;
         }
         else
         {
            //std::cout << "Using file \"delta3d_log.html\" for logging" << std::endl;
         }

         //TimeTag();

		 //logFile << std::endl;
         logFile.flush();
         //std::cout.flush();
      }
Ejemplo n.º 4
0
int main(int argc, char *argv[])
{
    // Initialize pin & symbol manager
    PIN_InitSymbols();
    if( PIN_Init(argc,argv) )
    {
        return Usage();
    }
    
    // Write to a file since cout and cerr maybe closed by the application
    TraceFile.open(KnobOutputFile.Value().c_str());
    TraceFile << hex;
    TraceFile.setf(ios::showbase);
    
    // Register Image to be called to instrument functions.
    IMG_AddInstrumentFunction(Image, 0);
    PIN_AddFiniFunction(Fini, 0);

    // Never returns
    PIN_StartProgram();
    
    return 0;
}
/* =====================================================================
 * Entry point for the tool
 * ===================================================================== */
int main(int argc, char * argv[])
{
    if (PIN_Init(argc, argv))
    {
        return Usage();
    }
    PIN_InitSymbols();

    PIN_SemaphoreInit(&SemAllThreadStarted);
    PIN_MutexInit(&MtxVecThreadIds);
    PIN_MutexInit(&MtxActiveThread);

    Out.open(KnobOutputFile.Value().c_str());
    ASSERT(Out, "Failed to open file " + KnobOutputFile.Value());

    IMG_AddInstrumentFunction(Image, 0);

    PIN_AddFiniFunction(OnExit, 0);

    // Never returns
    PIN_StartProgram();
    return 0;
}
Ejemplo n.º 6
0
int main(int argc, char *argv[])
{

    if (PIN_Init(argc, argv))
        return usage();


    outfile.open("arqsimucache.out");

    INS_AddInstrumentFunction(instrument_instruction, 0);
    PIN_AddFiniFunction(finalize, 0);

    RAM *ram = new RAM();
    Cache *l2 = new Cache("L2", ram, 1000*1024, 2, 16);
    Cache *l1 = new Cache("L1", l2, 64*1024, 2, 16);

    front_memory = l1;

    // start program and never return
    PIN_StartProgram();

    return 0;
}
	void open_store(std::string outfile) {
		owl_file.open(outfile.c_str(), std::ios::out);
		// Write Prefix
		if (owl_file.is_open()) {
			for (std::map<std::string, std::string>::iterator it =
					prefixes.begin(), ie = prefixes.end(); it != ie; ++it) {
				owl_file << "Prefix(" << it->first << "=" << ANGLEQUOTE(it->second)
						<< ")\n";

			}
			owl_file << "\n";
			// Write Ontology
			owl_file << "Ontology(" << ANGLEQUOTE(ontologyName) << "\n";
			// Write Import
			if (!importOWLs.empty()) {
				for (std::vector<std::string>::iterator it = importOWLs.begin(),
						ie = importOWLs.end(); it != ie; ++it) {
					owl_file << "Import(" << ANGLEQUOTE(*it) << ")\n";
				}
			}
			owl_file << "\n";
		}
	}
Ejemplo n.º 8
0
int main ()
{
  //int posFlag = 0,velFlag = 0; // indicator to keep track of analysis function calls
  while (std::getline(positionfile, line)) // Reading line by line
  {
      std::istringstream iss(line); // http://www.cplusplus.com/reference/sstream/istringstream/istringstream/

      iss >> marker;
      if ( marker == '$') {
          //posFlag = 0;
         //cout << "Read a special character $" << endl;
         iss >> step >> filenum; // In position.txt file line beginning with $, ($ 1 1) = ($ step filenum)
         cout << step << "\t" << filenum << endl;
         filename = "postxtfiles/" + filenum + filetype; //postxtfiles is the directory in which i want to save it
         //postxtfiles dir should exist in the current directory in which the program is running
         cout << filename << endl;


         PosFile.open(filename.c_str(), std::ofstream::out);
         //PosFile << line << endl;
         //cout << line << endl;
        }
      else if (marker == '#') {
Ejemplo n.º 9
0
	wesnoth_global_fixture()
	{
		using namespace boost::unit_test;
		reporter.open("boost_test_result.xml");
		assert( reporter.is_open() );

		results_reporter::set_stream(reporter);
//		lg::set_log_domain_severity("all",lg::debug());
		game_config::path = filesystem::get_cwd();


		// Initialize unit tests
		SDL_Init(SDL_INIT_TIMER);
		test_utils::get_fake_display(1024, 768);

		gui2::init();
		static const gui2::event::manager gui_event_manager;



		// Set more report as default
#if BOOST_VERSION >= 106000
		if(runtime_config::get<log_level>(runtime_config::LOG_LEVEL) == invalid_log_level)
			unit_test_log.set_threshold_level(log_messages);
		if(runtime_config::get<report_level>(runtime_config::REPORT_LEVEL) == INV_REPORT_LEVEL)
			results_reporter::set_level(SHORT_REPORT);
		unit_test_monitor.register_exception_translator<game::error>(&exception_translator_game);
		unit_test_monitor.register_exception_translator<config::error>(&exception_translator_config);
#else
		if(runtime_config::log_level() == invalid_log_level)
			unit_test_log.set_threshold_level(log_messages);
		if(runtime_config::report_level() == INV_REPORT_LEVEL)
			results_reporter::set_level(SHORT_REPORT);
		unit_test_monitor.register_exception_translator<game::error>(&exception_translator_game);
		unit_test_monitor.register_exception_translator<config::error>(&exception_translator_config);
#endif
	}
Ejemplo n.º 10
0
// prints out the EMessageType , Class string , Method string , file path string , line string , current date string , and a message and apps to an file called Debuglog.txt
void Debug::Log(const EMessageType MsgType, const std::string& Class, const std::string& Method, const std::string& file, const int& line, const std::string& message) {
	//clock objs
	std::chrono::system_clock::time_point currenttime;
	// initialize time_point
	currenttime = std::chrono::system_clock::now();
	//convert the currenttime obj into a time_t obj
	static time_t debugTime = Debug::getCurrentTime(currenttime);
	// file stream obj
	static std::ofstream debugLog;
	// open the stream obj
	debugLog.open("debugLog.txt", std::ofstream::app | std::ofstream::out);
	//switch statement using what type of message i should be getting
	switch (MsgType) {
		// for info print out the Class , Method of class , file path , which line the log was called , current time and date and a message regarding what could or is possibly happening
	case EMessageType::INFO:
		debugLog << "INFO: " << Class << "::" << Method << "() - " << "\n File :: " << file << "\n Line :: " << line << "\n Date :: " << ctime(&debugTime) << " Message :: " << message << "\n\n";
		// break for next case
		break;
		// for warning print out the Class , Method of class , file path , which line the log was called , current time and date and a message regarding what could or is possibly happening
	case EMessageType::WARNING:
		debugLog << "WARNING: " << Class << "::" << Method << "() - " << "File :: " << file << ", Line :: " << line << ", Date :: " << ctime(&debugTime) << " Message :: " << message << "\n\n";
		// break for next statement
		break;
		// for Error print out the Class , Method of class , file path , which line the log was called , current time and date and a message regarding what could or is possibly happening
	case EMessageType::ERROR:
		debugLog << "ERROR: " << Class << "::" << Method << "() - " << "File :: " << file << ", Line :: " << line << ", Date :: " << ctime(&debugTime) << " Message :: " << message << "\n\n";
		// break for next statement
		break;
		// for FATAL_ERROR print out the Class , Method of class , file path , which line the log was called , current time and date and a message regarding what could or is possibly happening
	case EMessageType::FATAL_ERROR:
		debugLog << "FATAL ERROR: " << Class << "::" << Method << "() - " << "File :: " << file << ", Line :: " << line << ", Date :: " << ctime(&debugTime) << " Message :: " << message << "\n\n";
		//final break
		break;
	}
	//close the file
	debugLog.close();
}
Ejemplo n.º 11
0
int main()
{
    logfile.open("ai++.log", std::ios_base::out | std::ios_base::trunc);
    if (!logfile.is_open()) {
        std::cerr << "ai: cannot open log. terminating." << std::endl;
        return 1;
    }

    RawBoard board;
    uint8_t state;
    AI ai;
    while (true) {
        read_board(std::cin, board);
        read_state(std::cin, state);

        AnalyzeResult result = ai.actuate(board);
        if (std::get<1>(result)) {
            std::cout << (uint8_t)std::get<0>(result) << std::flush;
        } else {
            std::cerr << "ai: no further options. terminating." << std::endl;
            return 0;
        }
    }
}
Ejemplo n.º 12
0
int main(INT32 argc, CHAR **argv)
{
    PIN_InitSymbols();
    PIN_Init(argc, argv);

    outfile.open("i18n_tool.out");
    
    IMG img = IMG_Open(KnobUnicodeExeName.Value());
    if (IMG_Valid(img) == TRUE)
    {
    	string exeFullName = KnobUnicodeExeName.Value();
    	
        outfile << exeFullName.substr(exeFullName.rfind("/")+1) << endl;
        IMG_Close(img);     
    }  
     
    IMG_AddInstrumentFunction(ImageLoad, 0);
    PIN_AddFiniFunction(Fini, 0);

    // Never returns
    PIN_StartProgram();

    return 0;
}
Ejemplo n.º 13
0
int parse_args(int argc, char **argv)
{

    int option;
     while ((option = getopt(argc, argv,"l:")) != -1)
    {
      switch (option) {
              case 'l' : 
                   if(logger)
                    logger.close(); 

                   logger.open(optarg, std::ofstream::out | std::ofstream::app);
                   if (logger.fail()) {
                   cerr << "open failure as expected: " << strerror(errno) << '\n';
                   return -1;
                   }

              break;
              default : 
              usage(); 
              return -1; 
             }    
    }
}
Ejemplo n.º 14
0
void InitObjFile()
{
	if (g_obj.is_open())
	{
		return;
	}

	std::ofstream file;
	file.open("logger.obj");

	if (file.is_open())
	{
		file.close();
	}

	g_obj.open("logger.obj", std::ios::app);

	g_obj.setf(std::ios::fixed, std::ios::floatfield);

	g_objFrameIndex = 0;
	g_objObjectIndex = 0;
	g_objVertexBaseIndex = 1;
	g_objVertexIndex = 1;
}
Ejemplo n.º 15
0
int main(int argc, char *argv[])
{
	if(argc==2){
		double d = atof(argv[1]);
		if(d!=0) amp = d;
		else amp = 1000.0;
	}
#ifdef FILE_SAVE
	ptime now = second_clock::local_time();
	std::string logname = to_iso_string(now) + std::string(".csv");
	ofs.open(logname.c_str());
#endif /* FILE_SAVE */
	port.set_option(serial_port_base::baud_rate(57600));
	port.set_option(serial_port_base::character_size(8));
	port.set_option(serial_port_base::flow_control(serial_port_base::flow_control::none));
	port.set_option(serial_port_base::parity(serial_port_base::parity::none));
	port.set_option(serial_port_base::stop_bits(serial_port_base::stop_bits::one));

	boost::thread thr_io(boost::bind(&io_service::run, &io));
	port.async_read_some( buffer(rbuf), boost::bind(&read_callback, _1, _2 ));

	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA);
	glutInitWindowSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
	glutInitWindowPosition(0, 0);
	window = glutCreateWindow("Value window");
	glutDisplayFunc(&DrawGLScene);
	glutIdleFunc(&DrawGLScene);
	glutReshapeFunc(&ReSizeGLScene);
	glutKeyboardFunc(&NormalKeyPressed);
	glutSpecialFunc(&SpecialKeyPressed);
	InitGL(DEFAULT_WIDTH, DEFAULT_HEIGHT);
	glutMainLoop();
	
	return 0;
}
Ejemplo n.º 16
0
void CommSerial::OpenFileAndPrintHeader(std::ofstream& out, const Grid& grid, const char* information)
{
  char path_str[129];
  int count = OutputCount();

  sprintf(path_str, "%s%04d.dat", OutputPath().c_str(), count);

  out.open(path_str, std::ios::trunc);

  out << "# vtk DataFile Version 2.0" << std::endl
      << count << ": " << information << std::endl
      << "ASCII" << std::endl
      << "DATASET STRUCTURED_POINTS" << std::endl
      << grid.Local().Size().X() << " "
      << grid.Local().Size().Y() << " "
      << grid.Local().Size().Z() << std::endl
      << "ORIGIN 0 0 0" << std::endl
      << "SPACING " << grid.Extent().MeshWidth().X() << " "
      << grid.Extent().MeshWidth() << " "
      << grid.Extent().MeshWidth() << std::endl
      << "POINT_DATA " << grid.Local().Size().Product() << std::endl
      << "SCALARS residual double 1" << std::endl
      << "LOOKUP_TABLE default" << std::endl;
}
Ejemplo n.º 17
0
void PerfdataWriter::RotateFile(std::ofstream& output, const String& temp_path, const String& perfdata_path)
{
	ObjectLock olock(this);

	if (output.good()) {
		output.close();

		if (Utility::PathExists(temp_path)) {
			String finalFile = perfdata_path + "." + Convert::ToString((long)Utility::GetTime());
			if (rename(temp_path.CStr(), finalFile.CStr()) < 0) {
				BOOST_THROW_EXCEPTION(posix_error()
				    << boost::errinfo_api_function("rename")
				    << boost::errinfo_errno(errno)
				    << boost::errinfo_file_name(temp_path));
			}
		}
	}

	output.open(temp_path.CStr());

	if (!output.good())
		Log(LogWarning, "PerfdataWriter")
		    << "Could not open perfdata file '" << temp_path << "' for writing. Perfdata will be lost.";
}
Ejemplo n.º 18
0
//TODO: Handle cleanup when killed close servos and serial
int main(int argc, const char* argv[])
{
    try
    {
        if (argc != 3)
        {
            std::cerr << "Usage: <port> <base/lift>" << std::endl;
            return 1;
        }

        boost::asio::io_service io_service;
        int port = std::atoi(argv[1]);
        const char* component = argv[2];
        if(strcmp(component, "lift") == 0) {
            const char* s = "/dev/servoblaster";
            const char* d = "/dev/ttyAMA0";
            servos.open(s, std::ofstream::out | std::ofstream::trunc);
            lift_serial = serial_connection::create(io_service, d);
        } else {
            const char* d0 = "/dev/ttyAMA0";
            //const char* d1 = "/dev/ttyUSB0";
            base_serial = serial_connection::create(io_service, d0);
            //sens_serial = serial_connection::create(io_service, d1);
        }
        std::cout << "Serving on port " << port << std::endl;
        std::cout << "Controlling " << component << std::endl;
        server s(io_service, port);
        io_service.run();
    }
    catch (std::exception& e)
    {
        std::cerr << "Exception: " << e.what() << "\n";
    }

    return 0;
}
Ejemplo n.º 19
0
    //opens the specified file
    inline void open(const std::string &filename)
    {
        #ifdef DEBUG
            file.open(filename.c_str());
        #endif
	}
Ejemplo n.º 20
0
 CSV(const char *filename) {
     out.open(filename);
 }
Ejemplo n.º 21
0
//---------------------------------------------------------------------------------------
// ****************METODOS PARA TRABAJAR CON ARCHIVOS TEXTO DE SALIDA********************
//---------------------------------------------------------------------------------------
// Permite abrir un archivo de salida
bool VGeneral :: AbrirArchivoSalida (std::ofstream &archivo, char nomb_arch [128])
{
   archivo.open (nomb_arch, ios::out);
   return archivo.is_open();
}
Ejemplo n.º 22
0
int WINAPI
WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
	// Parse the command line.
	LPSTR cmd_line_including_exe_name = GetCommandLineA();

	const int MAX_ARGS = 100;
	int argc = 0;
	char* argv[MAX_ARGS];		/* Flawfinder: ignore */

#if _DEBUG
	logfile.open("updater.log", std::ios_base::out);
    DEBUG("Parsing command arguments");
#endif
	
	char *token = NULL;
	if( cmd_line_including_exe_name[0] == '\"' )
	{
		// Exe name is enclosed in quotes
		token = strtok( cmd_line_including_exe_name, "\"" );
		argv[argc++] = token;
		token = strtok( NULL, " \t," );
	}
	else
	{
		// Exe name is not enclosed in quotes
		token = strtok( cmd_line_including_exe_name, " \t," );
	}

	while( (token != NULL) && (argc < MAX_ARGS) )
	{
		argv[argc++] = token;
		/* Get next token: */
		if (*(token + strlen(token) + 1) == '\"')		/* Flawfinder: ignore */
		{
			token = strtok( NULL, "\"");
		}
		else
		{
			token = strtok( NULL, " \t," );
		}
	}

	gUpdateURL = NULL;

	/////////////////////////////////////////
	//
	// Process command line arguments
	//

    DEBUG("Processing command arguments");
	
	//
	// Parse the command line arguments
	//
	int parse_args_result = parse_args(argc, argv);
	
	WNDCLASSEX wndclassex = { 0 };
	//DEVMODE dev_mode = { 0 };

	const int WINDOW_WIDTH = 250;
	const int WINDOW_HEIGHT = 100;

	wsprintf(gProgress, L"Connecting...");

	/* Init the WNDCLASSEX */
	wndclassex.cbSize = sizeof(WNDCLASSEX);
	wndclassex.style = CS_HREDRAW | CS_VREDRAW;
	wndclassex.hInstance = hInstance;
	wndclassex.lpfnWndProc = WinProc;
	wndclassex.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
	wndclassex.lpszClassName = win_class_name;
	
	RegisterClassEx(&wndclassex);
	
	// Get the size of the screen
	//EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dev_mode);
	
	gWindow = CreateWindowEx(NULL, win_class_name, 
		L"Second Life Updater",
		WS_OVERLAPPEDWINDOW, 
		CW_USEDEFAULT, 
		CW_USEDEFAULT, 
		WINDOW_WIDTH, 
		WINDOW_HEIGHT,
		NULL, NULL, hInstance, NULL);

	ShowWindow(gWindow, nShowCmd);
	UpdateWindow(gWindow);

	if (parse_args_result)
	{
		MessageBox(gWindow, 
				L"Usage: updater -url <url> [-name <window_title>] [-program <program_name>] [-silent]",
				L"Usage", MB_OK);
		return parse_args_result;
	}

	// Did we get a userserver to work with?
	if (!gUpdateURL)
	{
		MessageBox(gWindow, L"Please specify the download url from the command line",
			L"Error", MB_OK);
		return 1;
	}

	// Can't feed GetTempPath into GetTempFile directly
	char temp_path[MAX_PATH];		/* Flawfinder: ignore */
	if (0 == GetTempPathA(sizeof(temp_path), temp_path))
	{
		MessageBox(gWindow, L"Problem with GetTempPath()",
			L"Error", MB_OK);
		return 1;
	}
    std::string update_exec_path(temp_path);
	update_exec_path.append("Second_Life_Updater.exe");

	WCHAR update_uri[4096];
    mbstowcs(update_uri, gUpdateURL, sizeof(update_uri));

	int success = 0;
	int cancelled = 0;

	// Actually do the download
    try
    {
        DEBUG("Calling get_url_into_file");
        success = get_url_into_file(update_uri, update_exec_path, &cancelled);
    }
    catch (const Fetcher::InetError& e)
    {
        (void)e;
        success = FALSE;
        DEBUG("Caught: " << e.what());
    }

	// WinInet can't tell us if we got a 404 or not.  Therefor, we check
	// for the size of the downloaded file, and assume that our installer
	// will always be greater than 1MB.
	if (gTotalBytesRead < (1024 * 1024) && ! cancelled)
	{
		MessageBox(gWindow,
			L"The Second Life auto-update has failed.\n"
			L"The problem may be caused by other software installed \n"
			L"on your computer, such as a firewall.\n"
			L"Please visit http://secondlife.com/download/ \n"
			L"to download the latest version of Second Life.\n",
			NULL, MB_OK);
		return 1;
	}

	if (cancelled)
	{
		// silently exit
		return 0;
	}

	if (!success)
	{
		MessageBox(gWindow, 
			L"Second Life download failed.\n"
			L"Please try again later.", 
			NULL, MB_OK);
		return 1;
	}

	// TODO: Make updates silent (with /S to NSIS)
	//char params[256];		/* Flawfinder: ignore */
	//sprintf(params, "/S");	/* Flawfinder: ignore */
	//MessageBox(gWindow, 
	//	L"Updating Second Life.\n\nSecond Life will automatically start once the update is complete.  This may take a minute...",
	//	L"Download Complete",
	//	MB_OK);
		
/*==========================================================================*|
    // DEV-31680: ShellExecuteA() causes McAfee-GW-Edition and AntiVir
    // scanners to flag this executable as a probable virus vector.
    // Less than or equal to 32 means failure
	if (32 >= (int) ShellExecuteA(gWindow, "open", update_exec_path.c_str(), NULL, 
		"C:\\", SW_SHOWDEFAULT))
|*==========================================================================*/
    // from http://msdn.microsoft.com/en-us/library/ms682512(VS.85).aspx
    STARTUPINFOA si;
    PROCESS_INFORMATION pi;
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));

    if (! CreateProcessA(update_exec_path.c_str(), // executable file
                  NULL,                            // command line
                  NULL,             // process cannot be inherited
                  NULL,             // thread cannot be inherited
                  FALSE,            // do not inherit existing handles
                  0,                // process creation flags
                  NULL,             // inherit parent's environment
                  NULL,             // inherit parent's current dir
                  &si,              // STARTUPINFO
                  &pi))             // PROCESS_INFORMATION
	{
		MessageBox(gWindow, L"Update failed.  Please try again later.", NULL, MB_OK);
		return 1;
	}

	// Give installer some time to open a window
	Sleep(1000);

	return 0;
}
Ejemplo n.º 23
0
int main(int argc,char *argv[])
{
	typedef PsimagLite::Concurrency ConcurrencyType;
	ConcurrencyType concurrency(&argc,&argv,1);
	InputCheck inputCheck;
	PsimagLite::String filename="";
	int opt = 0;
	OperatorOptions options;
	PsimagLite::String strUsage(argv[0]);
	if (utils::basename(strUsage) == "operator") options.enabled = true;
	strUsage += " -f filename [-k] [-p precision] [-V] [whatToMeasure]";
	int precision = 6;
	bool keepFiles = false;
	bool versionOnly = false;
	/* PSIDOC DmrgDriver
	  \begin{itemize}
	  \item[-f] {[}Mandatory, String{]} Input to use.
	  \item[-p] [Optional, Integer] Digits of precision for printing.
	  \item[whatToMeasure] {[}Optional, String{]} What to measure in-situ
	  \item[-l] {[}Optional, String{]} Without this option std::cout is redirected
	  to a file.
	  This option with the string ``?'' prints name of such log file.
	  This option with the string ``-'' writes std::cout to terminal.
	  In other cases, string is the name of the file to redirect std::cout to.
	 \item[-k] [Optional] Keep untar files
	  \end{itemize}
	 */
	/* PSIDOC OperatorDriver
	 The arguments to the \verb!operator! executable are as follows.
	\begin{itemize}
	 \item[-f] [Mandatory, String] Input to use. The Model= line is
	very important in input.inp.

	\item[-s] [Optional, Integer] Site for operator.
	Meaningful only for Models where
	the Hilbert space depends on the site (different kinds of atoms).
	Defaults to 0.

	\item[-l] [Mandatory, String] The label or name for this operator.
	This is model dependent. For example to obtain $c_{\uparrow}$ for
	the Hubbard model, say \begin{verbatim}
	./operator -l c -f input.inp\end{verbatim}
	See the function naturalOperator for each Model.

	\item[-d] [Optional, Integer] Degree of freedom (spin, orbital or
	combination of both) to use. This is model dependent. For example to
	obtain $c_\downarrow$ for the Hubbard model, say
	\begin{verbatim}./operator -l c -d 1 -f input.inp\end{verbatim}
	See the function naturalOperator for each Model. Defaults to 0.

	\item[-t] [Optional, Void] Transpose the operator. For example to
	obtain $c^\dagger_\uparrow$ for a Hubbard model, say
	\begin{verbatim}./operator -l c -t -f input.inp\end{verbatim}
	\end{itemize}
	 */
	while ((opt = getopt(argc, argv,"f:s:l:d:F:o:p:tkV")) != -1) {
		switch (opt) {
		case 'f':
			filename = optarg;
			break;
		case 'o':
			std::cerr<<argv[0]<<": Omit the \"-o\". It's not needed anymore.\n";
			std::cerr<<"\t Write the insitu measurements at the end of the command line\n";
			return 1;
		case 's':
			options.site = atoi(optarg);
			break;
		case 'l':
			options.label = optarg;
			break;
		case 'd':
			options.dof = atoi(optarg);
			break;
		case 't':
			options.transpose = true;
			break;
		case 'k':
			keepFiles = true;
			break;
		case 'F':
			std::cerr<<argv[0]<<": Omit the \"-F\". It's not needed anymore.\n";
			std::cerr<<"\t It is implied by the label: n=bosonic, c=fermionic, etc\n";
			return 2;
		case 'p':
			precision = atoi(optarg);
			std::cout.precision(precision);
			std::cerr.precision(precision);
			break;
		case 'V':
			versionOnly = true;
			options.label = "-";
			break;
		default:
			inputCheck.usageMain(strUsage);
			return 1;
		}
	}

	// sanity checks here
	if (filename=="" && !versionOnly) {
		inputCheck.usageMain(strUsage);
		return 1;
	}

	PsimagLite::String insitu = (optind < argc) ? argv[optind] : "";

	if (!options.enabled && options.label != "-") {
		bool queryOnly = (options.label == "?");
		if (options.label == "" || options.label == "?") {
			options.label = ArchiveFilesType::coutName(filename);
			if (queryOnly) {
				std::cout<<options.label<<"\n";
				return 0;
			}
		}

		GlobalCoutStream.open(options.label.c_str());
		if (!GlobalCoutStream || GlobalCoutStream.bad()
		        || !GlobalCoutStream.good()) {
			PsimagLite::String str(argv[0]);
			str += ": Could not redirect std::cout to " + options.label + "\n";
			throw PsimagLite::RuntimeError(str);
		}

		std::cerr<<argv[0]<<" ATTENTION: All standard output now sent to ";
		std::cerr<<options.label<<"\n";
		std::cerr.flush();
		GlobalCoutBuffer = std::cout.rdbuf(); //save old buf
		std::cout.rdbuf(GlobalCoutStream.rdbuf()); //redirect std::cout to file
		atexit(restoreCoutBuffer);
	}

	// print license
	if (ConcurrencyType::root() && !options.enabled) {
		std::cout<<ProgramGlobals::license;
		Provenance provenance;
		std::cout<<provenance;
	}

	if (versionOnly) return 0;

	InputNgType::Writeable ioWriteable(filename,inputCheck);
	InputNgType::Readable io(ioWriteable);

	ParametersDmrgSolverType dmrgSolverParams(io, false);

	ArchiveFilesType af(dmrgSolverParams,filename,options.enabled,options.label);

	if (insitu!="") dmrgSolverParams.insitu = insitu;
	if (dmrgSolverParams.options.find("minimizeDisk") != PsimagLite::String::npos)
		dmrgSolverParams.options += ",noSaveWft,noSaveStacks,noSaveData";

#ifndef USE_PTHREADS
	inputCheck.checkForThreads(dmrgSolverParams.nthreads);
#endif

	ConcurrencyType::npthreads = dmrgSolverParams.nthreads;

	registerSignals();

	PsimagLite::String targeting = inputCheck.getTargeting(dmrgSolverParams.options);

	bool isComplex = (dmrgSolverParams.options.find("useComplex") != PsimagLite::String::npos);
	if (targeting=="TimeStepTargetting") isComplex = true;
	if (isComplex) {
		mainLoop0<MySparseMatrixComplex, CvectorSizeType>(io,dmrgSolverParams,targeting,options);
	} else {
		mainLoop0<MySparseMatrixReal, CvectorSizeType>(io,dmrgSolverParams,targeting,options);
	}

	if (options.enabled) return 0;

	af.deletePackedFiles();
	if (!keepFiles)
		ArchiveFilesType::staticDelete();
}
Ejemplo n.º 24
0
void DebugFile::init(std::string filename)
{
 file.open(filename.c_str(), std::ios::out | std::ios::app );
 file << "\n\n-----------------------------------------\n";
 currentTime() << " : Starting log.";
}
Ejemplo n.º 25
0
/* 
 * Tool used for verifying that libdft propagates taint correctly.
 */
int main(int argc, char **argv) {
	/* initialize symbol processing */
	PIN_InitSymbols();

	if (unlikely(PIN_Init(argc, argv)))
		goto err;

	IMG_AddInstrumentFunction(ImageLoad, 0);
	PIN_AddFiniFunction(OnExit, 0);

#ifdef DTRACKER_DEBUG
	INS_AddInstrumentFunction(CheckMagicValue, 0);
#endif
	
	LOG("Initializing libdft.\n");
	if (unlikely(libdft_init() != 0))
		goto err;

	// reset counters
	bzero(stdcount, sizeof(stdcount));

	// Open raw prov file.
	// This file is to be post-processed to get the data in a proper format.
	rawProvStream.open(ProvRawKnob.Value().c_str());


	/*
	 * Install taint sources and sinks.
	 * syscall_set_{pre, post}() set the callbacks in the libdft
	 * syscall description struct.
	 * These callbacks are respectively invoked through
	 * sysenter_save() and sysexit_save() function of libdft.
	 * In turn, these libdft functions are hooked to run before/after
	 * every syscall using PIN_AddSyscall{Entry, Exit}Function().
	 */

	/* dtracker_openclose.cpp: open(2), creat(2), close(2) */
	(void)syscall_set_pre(&syscall_desc[__NR_open], pre_open_hook);
	(void)syscall_set_pre(&syscall_desc[__NR_creat], pre_open_hook);
	(void)syscall_set_post(&syscall_desc[__NR_open], post_open_hook);
	(void)syscall_set_post(&syscall_desc[__NR_creat], post_open_hook);
	(void)syscall_set_post(&syscall_desc[__NR_close], post_close_hook);

	/* dtracker_read.cpp: read(2), readv(2) */
	(void)syscall_set_post(&syscall_desc[__NR_read], post_read_hook);
	(void)syscall_set_post(&syscall_desc[__NR_readv], post_readv_hook);

	/* dtracker_write.cpp: write(2), writev(2) */
	(void)syscall_set_post(&syscall_desc[__NR_write], post_write_hook);
	(void)syscall_set_post(&syscall_desc[__NR_writev], post_writev_hook);

	/* dtracker_mmap.cpp: mmap2(2), munmap(2) */
	(void)syscall_set_post(&syscall_desc[__NR_mmap2], post_mmap2_hook);
	(void)syscall_set_post(&syscall_desc[__NR_munmap], post_munmap_hook);


	/* start the program and return something to make the compiler happy */
	LOG("Starting program.\n");
	PIN_StartProgram();	
	return EXIT_SUCCESS;

err:
	/* error handling */

	/* detach from the process */
	libdft_die();

	/* return */
	return EXIT_FAILURE;
}
Ejemplo n.º 26
0
int main(int argc, char** argv)
{
    GameLog::Initialize();
    lout.open("log.txt",ios::out);

    stateMainMenu = true;
    stateGameMenu = false;

    bool kbEscape = false;

    global_config.Load();

    Assets::SetMusicVolume(global_config.music_volume);
    Assets::SetSoundVolume(global_config.sound_volume);
    if(global_config.music == false)Assets::SetMusicVolume(0);
    if(global_config.sound == false)Assets::SetSoundVolume(0);

    Engine* engine;
    engine = new Engine(global_config.width,global_config.height,global_config.fullscreen);

    sf::Image ico_darkhold;
    ico_darkhold.loadFromFile("./icon.png");
    engine->GetRenderContext().setIcon(128,128,ico_darkhold.getPixelsPtr());

    engine->GetRenderContext().setMouseCursorVisible(false);
    engine->GetRenderContext().setFramerateLimit(60);

    Assets::LoadPack(global_config.pack_assets);
    Assets::LoadList(global_config.list_assets);

    font_game = new Sprite("font_game",96);

    bool gamestarted = false;

    Assets::svolume = global_config.sound_volume;
    Assets::mvolume = global_config.music_volume;
    Assets::music = global_config.music;
    Assets::sound = global_config.sound;

    cout <<"[SYSTEM] Game started." << endl;

    engine->ff_phase = 1;
    engine->ff_alpha = 1.0F;

    screen_list.push_back(new ScreenMainMenu());

    while(engine->IsRunning())
    {
        glClearColor(0.0F,0.0F,0.0F,1.0F);
        engine->Update();
        glDisable(GL_DEPTH_TEST);

        Assets::svolume = global_config.sound_volume;
        Assets::mvolume = global_config.music_volume;
        Assets::music = global_config.music;
        Assets::sound = global_config.sound;

        if(gamestarted == false)
        {
            // Draw the title screen

            if(engine->ff_phase != 0)engine->Fade();

            Sprite* font_display = new Sprite("font_display",97);

            engine->SetFont(font_game);
            Engine::Print(0,0,"DARKHOLD DEMO",1.0F,0.0F,0.0F);
            font_display->w = 7;
            engine->SetFont(font_game);
            Engine::Print(0,40,"THIS IS A WORKING AND FULLY PLAYABLE");
            Engine::Print(0,50,"'EPISODE' OF MY GAME.");
            Engine::Print(0,60,"IT CONTAINS FOUR LEVELS AND A BOSS");
            Engine::Print(0,70,"ARENA, SEVERAL RUNES, MULTIPLE ENEMIES AND");
            Engine::Print(0,80,"IN ALL LIKELIHOOD, A FAIR SHARE OF BUGS.");
            Engine::Print(0,90,"ENJOY THE GAME; I MAY KEEP WORKING ON");
            Engine::Print(0,100,"IT IF PEOPLE LIKE THE CONCEPT.");

            Engine::Print(0,120,"PRESS SPACE OR (X) TO CONTINUE...",0.3F,0.3F,0.9F);
            engine->Render();

            delete font_display;

            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space) || sf::Joystick::isButtonPressed(0,0))
            {
                gamestarted = true;
            }

            if(sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
            {
                engine->GetRenderContext().close();
            }

            continue;
        }

        if(screen_list.empty() != true)
        {
            screen_list.back()->update();
            if(screen_list.back()->isDone())
            {
                screen_list.pop_back();
            }
            continue;
        }

        // Check if Escape is pressed

        if(sf::Keyboard::isKeyPressed(sf::Keyboard::Escape) || sf::Joystick::isButtonPressed(0,7))
        {
            if(!kbEscape)
            {
                screen_list.push_back(new ScreenGameMenu());
            }

            kbEscape = true;
        }
        else kbEscape = false;

        engine->go3D();
        glEnable(GL_ALPHA_TEST);
        glAlphaFunc(GL_GREATER,0);
        glEnable(GL_LIGHTING);
        glEnable(GL_LIGHT0);

        // Render stuff in 3D here

        engine->go2D();
        glDisable(GL_LIGHTING);

        // Render 2D stuff here

        engine->Render();
    }

    delete engine;



    delete font_game;\
    Assets::Destroy();

    global_config.Write();

    lout.flush();
    lout.close();

    return 0;
}
Ejemplo n.º 27
0
int main() {
  double pi2 = pi * pi;

  double at,dt1,Idc0,Idcn,dIdc,Idc,w1,I1,f0,T1,tn,t0,h,t,b,q0,q10,f1,L,r,a1,a2,a3,a4,b1,b2,b3,b4,c1,c2,c3,c4,V,Vs,q1s,P,Psc,q1sc,dVs,dq1s,dPsc,dq1sc,Ijj,w0;
  double f,q,q1;
  int n;
  cout << "Idc0=";
  cin >> Idc0;
  cout << "Idcn=";
  cin >> Idcn;
  cout << "dI=";
  cin >> dIdc;
  cout << "w1=";
  cin >> w1;
  cout << "I1=";
  cin >> I1;
  cout << "f0=";
  cin >> f0;
  cout << "n=";
  cin >> n;
  cout << "w0=";
  cin >> w0;
  cout << "b=";
  cin >> b;
  cout << "r=";
  cin >> r;
  cout << "dt=";
  cin >> h;
  cout << "dt1=";
  cin >> dt1;
  cout << "at=";
  cin >> at;
  res.open("absorpsingleres.txt", std::ios_base::app);
  L=1/(b*w0*w0);
  Idc=Idc0;
  t0=0;
  T1=2*pi/w1;
  tn=at+n*T1;

  while(Idc<=Idcn) {
    cout << "Idc=" << Idc << ", l=" << l << "\n";
    t=t0;
    q=0;
    f=f0;
    q1=0;
    Vs=0;
    q1s=0;
    Psc=0;
    q1sc=0;
    while(t<=at) {
      f1=f;
      q10=q1;
      a1=phi1(q1);
      b1=phi2(Idc,I1,w1,t,f,q1);
      c1=phi3(L,w0,r,Idc,I1,w1,t,q,f,q1);

      a2=phi1(q1+dt1*c1/2);
      b2=phi2(Idc,I1,w1,t+dt1/2,f+dt1*b1/2,q1+dt1*c1/2);
      c2=phi3(L,w0,r,Idc,I1,w1,t+dt1/2,q+dt1*a1/2,f+dt1*b1/2,q1+dt1*c1/2);

      a3=phi1(q1+dt1*c2/2);
      b3=phi2(Idc,I1,w1,t+dt1/2,f+dt1*b2/2,q1+dt1*c2/2);
      c3=phi3(L,w0,r,Idc,I1,w1,t+dt1/2,q+dt1*a2/2,f+dt1*b2/2,q1+dt1*c2/2);
      a4=phi1(q1+dt1*c3);
      b4=phi2(Idc,I1,w1,t+dt1,f+dt1*b3,q1+dt1*c3);
      c4=phi3(L,w0,r,Idc,I1,w1,t+dt1,q+dt1*a3,f+dt1*b3,q1+dt1*c3);
      q=q+dt1*(a1+2*a2+2*a3+a4)/6;
      f=f+dt1*(b1+2*b2+2*b3+b4)/6;
      q1=q1+dt1*(c1+2*c2+2*c3+c4)/6;
      t=t+dt1;
      
      if (f > pi2) {
        f = f - pi2;
      }

      res << t << "     " << q << "     " << f << "     " << q1 << "\n";
    }
    /*
    while(t<=tn) {
      f1=f;
      q10=q1;
      a1=phi1(q1);
      b1=phi2(Idc,I1,w1,t,f,q1);
      c1=phi3(L,w0,r,Idc,I1,w1,t,q,f,q1);
      a2=phi1(q1+h*c1/2);
      b2=phi2(Idc,I1,w1,t+h/2,f+h*b1/2,q1+h*c1/2);
      c2=phi3(L,w0,r,Idc,I1,w1,t+h/2,q+h*a1/2,f+h*b1/2,q1+h*c1/2);
      a3=phi1(q1+h*c2/2);
      b3=phi2(Idc,I1,w1,t+h/2,f+h*b2/2,q1+h*c2/2);
      c3=phi3(L,w0,r,Idc,I1,w1,t+h/2,q+h*a2/2,f+h*b2/2,q1+h*c2/2);
      a4=phi1(q1+h*c3);
      b4=phi2(Idc,I1,w1,t+h,f+h*b3,q1+h*c3);
      c4=phi3(L,w0,r,Idc,I1,w1,t+h,q+h*a3,f+h*b3,q1+h*c3);
      q=q+h*(a1+2*a2+2*a3+a4)/6;
      f=f+h*(b1+2*b2+2*b3+b4)/6;
      q1=q1+h*(c1+2*c2+2*c3+c4)/6;
      t=t+h;
      dVs=(sin(f1)+sin(f))*h/2;
      Vs=Vs+dVs;
      dq1s=(q10+q1)*h/2;
      q1s=q1s+dq1s;
      dPsc=(sin(f1)*cos(w1*(t-h))+sin(f)*cos(w1*t))*h/2;
      Psc=Psc+dPsc;
      dq1sc=(q10*cos(w1*(t-h))+q1*cos(w1*t))*h/2;
      q1sc=q1sc+dq1sc;
    }
    V=Idc-Vs/(n*T1)-q1s/(n*T1);
    P=I1/2-Psc/(n*T1)-q1sc/(n*T1);
    Ijj=Idc-q1s/(n*T1);
    //res << Idc << "     " << Ijj << "     " << V << "     " << P << "\n";
    */
    Idc=Idc+dIdc;
  }
  res.close();
  return 0;
}
Ejemplo n.º 28
0
	error() : logger2("Error") {
		#ifdef CPP_LOG_ERR_FILE
		ofs.open(CPP_LOG_ERR_FILE, 
			std::ios_base::app | std::ios_base::out);
		#endif
	};
int main(int argc, char* argv[])
{
	std::vector<Mat<float> > mse;
	
	//Neural Networks settings :
	Topology topo;
	unsigned int nbrneurons = 25;
	unsigned int nbrlayer = 1;
	unsigned int nbrinput = width*height;
	unsigned int nbroutput = 10;
	
	//topo.push_back(nbrinput,NTNONE);	//input layer
	topo.push_back(nbrinput,NTSIGMOID);	//input layer
	
	//topo.push_back(nbrneurons, NTSIGMOID);
	topo.push_back(15, NTSIGMOID);
	
	//topo.push_back(nbroutput, NTSOFTMAX);	//linear output
	topo.push_back(nbroutput, NTSIGMOID);	//linear output
	
	NN<float> nn(topo);
	nn.learning = false;
	//------------------------------
	
	//DATASET SETTINGS :
	report.open(report_fn.c_str(), ios::out);
    image.open(training_image_fn.c_str(), ios::in | ios::binary); // Binary image file
    label.open(training_label_fn.c_str(), ios::in | ios::binary ); // Binary label file

	// Reading file headers
    char number;
    for (int i = 1; i <= 16; ++i) {
        image.read(&number, sizeof(char));
	}
    for (int i = 1; i <= 8; ++i) {
        label.read(&number, sizeof(char));
	}
	
	//------------------------------
	
	//checking rotation :
	Mat<float> im1(8,8, (char)1);
	Mat<float> im2( rotate(im1,PI/2.0f) );
	
	im1.afficher();
	im2.afficher();
	//--------------------------------
	
	//checking arctan !!!
	float y = -4.0f;
	float x = 4.0f;
	std::cout << arctan(y,x)*180.0f/(PI) << std::endl;
	//--------------------------------------------------
	
	//checking reading :
	char labelval = 0;
	float theta = PI/2;
	im1 = inputMNIST(labelval);
	im2 = rotate(im1,theta);
	im2.afficher();
		
	std::cout << "Rotation of : " << theta*180.0f/PI << std::endl;
	//---------------------------------------------------
	
	
	
	int iteration = 25000;
	int offx = 2;
	int offy = 2;
	int size = 28;
	int countSuccess = 0;
	
	while( iteration)
	{
		Mat<float> rotatedinput( inputMNIST(labelval) );
		//let us choose the rotation :
		float theta = ((float)(rand()%360))*PI/180.0f;
		
		//let us apply it :
		rotatedinput = extract( rotate(rotatedinput, theta), offx,offy, offx+(size-1), offy+(size-1) );
		
		Mat<float> input( reshapeV( rotatedinput ) );
		Mat<float> target( 0.0f, 10,1);
		target.set( 1.0f, labelval+1, 1);
		
		if(labelval < 9)
		{
			Mat<float> output( nn.feedForward( input) );
	
			int idmax = idmin( (-1.0f)*output).get(1,1);
	
			transpose( operatorL(target,output) ).afficher();
	
			std::cout << " LEARNING ITERATION : " << iteration << " ; IDMAX = " << idmax << std::endl;
	
	
			nn.backProp(target);
			//nn.backPropCrossEntropy(target);
			
			
			//counting :
			if(idmax == labelval+1)
			{
				countSuccess++;
			}
			
			//-------------------
			
			if( iteration % 1000 == 0)
			{
				std::cout << " TEST : " << countSuccess << " / " << 1000 << std::endl;
				mse.push_back(Mat<float>((float)countSuccess,1,1));
		
				writeInFile(std::string("./mse.txt"), mse);
		
				countSuccess = 0;
			}
			
			iteration--;
			
			
		}
		
		
		
	}
	
	std::cout << " VALIDATION TEST : in progress.." << std::endl;
	
	iteration = 1000;
	int success = 0;
	while( iteration)
	{
		Mat<float> rotatedinput( inputMNIST(labelval) );
		//let us choose the rotation :
		//float theta = rand()%360;
		float theta = ((float)(rand()%360))*PI/180.0f;
		
		//let us apply it :
		rotatedinput = extract( rotate(rotatedinput, theta), offx,offy, offx+(size-1), offy+(size-1) );
		
		Mat<float> input( reshapeV( rotatedinput ) );
		Mat<float> target( 0.0f, 10,1);
		target.set( 1.0f, labelval+1, 1);
		
		if(labelval < 5)
		{
			Mat<float> output( nn.feedForward( input));
			int idmax = idmin( (-1.0f)*output).get(1,1);
		
			transpose(output).afficher();
			std::cout << " ITERATION : " << iteration << " ; IDMAX = " << idmax << std::endl;
		
			if(idmax == labelval+1)
			{
				success++;
			}
			
			iteration--;
		}
		
	}
	
	std::cout << "VALIDATION TEST : " << success << " / 1000." << std::endl;
	
	report.close();
	label.close();
	image.close();
	
	nn.save(std::string("neuralnetworksDIGITROTATED"));
		
	return 0;
}
Ejemplo n.º 30
0
	warning() : logger2("Warning") {
		#ifdef CPP_LOG_WARN_FILE
		ofs.open(CPP_LOG_WARN_FILE, 
			std::ios_base::app | std::ios_base::out);
		#endif
	};