Exemplo n.º 1
0
 void getFileModeCallback(const std_msgs::String::ConstPtr& msg)
 {
     std::string temp = msg->data;
     
     if( "write" == temp )
     {
         if( !tactileDataFile.is_open() && !jointsDataFile.is_open() )
         {
             std::cout << "\n\n ===== Creating files: " << tactileFileName << " and " << jointsFileName;
             tactileDataFile.open(tactileFileName.c_str());
             jointsDataFile.open(jointsFileName.c_str());
             writeStatus = true;
         }
     }
     else
     {
         if( tactileDataFile.is_open() && jointsDataFile.is_open() )
         {
             std::cout << "\n\n ===== Closing files: " << tactileFileName << " and " << jointsFileName;
             tactileDataFile.close();
             jointsDataFile.close();
             writeStatus = false;
         }                    
     }
     
     std::cout << "\n\n ===== mode: " << msg->data;
 }
Exemplo n.º 2
0
/* Flushes all ostreams used for debug messages.  You need to call
   this before forking.  */
void flush_debug()
{
    if (logfile_null.is_open())
        logfile_null.flush();
    if (logfile_file.is_open())
        logfile_file.flush();
}
Exemplo n.º 3
0
/*
Open the output file, initialize the output stream, and return the file's
length. If reload is true, first truncate any preexisting file
*/
unsigned long Download::openfile(char *url, bool reload, ofstream &fout, char *name)
{
    char fname[MAX_FILENAME_SIZE];

    if(!getfname(url, fname))
        throw DLExc("File name error");

    for(int i = 0; i < 5 && (!fout.is_open() || !fout); ++i)
    {
         if(!reload)
            fout.open(fname, ios::binary | ios::out | ios::app | ios::ate);
        else
            fout.open(fname, ios::binary | ios::out | ios::trunc);

         if(!fout.is_open() || !fout)
         {
            char buff[MAX_FILENAME_SIZE];
            strcpy(buff, fname);
            sprintf(fname, "%s-%u", buff, time(0)-i);
            fout.clear();
         }
    }

    if(!fout)
        throw DLExc("Could not open TEMP file!");

    strcpy(name, fname);

    // get current file length
    return fout.tellp();
}
Exemplo n.º 4
0
 virtual
 void
 close()
 {
   if(paramFile_.is_open()) paramFile_.close();
   if(occFile_.is_open()) occFile_.close();
 }
Exemplo n.º 5
0
BOOL OpenLogFiles()
{
	// Open import log file
	if ( FileSize("./log/import.log") > MAXLOGSIZE )
		// Truncate before writing
		logfile.open("./log/import.log", ios::out);
	else
		// Append to existing
		logfile.open("./log/import.log", ios::app);
	if ( !logfile.is_open() )
	{
		cerr << "Could not open 'import.log'" << endl;
		return FALSE;
	}

	// Open import error file
	if ( FileSize("./log/import.err") > MAXERRSIZE )
		// Truncate before writing
		errfile.open("./log/import.err", ios::out);
	else
		// Append to existing
		errfile.open("./log/import.err", ios::app);
	if ( !errfile.is_open() )
	{
		cerr << "Could not open 'import.err'" << endl;
		return FALSE;
	}
	return TRUE;
}
// Open the various files for output
bool DataScaling::openFiles(ifstream& kaggleFile, ofstream& nodeFile, ofstream& edgeFile, ofstream& adFile)
{
	kaggleFile.open(this->kaggleFile);
	if (!kaggleFile.is_open())
	{
		cout << "Failed to open input kaggle file:" << this->kaggleFile << endl;
		return(false);
	}

	nodeFile.open(this->nodeFile);
	if (!nodeFile.is_open())
	{
		cout << "Failed to open output node file:" << this->nodeFile << endl;
		return(false);
	}

	edgeFile.open(this->edgeFile);
	if (!edgeFile.is_open())
	{
		cout << "Failed to open output edge file:" << this->edgeFile << endl;
		return(false);
	}

	adFile.open(this->adFile);
	if (!adFile.is_open())
	{
		cout << "Failed to open output ad file:" << this->adFile << endl;
		return(false);
	}

	return(true);
}
Exemplo n.º 7
0
	void incomingData(Stream *stream)
	{
		Message *message = Message::receive(stream);
		UserMessage *userMessage = dynamic_cast<UserMessage *>(message);
		if (userMessage)
		{
			if (userMessage->type == eventId)
			{
				double elapsedTime = (double)startingTime.msecsTo(QTime::currentTime()) / 1000.;
				if (outputFile.is_open())
					outputFile << elapsedTime;
				timeStamps.push_back(elapsedTime);
				for (size_t i = 0; i < values.size(); i++)
				{
					if (i < userMessage->data.size())
					{
						if (outputFile.is_open())
							outputFile << " " << userMessage->data[i];
						values[i].push_back(userMessage->data[i]);
					}
					else
					{
						if (outputFile.is_open())
							outputFile << " " << 0;
						values[i].push_back(0);
					}
				}
				if (outputFile.is_open())
					outputFile << endl;
				replot();
			}
		}
		delete message;
	}
Exemplo n.º 8
0
/**
 * Output the energy/angular momentum.
 */
void output_converseved_quantities(double E1, double L1, ofstream& output_file_energy, ofstream& output_file_angular_momentum) {
  if (output_file_energy.is_open()) {
    output_file_energy << E1 << endl;
  }
  if (output_file_angular_momentum.is_open()) {
    output_file_angular_momentum << L1 << endl;
  }
}
 /**
  * Close the files in case they are open
  * @param scores_file the scores file
  * @param lattice_file the lattice file
  */
 inline void close_lattice_files(ofstream & scores_file, ofstream & lattice_file) const {
     if (scores_file.is_open()) {
         scores_file.close();
     }
     if (lattice_file.is_open()) {
         lattice_file.close();
     }
 }
Exemplo n.º 10
0
 ~Disassembler(){
     if (disassembly.is_open()){
         disassembly.close();
     }
     if (simulation.is_open()){
         simulation.close();
     }
 };
    public: void Load(physics::ModelPtr _model, sdf::ElementPtr _sdf){
      world = _model->GetWorld();
      model = _model;
      trunk = model->GetLink("trunk");

      #if(PRINT_DEBUG)
      cout << "Loading the velocity over time plugin" << endl;
      #endif
      connection = event::Events::ConnectWorldUpdateBegin(boost::bind(&VelocityOverTimePlugin::worldUpdate, this));

      // Get the name of the folder to store the result in
      const char* resultsFolder = std::getenv("RESULTS_FOLDER");
      if(resultsFolder == nullptr){
         cout << "Results folder not set. Using current directory." << endl;
         resultsFolder = "./";
      }

      {
        const string resultsXFileName = string(resultsFolder) + "/" + "velocities_x.csv";
        bool exists = boost::filesystem::exists(resultsXFileName);

        outputCSVX.open(resultsXFileName, ios::out | ios::app);
        assert(outputCSVX.is_open());
        if (!exists) {
          writeHeader(outputCSVX);
        }
      }

      {
        const string resultsYFileName = string(resultsFolder) + "/" + "velocities_y.csv";
        bool exists = boost::filesystem::exists(resultsYFileName);

        outputCSVY.open(resultsYFileName, ios::out | ios::app);
        assert(outputCSVY.is_open());

        if (!exists) {
          writeHeader(outputCSVY);
        }
      }


      {
        const string resultsZFileName = string(resultsFolder) + "/" + "velocities_z.csv";
        bool exists = boost::filesystem::exists(resultsZFileName);

        outputCSVZ.open(resultsZFileName, ios::out | ios::app);
        assert(outputCSVZ.is_open());

        if (!exists) {
           writeHeader(outputCSVZ);
        }
      }

       // Write out t0
       outputCSVX << "Velocity X (m/s), " << trunk->GetWorldCoGLinearVel().x << ", ";
       outputCSVY << "Velocity Y (m/s), " << trunk->GetWorldCoGLinearVel().y << ", ";
       outputCSVZ << "Velocity Z (m/s), " << trunk->GetWorldCoGLinearVel().z << ", ";
    }
Exemplo n.º 12
0
/**
 * Output the excentric/great half axis to a file.
 */
void output_orbital_parameters(double a1, double e1, ofstream& output_file_a, ofstream& output_file_e) {
  if (output_file_a.is_open()) {
    output_file_a << a1 << endl;
  }

  if (output_file_e.is_open()) {
    output_file_e << e1 << endl;
  }
}
Exemplo n.º 13
0
	void shared_print(string id, int value) {
		if (!f.is_open()) {   // lazy initialization   -- A
			std::unique_lock<mutex> locker(m_mutex);
	        if (!f.is_open()) {
				f.open("log.txt");   // This must be synchronized  -- B
	        }
		}
		f << "From " << id << ": " << value << endl;  // I don't care this is not synchronized
	}
Exemplo n.º 14
0
void close_debug()
{
    if (logfile_null.is_open())
        logfile_null.close();
    if (logfile_file.is_open())
        logfile_file.close();

    logfile_trace = logfile_info = logfile_warning = logfile_error = 0;
}
Exemplo n.º 15
0
void OpenOutputFile(){
	static string _FileNumber = "";
	if (!OutputFile.is_open() || _FileNumber != FileNumber){
		_FileNumber = FileNumber;
		if (OutputFile.is_open()){
			OutputFile.close();
		}
		string file = "output_" + FileNumber + ".txt";
		cout << "Opening output file...";
		OutputFile.open(file.c_str(), ios::ate | ios::app | ios::out);
		if (!OutputFile){
			TerminateError("Unable to open output file.");
		}
	}
}
Exemplo n.º 16
0
int main(int argc, char **argv)
{
    for(;;) {
        int c;
        int option_index = 0;

        static struct option long_options[] = {
            {"offset", 1, 0, 'o'},
            {"help", 0, 0, 'h'},
            {0, 0, 0, 0},
        };

        c = getopt_long(argc, argv, "ho:", long_options, &option_index);
        if(c == -1)
            break;

        switch(c) {
            case 'o':
                fileoffset = strtoul(optarg, NULL, 0);
                printf("offset %#zx\n", fileoffset);
                break;
            case 'h':
            default:
                usage(argc, argv);
                break;
        }
    }

    if (argc - optind < 2) {
        printf("not enough arguments\n");
        usage(argc, argv);
    }

    inputfile = argv[optind++];
    outputfile = argv[optind++];

    printf("input file %s\n", inputfile.c_str());
    printf("output file %s\n", outputfile.c_str());

    iHex hex;
    if (hex.Open(inputfile) < 0) {
        fprintf(stderr, "error opening input file\n");
        return 1;
    }

    out.open(outputfile.c_str(), ios::out|ios::trunc|ios::binary);
    if (!out.is_open()) {
        fprintf(stderr, "error opening output file\n");
        return 1;
    }

    hex.SetCallback(&ihexcallback);
    hex.Parse();

    hex.Close();

    out.close();

    return 0;
}
Exemplo n.º 17
0
bool SaveOBJ(ofstream& fout, const double* const& points, const int* const& triangles, const unsigned int& nPoints,
    const unsigned int& nTriangles, const Material& material, IVHACD::IUserLogger& logger, int convexPart, int vertexOffset)
{
    if (fout.is_open()) {

        fout.setf(std::ios::fixed, std::ios::floatfield);
        fout.setf(std::ios::showpoint);
        fout.precision(6);
        size_t nV = nPoints * 3;
        size_t nT = nTriangles * 3;

		fout << "o convex_" << convexPart << std::endl;

        if (nV > 0) {
            for (size_t v = 0; v < nV; v += 3) {
                fout << "v " << points[v + 0] << " " << points[v + 1] << " " << points[v + 2] << std::endl;
            }
        }
        if (nT > 0) {
            for (size_t f = 0; f < nT; f += 3) {
                     fout << "f " 
                     << triangles[f + 0]+vertexOffset << " "
                     << triangles[f + 1]+vertexOffset << " "
                     << triangles[f + 2]+vertexOffset << " " << std::endl;
            }
        }
        return true;
    }
    else {
        logger.Log("Can't open file\n");
        return false;
    }
}
Exemplo n.º 18
0
Arquivo: main.cpp Projeto: aunk/chives
long S_Rend::render(ifstream& in, ofstream& out) {

	long bn;
	long t;
	if (!(in.is_open()))
	{ return -1; }
	else {
	t = 300;
	size=0;

	for_each (std::istreambuf_iterator<char>(in), \
		std::istreambuf_iterator<char>(), \
		[&] (char x) {
		t=s_nop(t,0);
		cred.push_back(t);
		alpha = static_cast<long>(cred[size]);
		delta = static_cast<long>(x);
		lambda ^= delta ^ alpha;
		size++;
	});

    	printf("*");
	}
	if (out.is_open())
	{ out << lambda << endl;
		out << delta << endl;
			out << size << endl;
				out << cred[size-1] << endl; }

	else { return -1; }
	in.close();
	out.close();
	return 0;
}
Exemplo n.º 19
0
void WorkerThread::dumpPpm(ofstream& fout, const cv::Mat& frame) {
    if (fout.is_open()) {
        vector<uchar> buff;
        cv::imencode(".pgm", frame, buff);
        fout.write((char*)&buff.front(), buff.size());
    }
}
Exemplo n.º 20
0
void MQTTLogger::OnMessage(const struct mosquitto_message *message)
{
    string topic = message->topic;
    string payload = static_cast<const char*>(message->payload);
    std::time_t tt = std::time(NULL);
    char mbstr[100];

    std::strftime(mbstr, sizeof(mbstr), "%Y-%m-%d %H:%M:%S:", std::localtime(&tt));
    string time(mbstr);
    Output << time + "\t" << topic + "\t" +  payload << endl;
    if (Output.tellp() > Max){
        Output.close();
        int i;
        for (i = Number-1; i > 0; i--){
            if (access((Path_To_Log + "." + to_string(i)).c_str(), F_OK) != -1){// check if old log file exists
                if (rename((Path_To_Log + "." + to_string(i)).c_str(), (Path_To_Log + "." + to_string(i+1)).c_str()) != 0){
                    cerr << "can't create old log file \n";
                    exit(-1);
            }
        }
        }
        if (rename(Path_To_Log.c_str(), (Path_To_Log + ".1").c_str()) != 0){
            cerr << "can't create old log file \n";
            exit(-1);
        }
        Output.open(Path_To_Log);
        if (!Output.is_open()){
            cerr << "Cannot open log file for writting " << Path_To_Log << endl;
            exit (-1);
        }
        mosquittopp::unsubscribe(NULL, Mask.c_str());// unsubscribe and subscribe to save all retained messages after rotate
        Subscribe(NULL, Mask);
    }
}
    public: void Load(physics::ModelPtr _model, sdf::ElementPtr _sdf){
      world = _model->GetWorld();
      model = _model;

      #if(PRINT_DEBUG)
      cout << "Loading the angular momentum over time plugin" << endl;
      #endif
      connection = event::Events::ConnectWorldUpdateBegin(boost::bind(&AngularMomentumOverTimePlugin::worldUpdate, this));

      // Get the name of the folder to store the result in
      const char* resultsFolder = std::getenv("RESULTS_FOLDER");
      if(resultsFolder == nullptr){
         cout << "Results folder not set. Using current directory." << endl;
         resultsFolder = "./";
      }

      const string resultsFileName = string(resultsFolder) + "/" + "angular_momentum.csv";
      outputCSV.open(resultsFileName, ios::out);
      assert(outputCSV.is_open());
      writeHeader(outputCSV);

       math::Vector3 angularMomentum;
       for (unsigned int i = 0; i < boost::size(links); ++i) {
          const physics::LinkPtr link = model->GetLink(links[i]);
          angularMomentum += link->GetWorldInertiaMatrix() * link->GetWorldAngularVel();
       }

       // Write out t0
       outputCSV << world->GetSimTime().Double() << ", " << angularMomentum.x / 10.0
       << ", " << angularMomentum.y / 10.0 << ", " << angularMomentum.z / 10.0 << endl;
    }
int main(int argc, char * argv[])
{
	if ( argc < 3 )
	{
		cout << "Provide the following details of file that contains the image names." << endl;
		cout << "Expected command line arguments: <full path to directory> <filename>" << endl;
		return -1;
	}

	string folder_path = argv[1];
	string full_filename = folder_path + argv[2];
    ifstream infile;
    infile.open( full_filename.c_str() );
    if ( !infile.is_open() )
    {
    	cout << "Could not open file: " << full_filename << endl;
    	return -1;
    }

    // load flandmark model structure and initialize
 	model = flandmark_init("/home/teenarahul/RandD2/flandmark/flandmark/data/flandmark_model.dat");

 	if ( model == NULL )
 	{
 		cout << "Could not load flandmark model." << endl;
 		return -1;
 	}

	string full_output_filename = folder_path + string( "Metadata_Flandmark.txt" );
	outfile.open( full_output_filename.c_str(), ios::out );
    if ( !outfile.is_open() )
    {
    	cout << "Could not open file " << full_filename << " for writing." << endl;
    	return -1;
    }
	outfile << "** Format: <image file name> <left eye position: X> < left eye position: Y> <right eye position: X> < right eye position: Y> <expression label>";

	bool success = false;
    string image_name;
    string full_imagename;
    infile >> image_name; //Works even if the file is empty.

    while ( infile.peek() != EOF )
    {
    	success = false;
    	full_imagename = folder_path + image_name;
    	success = find_eye_positions_in_image( full_imagename, false, false );
        if ( !success )
        {
        	cout << "Eye positions not detected in image: " << image_name << "." << endl;
        }
        else
        {
    	    save_metadata( image_name );
        }
    	infile >> image_name;
    }
    infile.close();
    outfile.close();
}
Exemplo n.º 23
0
void tbl_open(int tbl, ofstream& f) {
  char prompt[256];
  char fullpath[256];
  struct stat fstats;
  int retcode;

  if (*tdefs[tbl].name == PATH_SEP)
    strcpy(fullpath, tdefs[tbl].name);
  else
    sprintf(fullpath, "%s%c%s", env_config(PATH_TAG, PATH_DFLT), PATH_SEP,
            tdefs[tbl].name);

  retcode = stat(fullpath, &fstats);
  if (retcode && (errno != ENOENT)) {
    fprintf(stderr, "stat(%s) failed.\n", fullpath);
    exit(-1);
  }
  if (S_ISREG(fstats.st_mode) && !force) {
    sprintf(prompt, "Do you want to overwrite %s ?", fullpath);
    if (!yes_no(prompt))
      exit(0);
  }

  f.open(fullpath);
  if (!f.is_open()) {
    fprintf(stderr, "Open failed for %s at %s:%d\n",
            fullpath, __FILE__, __LINE__);
    exit(1);
  }
}
Exemplo n.º 24
0
static bool switch_log(ofstream &flog)
{
    GenerateTime("pacs_log\\%Y\\%m\\%d\\%H%M%S_service_n.txt", buff, sizeof(buff));
    if(flog.tellp() > 10 * 1024 * 1024 || strncmp(buff, current_log_path.c_str(), 20)) // 20 == strlen("pacs_log\\YYYY\\MM\\DD\\")
    {
	    if(PrepareFileDir(buff))
        {
            if(flog.is_open())
            {
                time_header_out(flog) << "to be continued" << endl;
                flog.close();
            }
            flog.open(buff);
            if(flog.fail())
            {
                cerr << "watch_notify() switch log " << buff << " failed" << endl;
                return false;
            }
            time_header_out(flog) << "continuation of " << current_log_path << endl;
            current_log_path = buff;
        }
	    else
        {
            DWORD gle = GetLastError();
            cerr << "watch_notify() switch log failed, PrepareFileDir(" << buff << ") failed" << endl;
		    return false;
        }
    }
    return true;
}
Exemplo n.º 25
0
	void DisabledInit() { 
		//Config loading
		try {
			cameraLight->Set(Relay::kOff);
			if (!Config::LoadFromFile("config.txt")) {
				cout << "Something happened during the load." << endl;
			}
			Config::Dump();
			
			myDrive->DisablePID();
			myDrive->ResetPID();
			
			if(fout.is_open() && !freshStart && !ds->IsFMSAttached()){
				fout.close();
			myShooter->ResetShooterProcess();
			
			lc->holdState(false);
			}
		} catch (exception ex) {
			cout << "Disabled exception. Trying again." << endl;
			cout << "Exception: " << ex.what() << endl;
		}
		
		//ResetShooterMotors();
		/*
		SmartDashboard::PutNumber("Target Info S",1741);
		cout<<SmartDashboard::GetNumber("Target Info S");
		*/
	}
Exemplo n.º 26
0
/**
 * Open a log file for writing to.
 * @return SUCCESS or FAIL
 */
int OpenLogFile(string path)
{
    logFilePath = path;
    //-------------------------------------------------------------------------
    //  Open file with append mode.
    //-------------------------------------------------------------------------
    logFileStream.open(path.c_str(), ios::app);
    
    //-------------------------------------------------------------------------
    //  If the file successfully opened, then set the flag for the other
    //  functions to know that the file is open..
    //-------------------------------------------------------------------------
    if (logFileStream.is_open())
    {
        logOpen = TRUE;
    }
    //-------------------------------------------------------------------------
    //  .. Else return FAIL.
    //-------------------------------------------------------------------------
    else
    {
        return FAIL;
    }
    
    //-------------------------------------------------------------------------
    //  If flow reaches here, then everything is good.
    //-------------------------------------------------------------------------
    return SUCCESS;
}
Exemplo n.º 27
0
// This method outputs the object's variables in the file 'fout'.
void SearchControl::showInput(ofstream & fout)
{
  if (!fout.is_open())
    return;
  if ((initial_search == NULL) && (iterative_search == NULL) &&
      (speculative_search == NULL))
    fout << "\nNo search.\n----------\n";
  else
    {
      if (initial_search != NULL)
	{
	  fout << "\nInitial search type:\n--------------------\n";
	  initial_search->showInput(fout);
	}
      if (iterative_search != NULL)
	{
	  fout << "\nIterative search type:\n----------------------\n";
	  iterative_search->showInput(fout);
	}
      if (speculative_search != NULL)
	{
	  fout << "\nSpeculative search: Executed after a successful iteration.";
	  fout << "\n-------------\n";
	}
    }
}
Exemplo n.º 28
0
int main()
{
LOGFILE.open("lab2_part1.log",ios::trunc);
if (LOGFILE.is_open())
  LOGFILE << POS_IN_PROGRAM << "start of logging" << endl;
else 
  {
  cout << "Unable to open file for logging.";
  return 1;
  }
	
// now all your regular stuff can go here

char c_array[5];
int i_array[5];
string intMsg = "Populate the int array with values.";
string charMsg = "Populate the char array with values.";
string dmpIntMsg = "Dump the data in the int array";
string dmpCharMsg = "Dump the data in the char array";

PromptForInt(intMsg, i_array);
PromptForChar(charMsg, c_array);

DumpInt(dmpIntMsg, i_array);
DumpChar(dmpCharMsg, c_array);


// close the logfile and exit
LOGFILE.close();
return 0;
}
Exemplo n.º 29
0
void ask(istream& in, ofstream& log, Aeromatic::Param* param)
{
    string input;

    cout << param->name();
    cout << " [" << param->get_units() << "]";
    cout << " (" << param->get() << ")";
    cout << ": ";

    unsigned options = param->no_options();
    for(unsigned j=0; j<options; ++j)
    {
        cout << endl;
        cout << " " << j << ": ";
        cout << param->get_option(j);
    }
    if (options) cout << endl;

    getline(in, input);
    if (!input.empty())
    {
        if (input == "?" || input == "h" || input == "help")
        {
            cout << param->help() << endl;
            getline(in, input);
        }
        if (!input.empty()) {
            param->set(input);
        }
    }
    if (log.is_open()) {
        log << input << endl;
    }
}
Exemplo n.º 30
0
int main(int argc, CHAR *argv[])
{
    PIN_InitSymbols();

    if( PIN_Init(argc,argv) )
    {
        return Usage();
    }
	
    string outFileName = KnobOutputFile.Value() + string("_") + decstr(PIN_GetPid());
    Out.open(outFileName.c_str(), ios_base::app);
    if (!Out.is_open()) 
    {
        cerr << "Can't open file " <<  outFileName << endl;
        exit(-1);
    }
    cerr << "Open file " <<  outFileName << endl;

    PIN_AddForkFunctionProbed(FPOINT_BEFORE, BeforeFork, 0);
    PIN_AddForkFunctionProbed(FPOINT_AFTER_IN_CHILD, AfterForkInChild, 0);
    PIN_AddForkFunctionProbed(FPOINT_AFTER_IN_PARENT, AfterForkInParent, 0);
    PIN_AddFollowChildProcessFunction(FollowChild, 0);

    PIN_StartProgramProbed();

    return 0;
}