Esempio n. 1
20
void put_check_for_nan(const CppAD::vector<Base>& vec, std::string& file_name)
{
	size_t char_size       = sizeof(Base) * vec.size();
	const char* char_ptr   = reinterpret_cast<const char*>( vec.data() );
# if CPPAD_HAS_MKSTEMP
	char pattern[] = "/tmp/fileXXXXXX";
	int fd = mkstemp(pattern);
	file_name = pattern;
	write(fd, char_ptr, char_size);
	close(fd);
# else
# if CPPAD_HAS_TMPNAM_S
		std::vector<char> name(L_tmpnam_s);
		if( tmpnam_s( name.data(), L_tmpnam_s ) != 0 )
		{	CPPAD_ASSERT_KNOWN(
				false,
				"Cannot create a temporary file name"
			);
		}
		file_name = name.data();
# else
		file_name = tmpnam( CPPAD_NULL );
# endif
	std::fstream file_out(file_name.c_str(), std::ios::out|std::ios::binary );
	file_out.write(char_ptr, char_size);
	file_out.close();
# endif
	return;
}
Esempio n. 2
0
bool CmdWriteIfcFile::doCmd()
{
	if( m_file_path.length() == 0 )
	{
		return false;
	}

	shared_ptr<GeometryConverter> geom_converter = m_system->getGeometryConverter();
	shared_ptr<IfcPPModel>& model = geom_converter->getIfcPPModel();
	model->initFileHeader( m_file_path );
	std::stringstream stream;

	m_system->getIfcPPWriter()->writeModelToStream( stream, model );

	QFile file_out( m_file_path.c_str() );
	if( !file_out.open(QIODevice::WriteOnly | QIODevice::Text) )
	{
		return false;
	}

	QTextStream file_out_stream( &file_out );
	file_out_stream << stream.str().c_str();
	file_out.close();

	return true;
}
Esempio n. 3
0
int main(int argc, char const *argv[]) {
	std::fstream file_out( "out.txt" , std::fstream::out);
	// std::fstream file( "in.txt" , std::fstream::in);

	//std::string inputStr("1 8");  // found 4
	//std::string inputStr("2 16");  // found 4
	//std::string inputStr("37 12392342");  // found 23104.9993088173
	std::string inputStr("1 2000000000");  // found 76374950.8918325007
	std::istringstream iss(inputStr);

	//std::istream& input = std::cin;
	std::istream& input = iss;
	// std::istream& input = file;

	std::cout.precision(10);
	std::cout << std::fixed;
	std::ostream& output = std::cout;
	// std::ostream& output = file_out;

	double c;
	input >> c;

	double time;
	input >> time;

	SortEstimate se;

	double numberOfInts = se.howMany(c, time, output);
	output << "\n\nnumberOfInts = " << numberOfInts << "\n";

	file_out.close();
	return 0;
}
int main( int argc, char** argv )
{
    std::string codec_in("XML"),
                codec_out("Bach");

    while (1) {
        int c = getopt(argc, argv, "fs:i:o:");
        if (c == -1) {
            break;
        } else if (c == 'f') {
            option_format = 1;
        } else if (c == 's') {
            option_spacing = strtol(optarg, NULL, 0);
        } else if (c == 'i') {
            codec_in = optarg;
        } else if (c == 'o') {
            codec_out = optarg;
        }
    }

    if ((argc - optind) != 2) {
        usage(argv[0]);
        return 1;
    }

    std::string file_in(argv[argc - 2]);
    std::string file_out(argv[argc - 1]);

    std::cout << "Reading from " << file_in << " to " << file_out << std::endl << std::flush;

    // convert file
    return convert(file_in, codec_in, file_out, codec_out);
}
Esempio n. 5
0
bool HMI_Initial::FileCopyToConfigdir(const char *dir_)
{
    QDir  dir(dir_);
    if(!dir.exists()){
        LOGE("%s not exist",dir.dirName().toUtf8().data());
        return false;
    }
    if(!QDir(CONFIG_DIR).exists()){
        QDir dir;
        if(!dir.mkdir(CONFIG_DIR)){
            LOGE("%s create failed",CONFIG_DIR);
            return false;
        }
        else
            LOGE("%s create success",CONFIG_DIR);
    }
    QFileInfoList list=dir.entryInfoList();
    LOGI("total %d files",list.count());
    for(int i=0;i<list.count();i++){
        QFileInfo info=list.at(i);

        QFile file_in(info.filePath());
        file_in.open(QFile::ReadOnly);
        QFile file_out(QString(CONFIG_DIR)+"/"+info.fileName());
        file_out.open(QFile::ReadWrite);
        file_out.write(file_in.readAll());
        file_out.close();
        file_in.close();
        LOGI("%s copy to %s",file_in.fileName().toUtf8().data(),file_out.fileName().toUtf8().data());
    }
    return true;
}
 virtual int main(const std::vector<std::string> &args) override {
     if(args.size() > 0) {
         logger().warning("You supplied arguments; program does not take any");
         displayHelp();
         return TwitterSubliminalDecode::EXIT_USAGE;
     }
     if (terminate_early) {
         return TwitterSubliminalDecode::EXIT_OK;
     }
     block_size = config().getUInt("blocksize");
     logger().information("Decoding subliminal message with block size %?u from Twitter.", block_size);
     std::string result;
     DO_CASE(block_size);
     logger().information("Successfully decoded message of size %?u bytes.", result.size());
     if(!config().has("output_path")) {
         logger().information(result);
     } else {
         auto output_path = config().getString("output_path");
         std::ofstream file_out(output_path);
         if(file_out.fail()) {
             logger().critical("Unable to open %s for writing.", output_path);
             return TwitterSubliminalDecode::EXIT_IOERR;
         }
         file_out << result;
         logger().information("Wrote output to %s", output_path);
     }
     return TwitterSubliminalDecode::EXIT_OK;
 };
Esempio n. 7
0
int main(int argc,char **argv)
{
//  debug_builder dbg;
//  null_builder dbg;
//  csv_writer<file_out> dbg((file_out(stdout))); // CPP11: dbg{{stdout}}
//  csv_writer<file_out> dbg(file_out(stdout),'\'',',',true);

#if 1
    SimpleCSV::Table tbl;
    SimpleCSV::builder dbg(tbl);
#endif

    csvparser cp(dbg,'\'');
    cp(
        "\n"
        "1, 's' , 3,4   a\n"
        ",1,2,3,4\n"
        " asdf, 'asd''df', s\n"
    );

    csv_writer<file_out> dbg2(file_out(stdout),'\'',',',true);
    tbl.write(dbg2);

    return 0;
}
Esempio n. 8
0
void Window::on_btnStart_clicked()
{
    {
        QFile file(ui->input_filename->text());
        if (!file.open(QIODevice::ReadOnly))
        {
            QMessageBox::critical(this, ui->input_filename->text(), "Не можу відкрити вхідний файл.", QMessageBox::Ok);
            return;
        }

        QFile file_out(ui->output_filename->text());
        if (ui->allow_save_to_file->isChecked() && !file_out.open(QIODevice::WriteOnly))
        {
            QMessageBox::critical(this, ui->output_filename->text(), "Не можу відкрити вихідний файл.", QMessageBox::Ok);
            return;
        }
    }

    clearAll();

    ui->groupBox->setEnabled(false);
    ui->progressBar->setValue(0);
    ui->progressBar->show();
    calculator->setData(ui->input_filename->text(),
                        ui->output_filename->text(),
                        ui->spin_from->value(),
                        ui->spin_to->value(),
                        ui->spin_average->value());
    calculator->u_coef = ui->spin_u_coef->value();
    calculator->i_coef = ui->spin_i_coef->value();
    calculator->setInvertPolicy(ui->invert_1->isChecked() && ui->invertion->isChecked(), ui->invert_2->isChecked() && ui->invertion->isChecked());
    emit beginCalc();
}
Esempio n. 9
0
void output_image(char* filename,int* image,int width,int height)
	{
	//------------------------------------------------------- HEADER
	// create/erase file
	ofstream file_out(filename);

	// raw PGM data format 
	file_out<<"P5\n";

	// commnet on PGM file
	file_out<<"#Lupescu Grigore @2010\n";

	// write image size
	file_out<<width<<" "<<height<<"\n";

	// write max grayscale value
	file_out<<255<<"\n";

	// finish writing header
	file_out.close();	
	
	//------------------------------------------------------- BODY
	// attempt to append file for writing
	FILE* fp=fopen(filename, "a+b");
	if(fp==NULL)
		return;

	//write data
	for(int i=0;i<width;i++)
		for(int j=0;j<height;j++)
			fwrite((char*)&image[i*height+j],1,1,fp);
		
	// close file
	fclose(fp);
	}
Esempio n. 10
0
	//Assumes larva_scores is already sorted
	void write_larva_scores(std::string name, int score) {
		bool is_it_too_big = false; //assume false
		if(larva_scores.size() != 0) {
			std::tuple<std::string, int> last_entry = larva_scores.at(larva_scores.size()-1);
			if((score < std::get<1>(last_entry)) && larva_scores.size() == 9) {
				is_it_too_big = false;
				larva_scores.pop_back();
			}
			else if((score > std::get<1>(last_entry)) && larva_scores.size() == 9) {
				is_it_too_big = true;
			}
			//else { is_it_too_big = false; }
		}
		if(is_it_too_big == true) {
			std::cout << "Sorry " + name + " your score isn't good enough to make the high scores :(" << std::endl;
		}
		else {
			if(name.size() < 10) {
				int initial_size = name.size();
				for(int i=initial_size; i<10; i++) {
					name += " "; //FORMATTING
				}
			}
			larva_scores.push_back(std::make_tuple(name, score));
			//http://stackoverflow.com/questions/23030267/custom-sorting-a-vector-of-tuples
			std::sort(larva_scores.begin(), larva_scores.end(), 
				[](std::tuple<std::string, int> const &t1, std::tuple<std::string, int> const &t2) {
				return std::get<1>(t1) < std::get<1>(t2);
				});

			std::string file_lines[23];
			std::string line;
			std::ifstream file_in (scores_file);
			if(file_in.is_open()) {
				int count = 0; 
				while(std::getline(file_in, line)) {
					file_lines[count] = line;
					count++;
				}
				file_in.close();
			}
			else { std::cout << "Unable to open file." << std::endl; }
		
			std::ofstream file_out (scores_file);
			if(file_out.is_open()) { 
				for(int i=0; i<23; i++) {
					int bound = larva_scores.size();
					if((i > 1 && i < 11) && ((i-2)<bound)) {
						std::tuple<std::string, int> temp = larva_scores.at(i-2);
						int place = i-1;
						file_out << place << ".   " + std::get<0>(temp) + "     " << std::get<1>(temp) << "\n"; 
					}
					else { file_out << file_lines[i] + "\n"; } 
				}
				file_out.close();
			}	
			else { std::cout << "Unable to open file." << std::endl; }
		}
	}
Esempio n. 11
0
void frmInstalarJuego::on_btnOk_clicked()
{
	QDir dir;
	QString install_info = tr("El ejecutable suele ser: INSTALL, si no esta seguro teclee DIR y pulsa INTRO");
	if( QFile::exists(grlCfg.DirDOSBox) && dir.exists(fGrl->getDirRelative(ui->txtDestinoPath->text(), "DosGames")) )
	{
		QStringList lista_multiple_iso;
		QString tipo_origen = ui->cbxMontaje_type_drive->itemData( ui->cbxMontaje_type_drive->currentIndex() ).toString();
		QFile file_out(grlDir.Temp +"dosbox.conf");
		if ( file_out.open(QIODevice::WriteOnly | QIODevice::Text) )
		{
			QString dir_montaje = fGrl->getDirRelative(ui->txtMontaje_path->text(), "DosGames");

			QTextStream out(&file_out);
			out.setCodec("UTF-8");
			out << "[autoexec]" << endl;
			out << "@echo off" << endl;

			if( tipo_origen == "drive" )
				out << "mount D \"" << dir_montaje << "\"" << endl;
			else if( tipo_origen == "cdrom" )
				out << "mount D \"" << dir_montaje << "\" -t cdrom" << endl;
			else if( tipo_origen == "floppy" )
				out << "mount A \"" << dir_montaje << "\" -t floppy" << endl;
			else if( tipo_origen == "IMG_floppy" )
				out << "imgmount A \"" << dir_montaje << "\" -t floppy" << endl;
			else if( tipo_origen == "IMG_iso" )
				out << "imgmount D \"" << dir_montaje << "\" -t iso" << endl;
			else if( tipo_origen == "IMG_multi_iso" )
			{
				lista_multiple_iso.clear();
				for( int i = 0; i < ui->lw_MultiIso->count(); ++i )
				{
					if(i == 0)
						lista_multiple_iso << "\""+ fGrl->getShortPathName( fGrl->getDirRelative(ui->lw_MultiIso->item(i)->text()) ) +"\"";
					else
						lista_multiple_iso << "\""+ fGrl->getDirRelative(ui->lw_MultiIso->item(i)->text()) +"\"";
				}
				out << "imgmount D " << lista_multiple_iso.join(" ") << " -t iso" << endl;
			}
			else if( tipo_origen == "IMG_hdd" )
				out << "imgmount D \"" << dir_montaje << "\" -t hdd" << endl;

			out << "mount C \"" << fGrl->getDirRelative(ui->txtDestinoPath->text(), "DosGames") << "\"" << endl;
			out << "echo " << install_info << endl;

			if(tipo_origen == "floppy" || tipo_origen == "IMG_floppy")
				out << "A:" << endl;
			else
				out << "D:" << endl;

			out.flush();
			file_out.close();
		}
		ejecutar( grlCfg.DirDOSBox, "-conf|"+grlDir.Temp +"dosbox.conf", grlDir.Temp);
	} else
		QMessageBox::information( this, "",tr("Puede que no este disponible el ejecutable del emulador.\nO el directorio de destino."));

}
Esempio n. 12
0
void InliningDatabase::local_file_out_klass(nmethod* nm) {
  if (nm->isZombie()) return;
  if (nm->receiver_klass() == local_klass) {
    if (file_out(nm)) {
      local_number_of_nmethods_written++;
    }
  }
}
Esempio n. 13
0
File: INI.cpp Progetto: LoisG/yetris
void INI::Parser::saveAs(std::string filename)
{
	std::ofstream file_out(filename.c_str());
	if (!file_out)
		throw std::runtime_error(std::string("Couldn't open '" + filename + "'"));

	this->dump(file_out);
}
Esempio n. 14
0
void analysis_t_test1::Terminate()
{
   // The Terminate() function is the last function to be called during
   // a query. It always runs on the client, it can be used to present
   // the results graphically or save the results to file.
  TFile file_out("analysis_t_test1_output.root","recreate");
  TList *outlist = GetOutputList();
  
  outlist->Write();
  file_out.Write();
  file_out.Close();

}
Esempio n. 15
0
void frmListIconCfg::on_btnSaveText_clicked()
{
	QString archivo = fGrl->ThemeApp() + ui->cbxListFiles->itemData( ui->cbxListFiles->currentIndex() ).toString();
	QFile file_out( archivo );
	if( file_out.exists() )
	{
		if ( file_out.open(QIODevice::WriteOnly | QIODevice::Text) )
		{
			QTextStream out(&file_out);
			out.setCodec("UTF-8");
			out << editor->toPlainText() << endl;
			out.flush();
			file_out.close();
		}
	}
}
Esempio n. 16
0
void
MatrixEigenSparse<T>::printMatlab( const std::string filename ) const
{
    std::string name = filename;
    std::string separator = " , ";

    // check on the file name
    int i = filename.find( "." );

    if ( i <= 0 )
        name = filename + ".m";

    else
    {
        if ( ( size_type ) i != filename.size() - 2 ||
                filename[ i + 1 ] != 'm' )
        {
            std::cerr << "Wrong file name ";
            name = filename + ".m";
        }
    }

    std::ofstream file_out( name.c_str() );

    FEELPP_ASSERT( file_out )( filename ).error( "[Feel::spy] ERROR: File cannot be opened for writing." );

		std::string varName = "var_" + filename.substr(0,filename.find("."));
    file_out << varName << " = [ ";
    file_out.precision( 16 );
    file_out.setf( std::ios::scientific );

    for (int k=0; k<M_mat.outerSize(); ++k)
    {
        for (typename matrix_type::InnerIterator it(M_mat,k); it; ++it)
        {
            value_type v = it.value();

            file_out << it.row() + 1 << separator
                     << it.col() + 1 << separator
                     << v  << std::endl;
        }
    }

    file_out << "];" << std::endl;
    file_out << "I="<<varName<<"(:,1); J="<<varName<<"(:,2); "<<varName<<"="<<varName<<"(:,3);" << std::endl;
    file_out << "spy("<<varName<<");" << std::endl;
}
Esempio n. 17
0
void CodeText(string file_name, string text, int sequence_length /*= 1*/)
{
  auto occurrences = CountCharsOccurrence(text, sequence_length);
  auto huffman_codes = Huffman(occurrences);

  // write huffman codes
  ofstream file_out(file_name, std::ios::binary);
  if (!file_out.is_open()) return;

  // write sequence length
  file_out.write((char*)&sequence_length, sizeof(int));
  // write max_code length
  int max_code_length = FindMaximumHuffmanCode(huffman_codes).size();
  file_out.write((char*)&max_code_length, sizeof(int));
  // write codes num
  int num_codes = huffman_codes.size();
  file_out.write((char*)&num_codes, sizeof(int));
  // write codes one by one
  for (unsigned i = 0; i < num_codes; ++i) {
    string str = huffman_codes[i].first;
    string code = huffman_codes[i].second;
    file_out.write(str.c_str(), sizeof(char)*(sequence_length+1));
    file_out.write(code.c_str(), sizeof(char)*(max_code_length+1));
  }
  // code text
  string text_coded = ReplaceCharForHuffmanCode(text, huffman_codes);
  // number bytes to write
  int num_data_bytes = ceil(text_coded.size()/8.0);
  file_out.write((char*)&num_data_bytes, sizeof(int));
  // write coded text byte by byte
  for (unsigned i = 0; i < text_coded.size(); i+=8) {
    string byte_slice = text_coded.substr(i, 8);
    if (byte_slice.size() < 8) {
      byte_slice.append(8 - byte_slice.size(), '0');
    }
    char byte = BinaryStringToULong(byte_slice);
    file_out.write((char*)&byte, sizeof(char));
  }
  cout << "================ " << file_name << " ================";
  cout << "\nCoded file size=" << file_out.tellp();
  cout << "\n\tNum of codes=" << num_codes;
  cout << "\n\tMax. code length=" << max_code_length;
  cout << "\n\tCharacter sequence length=" << sequence_length << endl;
  file_out.close();
}
Esempio n. 18
0
bool Account::createAccount(const std::string& accountName, const int& accountNum, const std::string& pin, const std::string& bankSalt)
{
	if(accountName == "")
	{
		return false;
	}
	this->accountName = accountName;
	if(accountNum <= 0)
	{
		return false;
	}
	this->accountNum = accountNum;

	this->salt = makeHash(randomString(128));

	std::string card = makeHash(to_string(this->accountNum) + salt);

	this->card = card;

	std::ofstream outfile;

	std::string cardFile = "cards/" + this->accountName + ".card";

	std::ofstream file_out(cardFile.c_str());
	// write values to cards
	if(file_out.is_open())
	{
		file_out << card;
	} 
	file_out.close();

	//If oin sucessfully set then the account can be unlocked for use.
	if(setPIN(pin, bankSalt))
	{
		islocked = false;
	} else {
		islocked = true;
	}

	return true;
}
Esempio n. 19
0
void LLSpellChecker::addToDictFile(const std::string& dict_path, const std::string& word)
{
	std::vector<std::string> word_list;

	if (gDirUtilp->fileExists(dict_path))
	{
		llifstream file_in(dict_path.c_str(), std::ios::in);
		if (file_in.is_open())
		{
			std::string word; int line_num = 0;
			while (getline(file_in, word))
			{
				// Skip over the first line since that's just a line count
				if (0 != line_num)
				{
					word_list.push_back(word);
				}
				line_num++;
			}
		}
		else
		{
			// TODO: show error message?
			return;
		}
	}

	word_list.push_back(word);

	llofstream file_out(dict_path.c_str(), std::ios::out | std::ios::trunc);	
	if (file_out.is_open())
	{
		file_out << word_list.size() << std::endl;
		for (std::vector<std::string>::const_iterator itWord = word_list.begin(); itWord != word_list.end(); ++itWord)
		{
			file_out << *itWord << std::endl;
		}
		file_out.close();
	}
}
Esempio n. 20
0
bool BFile::copy ( const BAsciiString &filename, const BAsciiString &new_filename ) {
    if ( !exists ( filename ) || exists ( new_filename ) ) {
        return false;
    }

    BFile file_in ( filename );
    if ( !file_in.open ( BIODevice::ReadOnly ) ) {
        return false;
    }

    BFile file_out ( new_filename );
    if ( !file_out.open ( BIODevice::WriteOnly ) ) {
        return false;
    }

    file_out.write ( file_in.Buffer );

    file_in.close();
    file_out.close();

    return true;
}
Esempio n. 21
0
bool CmdWriteIfcFile::doCmd()
{
	if( m_file_path.length() == 0 )
	{
		return false;
	}

	m_system->getIfcModel()->initFileHeader( m_file_path );
	std::stringstream stream;
	m_reader_writer->getIfcPPWriter()->writeStream( stream, m_system->getIfcModel() );

	QFile file_out( m_file_path.c_str() );
	if( !file_out.open(QIODevice::WriteOnly | QIODevice::Text) )
	{
		return false;
	}

	QTextStream file_out_stream( &file_out );
	file_out_stream << stream.str().c_str();
	file_out.close();

	return true;
}
Esempio n. 22
0
void Bundle::write_ascii(char *filename, int taper_info)
{
  ofstream file_out (filename);

  file_out << "! this file contains " << num_lines << " streamlines" << endl;
  file_out << endl;
  file_out << "delta_step " << delta_step << endl;
  file_out << endl;

  for (int i = 0; i < num_lines; i++) {
    Streamline *st = lines[i];
    file_out << "st " <<
      st->xorig << " " <<
      st->yorig << " " <<
      st->length1 << " " <<
      st->length2 << " ";
    if (taper_info)
      file_out << st->taper_tail << " " << st->taper_head;
    file_out << endl;
  }

  file_out << endl;
}
int main(int argc, char *argv[])
{
    char infile_name[256],outfile_name[256];
    
    if (argc > 1) strcpy(infile_name,argv[1]);
    else strcpy(infile_name,"course_inf.txt");
    ifstream file_in(infile_name);    //  声明与打开输入流

    if (file_in == 0) {
        cout << "不能打开课程信息文件 " << infile_name << endl;
        exit (1);
    }
   
    if (argc > 2) strcpy(outfile_name,argv[2]);
    else strcpy(outfile_name,"curriculum_scedule.txt");
    ofstream file_out(outfile_name);   //  声明与打开输出流

    if (file_out == 0) {
        cout << "不能打开课程请文件 " << outfile_name << endl;
        exit (1);
    }

    cout<<"课程信息文件为: "<<infile_name<<endl<<endl;
    cout<<"正在排课,请稍候..."<<endl<<endl;

    //Range_Course<8,1000>表示排8学期课(从第1学期到第8学期),最多能对1000门课进行排课
    Range_Course<8,1000> rc(&file_in, &file_out);

    rc.read();               //输入课程信息
    rc.topological_order();  //用拓扑排的思进行排课
    rc.write();              //输出课表

    cout<<"排课结束,课表文件为: "<<outfile_name<<endl;
    cout<<"按任意退出"<<endl;

    return 0;
}
Esempio n. 24
0
void MibEditor::ExtractMIBfromRFC(void)
{
    QRegExp module_regexp("^[ \t]*([A-Za-z0-9-]*) *(PIB-)?DEFINITIONS *(::=)? *(BEGIN)? *$");
    QRegExp page_regexp("\\[[pP]age [iv0-9]*\\] *");
    QRegExp macro_regexp("^[ \t]*[A-Za-z0-9-]* *MACRO *::=");
    QRegExp end_regexp("^[ \t]*END[ \t]*$");
    QRegExp blankline_regexp("^[ \t]*$");
    QRegExp blank_regexp("[^ \t]");
    QRegExp leadingspaces_regexp("^([ ]*)");
    QRegExp draft_regexp("^[ ]*Internet[ \\-]Draft");

    QFile file_in("empty");
    QFile file_tmpout("empty");
    QFile file_out("empty");
    QTextStream in(&file_in);
    QTextStream tmpout; 
    QTextStream out; 

    QString line;
    QString module;
    QStringList modules;

    QString dir = NULL, filename = NULL;
    int skipmibfile = 0, skip = 0, skipped = 0, macro = 0, n = 0;

    // Open RFC file
    filename = QFileDialog::getOpenFileName(s->MainUI()->MIBFile,
                                        tr("Open RFC file"), "", 
                                        "RFC files (*.txt);;All Files (*.*)");

    if (!filename.isEmpty())
    {
        file_in.setFileName(filename);
        if (!file_in.open(QFile::ReadOnly | QFile::Text))
        {
            QMessageBox::warning(NULL, tr("SnmpB: Extract MIB from RFC"),
                                 tr("Cannot read file %1: %2\n")
                                 .arg(file_in.fileName())
                                 .arg(file_in.errorString()));
            return;
        }
    }
    else
        return;

    // Ask for directory where to save MIB files 
    dir = QFileDialog::getExistingDirectory(s->MainUI()->MIBFile,
                           tr("Select destination folder for MIB files"), "");

    if (dir.isEmpty())
    {
        QMessageBox::warning(NULL, tr("SnmpB: Extract MIB from RFC"),
                             tr("No directory selected. Aborting.\n"));
        file_in.close();
        return;
    }

    if (!QFileInfo(dir).isWritable())
    {
        QMessageBox::warning(NULL, tr("SnmpB: Extract MIB from RFC"),
                tr("Directory not writable by this user. Aborting.\n"));
        file_in.close();
        return;
    }

    // Extract & save each modules ...

    // Process each line
    while (in.atEnd() != true)
    {
        line = in.readLine();

        if (draft_regexp.indexIn(line) != -1)
            continue;

        // Start of module
        if (module_regexp.indexIn(line) != -1)
        {
            module = module_regexp.cap(1); 
            skip = 9;
            skipped = -1;
            macro = 0;
            n = 0;

            // Create temporary output file
            file_tmpout.setFileName(QDir::tempPath()+"/"+module+".tmp");
            file_tmpout.remove();
            if (!file_tmpout.open(QFile::ReadWrite | QFile::Text))
            {
                QMessageBox::warning(NULL, tr("SnmpB: Extract MIB from RFC"),
                                     tr("Cannot create file %1: %2. Abort.\n")
                                     .arg(file_tmpout.fileName())
                                     .arg(file_tmpout.errorString()));
                file_in.close();
                return;
            }

            tmpout.setDevice(&file_tmpout); 

            // Create output file
            file_out.setFileName(dir+"/"+module);
            if (file_out.exists())
            {
                QMessageBox mb(QMessageBox::Question, 
                               tr("SnmpB: Extract MIB from RFC"), 
                               tr("The file %1 already exist.\n")
                               .arg(file_out.fileName()));
                QPushButton *ob = mb.addButton(tr("Overwrite"), 
                                               QMessageBox::YesRole);
                QPushButton *sb = mb.addButton(tr("Skip"), 
                                               QMessageBox::NoRole);
                mb.exec();

                if (mb.clickedButton() == ob)
                {
                    // overwrite 
                    skipmibfile = 0;
                }
                else if (mb.clickedButton() == sb)
                {
                    // skip 
                    skipmibfile = 1;
                }
            }
            else
                skipmibfile = 0;

            if (!skipmibfile)
            {
                file_out.remove();
                if (!file_out.open(QFile::ReadWrite | QFile::Text))
                {
                    QMessageBox::warning(NULL, tr("SnmpB: Extract MIB from RFC"),
                                         tr("Cannot create file %1: %2. Skipping.\n")
                                         .arg(file_out.fileName())
                                         .arg(file_out.errorString()));
                    skipmibfile = 1;
                }
                else
                    out.setDevice(&file_out);
            }
        }

        // At the end of a page we start the counter skipped to skip the
        // next few lines.
        if (page_regexp.indexIn(line) != -1)
            skipped = 0;

        // If we are skipping...
        if (skipped >= 0)
        {
            skipped++;

            // If we have skipped enough lines to the top of the next page...
            if (skipped >= skip)
            {
                skipped = -1;
            }
            else
            {
                // Finish skipping, if we find a non-empty line, but not before
                // we have skipped four lines. remember the miminum of lines
                // we have ever skipped to keep empty lines in a modules that
                // appear near the top of a page.
                if ((skipped >= 4) && (blank_regexp.indexIn(line) != -1))
                {
                    if (skipped < skip)
                        skip = skipped;

                    skipped = -1;
                }   
            }
        }

        // So, if we are not skipping and inside a module, remember the line.
        if ((skipped == -1) && (module.length() > 0))
        {
            n++;
            tmpout << line << endl;
        }

        // Remember when we enter a macro definition
        if (macro_regexp.indexIn(line) != -1)
            macro = 1;

        // End of module
        if (end_regexp.indexIn(line) != -1)
        {
            if (macro == 0)
            {
                tmpout.flush(); 
                tmpout.seek(0);

                int strip = 99, p = 0;

                while (tmpout.atEnd() != true)
                {
                    line = tmpout.readLine();

                    // Find the minimum column that contains non-blank
                    // characters in order to cut a blank prefix off.
                    // Ignore lines that only contain white spaces.
                    if (blankline_regexp.indexIn(line) == -1)
                    {
                        if (leadingspaces_regexp.indexIn(line) != -1)
                        {
                            p = leadingspaces_regexp.cap(1).length(); 
                            if ((p < strip) && (line.length() > p))
                                strip = p;
                        }
                    }
                }

                tmpout.seek(0);

                if (!skipmibfile)
                {
                    int num_bl = 0;

                    while (tmpout.atEnd() != true)
                    {
                        line = tmpout.readLine();
                        // For each block of consecutive blank lines,
                        // remove all lines but one.
                        if (blankline_regexp.indexIn(line) != -1)
                        {
                            num_bl++;
                            continue;
                        }
                        else
                        {
                            if (num_bl > 0)
                                out << endl;
                            num_bl = 0;
                        }

                        out << line.remove(0, strip) << endl;
                    }

                    out.flush(); 
                    file_out.close();

                    modules << module;
                }

                file_tmpout.remove();

                module = "";
            }
            else
            {
                macro = 0;
            }
        }
    }

    file_in.close();
 
    if(modules.size() > 0)
    {
        QString module_list;
        for (int i = 0; i < modules.size(); i++)
        {
            module_list += "\n\t";
            module_list +=  modules[i];
        }

        QMessageBox::information(NULL, tr("SnmpB: Extract MIB from RFC"),
                                 tr("%1 MIB module(s) have been extracted. \
The following MIB file(s) were created: %2")
                                 .arg(modules.size())
                                 .arg(module_list));
    }
Esempio n. 25
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    // Open the installer file
    QString name_in = "full_installer_script.nsi";
    QString name_out = name_in + "temp";
    QFile file_in(name_in);
    QFile file_out(name_out);
    file_in.open(QIODevice::ReadOnly | QIODevice::Text);
    file_out.open(QIODevice::WriteOnly | QIODevice::Truncate);
    QTextStream in_enc(&file_in);
    QTextStream out_enc(&file_out);
    out_enc.setCodec("UTF-8");
    while(!in_enc.atEnd())
    {
        QString line = in_enc.readLine();
        // Update to current revision
        if(line.contains("  !define REVISION "))
        {
            QStringList temp = line.split("\"");
            temp[1] = QString::number(getLocalVersion());
            line = temp.join("\"");
        }

        // Update translations lines (including commented ones)
        QString langString = "LangString ";
        if(line.startsWith("; LangString")){
            langString = "; LangString ";
        }

        if(line.startsWith(langString)){
            QString backup = line;

            // Get language infos
            QStringList temp_lang = line.replace("{","|").replace("}","|").split("|");
            QStringList temp_lang_name = temp_lang[1].split("_");
            QString langName = temp_lang_name[1];
            QString langCode = getLanguageCodeFromName(langName);

            // Get tag
            QStringList temp_tag = temp_lang[0].split(" ");
            QString tag = temp_tag[1];
            if(backup.startsWith(";"))
            { // Pick the second char as the first is a comment
                tag = temp_tag[2];
            }
            QString translation = getTranslation(langCode, tag);
            if (!translation.isEmpty())
            {
                line = langString + tag + " ${LANG_" + langName + "} " + "\"" + translation + "\"";
            }
            else
            {
                line = backup;
            }
        }

        out_enc << line << "\n";
    }
    file_in.close();
    file_out.close();
    QFile::remove(name_in);
    QFile::rename(name_out,name_in);
    return 0;
}
Esempio n. 26
0
void InliningDatabase::local_file_out_all(nmethod* nm) {
  if (nm->isZombie()) return;
  if (file_out(nm)) {
    local_number_of_nmethods_written++;
  }
}
int main(int argc, char * argv[])
{
    system("bash dataprep.sh");

    #pragma omp parallel for
    for(int n=1; n<argc; n++)
    {
        Mat srcImg=imread(argv[n],CV_LOAD_IMAGE_GRAYSCALE);
        Mat img=imread(argv[n],CV_LOAD_IMAGE_COLOR);
        string str=argv[n];
        cout<<"\n\n processing the image: "<<str<<endl;
        if (!srcImg.data)
        {
            cout<<"failed to load the image!\n";
            // return 0;
            continue;
        }

        for(int i=0; i< srcImg.rows; i++)
        {
            for(int j=0; j<5; j++)
            {
                srcImg.at<uchar>(i,j)=uchar(0);
                srcImg.at<uchar>(i,srcImg.cols-j-1)=uchar(0);
            }
        }

        for(int i=0; i<srcImg.cols; i++)
        {
            for(int j=0; j<5; j++)
            {
                srcImg.at<uchar>(j,i)=uchar(0);
                srcImg.at<uchar>(srcImg.rows-j-1,i)=uchar(0);
            }
        }

        //detect lsd lines in an input image;
        int cols=srcImg.rows;
        int rows=srcImg.cols;
        double*  lsd_srcImg=new double[cols*rows];
        for (int i=0; i<cols; i++)
        {
            for (int j=0; j<rows; j++)
            {
                lsd_srcImg[i+j*cols]=static_cast<double>(srcImg.at<uchar>(i,j));
            }
        }
        double* lsd_dstImg;
        int n=0;
        lsd_dstImg=lsd(&n,lsd_srcImg,cols,rows);

        cout<<"finished the lsd detection!\n";
        vector<LSDline> lsdLine;
        for (int i=0; i<n; i++)
        {
            LSDline lsdLine_tmp;
            lsdLine_tmp.lineBegin.y=lsd_dstImg[i*7+0];
            lsdLine_tmp.lineBegin.x=lsd_dstImg[i*7+1];
            lsdLine_tmp.lineEnd.y=lsd_dstImg[i*7+2];
            lsdLine_tmp.lineEnd.x=lsd_dstImg[i*7+3];
            lsdLine_tmp.width=lsd_dstImg[i*7+4];
            lsdLine_tmp.p=lsd_dstImg[i*7+5];
            lsdLine_tmp.log_nfa=lsd_dstImg[i*7+6];
            lsdLine_tmp.tagBegin=1;
            lsdLine_tmp.tagEnd=1;
            cout<<lsdLine_tmp.lineBegin.x<<" "<<lsdLine_tmp.lineBegin.y<<" "<<lsdLine_tmp.lineEnd.x<<"  "<<lsdLine_tmp.lineEnd.y<<endl;
            float distThreshold=12;
            if(sqrt((lsdLine_tmp.lineBegin.x-lsdLine_tmp.lineEnd.x)*(lsdLine_tmp.lineBegin.x-lsdLine_tmp.lineEnd.x)+
                    (lsdLine_tmp.lineBegin.y-lsdLine_tmp.lineEnd.y)*(lsdLine_tmp.lineBegin.y-lsdLine_tmp.lineEnd.y))>distThreshold)
            {
                lsdLine.push_back(lsdLine_tmp);
            }
        }

        cout<<"the detected lsd lines' number is: "<<lsdLine.size()<<endl;
        //define the img1 to display the detected LSD lines and junctions;
        Mat img1(img.size(),CV_8UC3,Scalar::all(0));
        delete[] lsd_srcImg;


        displayLSDline(lsdLine,img1);
        //imwrite("img1.bmp",img1);

        vector<Ljunct> Jlist;
        vector<LsdJunction> lsdJunction;



        if(LSD2Junct(lsdLine,Jlist,lsdJunction,search_distance,img))
        {
            cout<<"transform successfully!\n";
        }
        else
        {
            cout<<"cannot form L-junctions from LSD lines!\n";
            //for processing, we also need to write the the detect result;
            char c='_';
            int name_end=str.find(c,0);
            string ori_name_tmp1=str.substr(7,name_end-7);
            // char* ch2=".bmp";
            // int location=str.find(ch2,0);
            // string ori_name_tmp1 = str.substr(7,location-7);
            string dst_tmp = "./DetectResultOri/"+ori_name_tmp1;
            string ori_name_tmp="./OrigImg/"+ori_name_tmp1;

            // Mat oriImg_tmp = imread(ori_name_tmp.c_str(),CV_LOAD_IMAGE_COLOR);
            // imwrite(dst_tmp,oriImg_tmp);
            string filestring_tmp="./dstFile/"+str.substr(srcImgDir.size(),str.size()-4)+".jpg.txt";
            ofstream file_out(filestring_tmp.c_str());
            if(!file_out.is_open())
            {
                cout<<"cannot open the txt file!\n";
            }
            string imageName=str.substr(srcImgDir.size(),str.size()-4)+".jpg";
            file_out<<imageName<<"\t"<<img.cols<<"\t"<<img.rows<<endl;

            continue;
        }
        //vector<string> code_string1;
        vector<Ljunct> Jlist_coding;
        vector<codeStringBoundingBox> code_string;
        code_string=encodingFromLsdJunction(lsdJunction, Jlist_coding,srcImg);
        classifyRoadMarking(code_string,srcImg);

        string str_tmp=str.substr(srcImgDir.size(),str.size());
        cout<<"!!!!!the Jlist_coding size is: "<<Jlist_coding.size()<<endl<<endl;
        
        displayLjunct(Jlist_coding,img1,str_tmp);

        DrawBoundingBox(code_string,img,str_tmp);

        //drawing the bounding box in original image;
        char c='_';
        int name_end=str.find(c,0);
      //  string ori_name=str.substr(7,name_end-7);
        
         char* ch=".bmp";
         int location=str.find(ch,0);
         cout<<"the find .bmp in "<<str<<" is in "<<location<<endl;
         string ori_name=str.substr(7,location-7);
        
         cout<<ori_name<<endl;
         string ori_img="./OrigImg/"+ori_name+".JPG";

         Mat oriImg=imread(ori_img.c_str(),CV_LOAD_IMAGE_COLOR);
         if(!oriImg.data)
         {
             cout<<"cannot load the original image!\n";
             //return 0;
             char ch;
             cin.get(ch);
             continue;
         }
         
        /*
        Point2f imgP1=Point2f(219,668);
        Point2f imgP2=Point2f(452,469);
        Point2f imgP3=Point2f(622,472);
        Point2f imgP4=Point2f(882,681);
        Point2f imgP5=Point2f(388,520);
        Point2f imgP6=Point2f(688,523);
        Point2f imgP7=Point2f(454,538);
        Point2f imgP8=Point2f(645,539);
        Point2f imgP9=Point2f(508,486);
        Point2f imgP10=Point2f(573,509);

        Point2f imgP[10]= {imgP1,imgP2,imgP3,imgP4,imgP5,imgP6,imgP7,imgP8,imgP9,imgP10};
        Point2f objP1=Point2f(250,900);
        Point2f objP2=Point2f(250,100);
        Point2f objP3=Point2f(800,100);
        Point2f objP4=Point2f(800,900);
        Point2f objP5=Point2f(250,550);
        Point2f objP6=Point2f(800,550);
        Point2f objP7=Point2f(400,625);
        Point2f objP8=Point2f(650,625);
        Point2f objP9=Point2f(450,300);
        Point2f objP10=Point2f(600,475);



        Point2f objP[10]= {objP1,objP2,objP3,objP4,objP5,objP6,objP7,objP8,objP9,objP10};
        */
        vector<Point2f> imgP;
        imgP.push_back(Point2f(300,450));
        imgP.push_back(Point2f(700,450));
        imgP.push_back(Point2f(465,450));
        imgP.push_back(Point2f(535,450));
        imgP.push_back(Point2f(260,820));
        imgP.push_back(Point2f(740,820));

        vector<Point2f> objP;
        objP.push_back(Point2f(0,0));
        objP.push_back(Point2f(1000,0));
        objP.push_back(Point2f(400,0));
        objP.push_back(Point2f(600,0));
        objP.push_back(Point2f(400,1000));
        objP.push_back(Point2f(600,1000));

        //Mat H=getPerspectiveTransform(objP,imgP);
        Mat H=findHomography(objP,imgP,CV_RANSAC);
        DrawBoundingBox_Ori(code_string,oriImg,ori_name,H,str_tmp);
    }
    return 0;
}
Esempio n. 28
0
int main(int argc, char** argv){
  
  
  QCoreApplication app(argc, argv);
  QDateTime logTime=QDateTime::currentDateTime();
  
  
  QTextStream standard_out(stdout);
  QTextStream standard_in(stdin);
  QTextStream file_out(stdout);
  QFile logFile(".spiedo.log");
  logFile.open(QIODevice::WriteOnly|QIODevice::Append);
  QTextStream log_out(&logFile);
  log_out << QObject::tr("####### - %1 - #######").arg( logTime.toString() )<< endl;
  
  
  
  
  QSerialPort * SerialSelected=Connection();
  if( SerialSelected == 0 )  return 1;
  ConfigurePort(SerialSelected);
  
  standard_out << QObject::tr("Serial is Configured") << endl;
  
  
  
  
  
  if( !SerialSelected->open(QIODevice::ReadWrite) ) {
    standard_out << QObject::tr(" Failed to open port %1, error: %2").arg(SerialSelected->portName()).arg(SerialSelected->errorString()) << endl;
    return 1;
    
  }else{
  standard_out << QObject::tr("Serial is open.") << endl;
  }
  
  SerialSelected->setRequestToSend(true);
  SerialSelected->setRequestToSend(false);
  
  standard_out << QObject::tr("Serial is Configuration:") << endl
               << QObject::tr("Baud rate: ") <<   SerialSelected->baudRate()  << endl
	       << QObject::tr("DataBit: ") <<   SerialSelected->dataBits() << endl
	       << QObject::tr("Parity: ") << ( SerialSelected->parity() )<< endl
               << QObject::tr("Stop Bits: ") << ( SerialSelected->stopBits() )<< endl
	       << QObject::tr("FlowControl:  ") << ( SerialSelected->flowControl() )<< endl
	       
	       ;
  SerialSelected->setRequestToSend(true);
  SerialSelected->setRequestToSend(false);

         
  
  QThread::sleep(2);
  
  char buf[64];                                                                    
  qint64 leghtbuf=0;
  while( ( SerialSelected->waitForReadyRead(10000) ) ){
    
    if( SerialSelected->canReadLine() ){
      leghtbuf=SerialSelected->readLine(buf,sizeof(buf));
      standard_out << buf << endl;
      if( leghtbuf >= 8 ) break;
      
    }
    standard_out << QObject::tr("Waiting for sketchCode") << endl;

  }
  
  if( leghtbuf == 0 ){
   standard_out << QObject::tr("Error: %1").arg(SerialSelected->errorString() ) << endl
		<< QObject::tr(" No sketchCode :(") << endl;
   return 1;
  }else{
    standard_out << QObject::tr("SketchCode recived!") << endl
		 << QObject::tr(" Code: %1 ").arg(buf) << endl
 		 << QObject::tr("Is it correct[Y/n]?\n>>") << flush
 		 ;
  }
  QString tmp;
  tmp=standard_in.readLine();
  if(  tmp[0] == 'n' ) return 0;
  SerialSelected->write("~");
  SerialSelected->flush();
  SerialSelected->waitForReadyRead(1000);
  SerialSelected->readAll();

  standard_out << QObject::tr("HandShake Terminate.") << endl;
  
  
  
  QByteArray Data;
  QByteArray dataBuffer;
  QString nameFile;
  QFile LogMisure;
  char command=' ';
  bool exit=false;
  
  
  standard_out << QObject::tr("Controllo della Seriale:") << endl
		     << QObject::tr("\t[r] Campiona per 1000 volte e restiusce la seguente stringa:") << endl
		     << QObject::tr("\t\t dutyCicle:Mean:Sigma") << endl
		     << QObject::tr("\t[w] Modifica il duty Cicle") << endl
		     << QObject::tr("\t[a] Fa una scansione completa sul duty Cicle da 0 a 255\n")
		     << QObject::tr("\t\t eseguendo ogni volta la lettura( vedi [r] )")<< endl
		     << QObject::tr("\t[t] Acquisisce misure raw dal fotodiodo ad intervalli regolari\n"
				    "\t\trestituendo ad ogni misura la stringa:\n\t\t\tclock:rawMeasure#\n"
				    "\t\tdove il clock è il tempo trascorso tra l'ultimo reset e la \n"
				    "\t\tmisura rawMeasure, espresso in microsecondi\n" ) << flush
		     << QObject::tr("\t[h] restituisce questo OutPut") << endl
		     << QObject::tr("\t[s] Salva su File") << endl
		     << QObject::tr("\t[q] Salva  Esce") << endl
		     ;
  SerialSelected->write("w");
  SerialSelected->flush();
  SerialSelected->write("0");
  SerialSelected->flush();
  
  
  
  while(true){
    standard_out << ">>" << flush;
    standard_in >> command;
    switch(command){
      case 'r':
	SerialSelected->write("r");
	SerialSelected->flush();
	SerialSelected->clear();
	
	while( ( SerialSelected->waitForReadyRead(10000) ) ){
    
	  if( SerialSelected->canReadLine() ){
	   
	    dataBuffer = SerialSelected->readAll();
	    standard_out << dataBuffer << flush;
	    log_out << QObject::tr("[r]:\n") << dataBuffer << flush;
	    dataBuffer.clear();
	    break;
	  }
	}
	SerialSelected->clear();
	SerialSelected->readAll();

        break;
	
      case 'w':
	SerialSelected->write("w");
	SerialSelected->flush();
	standard_out << QObject::tr("Inserire il valore della duty Cicle\n>>") << flush;
	standard_in >> tmp;
	SerialSelected->write(tmp.toStdString().c_str());
	SerialSelected->flush();
	SerialSelected->readAll();
	break;
	
	
	
      case 'a':
        SerialSelected->write("a");
	SerialSelected->flush();
	SerialSelected->clear();

	Data.append("#").append(logTime.toString("ddMMyyyy hhmmss") ).append("\n");
	Data.append("#Scanning on dutyCicle\n#duty\tmean\tsigma\n");
	{
	  QByteArray tmp_data;
	  bool breakWhile=false;
	  while( ( SerialSelected->waitForReadyRead(-1) ) ){
	      tmp_data.clear();
	      tmp_data.append( SerialSelected->readAll() );

	      
	      if( tmp_data.contains('$') ){
		tmp_data.remove( tmp_data.indexOf('$'),1 );
		standard_out << "ora esco" << endl;

		breakWhile=true;
	      }
	      tmp_data.replace(':','\t');
	      tmp_data.replace('%','\n');
	      standard_out << tmp_data << flush;
	      Data.append(tmp_data);
	      
	      
	      if( breakWhile ) break;
	  }
	}
	SerialSelected->readAll();
	
	break;
	
      case 't':
	SerialSelected->write("t");
	SerialSelected->flush();
	SerialSelected->clear();
	
	Data.append("#").append(logTime.toString("ddMMyyyy hhmmss") ).append("\n");
	Data.append("#Acquire ");
	standard_out << QObject::tr("Inserire il numero di misure che si vuole fare\n>>") << flush;
	standard_in >> tmp;
	SerialSelected->write(tmp.toStdString().c_str());
	SerialSelected->flush();
	
	Data.append(" measure\n#time\tMeasure\n");
	{
	  QByteArray tmp_data;
	  bool breakWhile=false;
	  while( ( SerialSelected->waitForReadyRead(10000) ) ){
	      standard_out << "dentro la lettura" << endl;
	      tmp_data.clear();
	      tmp_data.append( SerialSelected->readAll() );
	      
	      if( tmp_data.contains('$') ){
		standard_out << "ora esco" << endl;
		breakWhile=true;
	      }
	      tmp_data.replace(':','\t');
	      tmp_data.replace('%','\n');
	      tmp_data.replace('$','\n');
	      Data.append(tmp_data);
	      if( breakWhile ) break;
	  }
	}
	SerialSelected->readAll();
	break;
      case 's':
	save:
	if ( Data.isEmpty() ){
	  standard_out << QObject::tr("Nothing to save") << endl;
	  break;
	}
	standard_out << QObject::tr("Nome del file: ") << flush;
	
	standard_in >> nameFile;
	LogMisure.setFileName(nameFile);
	LogMisure.open(QIODevice::WriteOnly|QIODevice::Append);
	log_out << QObject::tr("Saving data in %1/ \b%2").arg( QDir::currentPath() ).arg( LogMisure.fileName() )  << endl;

	
	
	file_out.setDevice(&LogMisure);

	
	file_out << Data << flush;
	file_out.device()->close();
	Data.clear();
	break;
	
	
      case 'q':
	SerialSelected->write("q");
	SerialSelected->flush();
	SerialSelected->clear();

	exit=true;
	goto save;
	
	break;
	
      case 'h':
	standard_out << QObject::tr("Controllo della Seriale:") << endl
		     << QObject::tr("\t[r] Campiona per 1000 volte e restiusce la seguente stringa:") << endl
		     << QObject::tr("\t\t dutyCicle:Mean:Sigma") << endl
		     << QObject::tr("\t[w] Modifica il duty Cicle") << endl
		     << QObject::tr("\t[a] Fa una scansione completa sul duty Cicle da 0 a 255\n")
		     << QObject::tr("\t\teseguendo ogni volta la lettura( vedi [r] )")<< endl
		     << QObject::tr("\t[h] restituisce questo OutPut") << endl
		     << QObject::tr("\t[t] Acquisisce misure raw dal fotodiodo ad intervalli regolari\n"
				    "\t\trestituendo ad ogni misura la stringa:\n\t\t\tclock:rawMeasure#\n"
				    "\t\tdove il clock è il tempo trascorso tra l'ultimo reset e la \n"
				    "\t\tmisura raw Measure, espresso in microsecondi\n" ) << flush
		     << QObject::tr("\t[s] Salva su File") << endl
		     << QObject::tr("\t[q] Salva  Esce") << endl
		     ;
	break;
      default:
	if(exit) break;
    }
    if(exit) break;
    
    
  }
  return 0;
}
Esempio n. 29
0
void Vivaldi::Run() {
  assert(dir_client_.get() != NULL);
  assert(osd_client_.get() != NULL);

  // Initialized to (0,0) by default
  my_vivaldi_coordinates_.set_local_error(0.0);
  my_vivaldi_coordinates_.set_x_coordinate(0.0);
  my_vivaldi_coordinates_.set_y_coordinate(0.0);

  ifstream vivaldi_coordinates_file(vivaldi_options_.vivaldi_filename.c_str());
  if (vivaldi_coordinates_file.is_open()) {
    my_vivaldi_coordinates_.ParseFromIstream(&vivaldi_coordinates_file);
    if (!my_vivaldi_coordinates_.IsInitialized()) {
        Logging::log->getLog(LEVEL_ERROR)
            << "Vivaldi: Could not load coordinates from file: "
            << my_vivaldi_coordinates_.InitializationErrorString() << endl;
      my_vivaldi_coordinates_.Clear();
    }
  } else {
    if (Logging::log->loggingActive(LEVEL_INFO)) {
      Logging::log->getLog(LEVEL_INFO)
          << "Vivaldi: Coordinates file does not exist,"
          << "starting with empty coordinates." << endl
          << "Initialization might take some time." << endl;
    }
  }
  vivaldi_coordinates_file.close();

  VivaldiNode own_node(my_vivaldi_coordinates_);

  uint64_t vivaldi_iterations = 0;

  list<KnownOSD> known_osds;
  bool valid_known_osds = false;

  vector<uint64_t> current_retries;
  int retries_in_a_row = 0;
  list<KnownOSD>::iterator chosen_osd_service;
  ZipfGenerator rank_generator(vivaldi_options_.vivaldi_zipf_generator_skew);

  for (;;) {
    boost::scoped_ptr<rpc::SyncCallbackBase> ping_response;
    try {
      // Get a list of OSDs from the DIR(s)
      if ((vivaldi_iterations %
               vivaldi_options_.vivaldi_max_iterations_before_updating) == 0) {
        valid_known_osds = UpdateKnownOSDs(&known_osds, own_node);
        if (valid_known_osds && !known_osds.empty()) {
          rank_generator.set_size(known_osds.size());
        }
        // The pending retries are discarded, because the old OSDs might not
        // be in the new list
        current_retries.clear();

        retries_in_a_row = 0;
        chosen_osd_service = known_osds.begin();
      }

      // There are known OSDs, ping one of them.
      if (valid_known_osds && !known_osds.empty()) {
        // Choose an OSD, only if there's no pending retry
        if (retries_in_a_row == 0) {
          int index = rank_generator.next();

          list<KnownOSD>::iterator known_iterator = known_osds.begin();
          for (int i = 0;
               (i < index) && (known_iterator != known_osds.end());
               known_iterator++, i++) {
            // Move the iterator over the chosen service
          }
          chosen_osd_service = known_iterator;
        }

        // Ping chosen OSD.
        xtreemfs_pingMesssage ping_message;
        ping_message.set_request_response(true);
        ping_message.mutable_coordinates()
            ->MergeFrom(*own_node.GetCoordinates());

        VivaldiCoordinates* random_osd_vivaldi_coordinates;

        if (Logging::log->loggingActive(LEVEL_DEBUG)) {
          Logging::log->getLog(LEVEL_DEBUG)
              << "Vivaldi: recalculating against: "
              << chosen_osd_service->GetUUID() << endl;
        }

        SimpleUUIDIterator pinged_osd;
        pinged_osd.AddUUID(chosen_osd_service->GetUUID());

        // start timing
        boost::posix_time::ptime start_time(boost::posix_time
            ::microsec_clock::local_time());

        // execute sync ping
        ping_response.reset(
            ExecuteSyncRequest(
                boost::bind(
                    &xtreemfs::pbrpc::OSDServiceClient::xtreemfs_ping_sync,
                    osd_client_.get(),
                    _1,
                    boost::cref(auth_bogus_),
                    boost::cref(user_credentials_bogus_),
                    &ping_message),
                &pinged_osd,
                uuid_resolver_,
                RPCOptionsFromOptions(vivaldi_options_)));

        // stop timing
        boost::posix_time::ptime end_time(
            boost::posix_time::microsec_clock::local_time());
        boost::posix_time::time_duration rtt = end_time - start_time;
        uint64_t measured_rtt = rtt.total_milliseconds();

        xtreemfs::pbrpc::xtreemfs_pingMesssage* ping_response_obj =
            static_cast<xtreemfs::pbrpc::xtreemfs_pingMesssage*>(
            ping_response->response());
        random_osd_vivaldi_coordinates = ping_response_obj->mutable_coordinates();

        if (Logging::log->loggingActive(LEVEL_DEBUG)) {
          Logging::log->getLog(LEVEL_DEBUG)
              << "Vivaldi: ping response received. Measured time: "
              << measured_rtt << " ms" << endl;
        }

        // Recalculate coordinates here
        if (retries_in_a_row < vivaldi_options_.vivaldi_max_request_retries) {
          if (!own_node.RecalculatePosition(*random_osd_vivaldi_coordinates,
                                            measured_rtt,
                                            false)) {
            // The movement has been postponed because the measured RTT
            // seems to be a peak
            current_retries.push_back(measured_rtt);
            retries_in_a_row++;
          } else {
            // The movement has been accepted
            current_retries.clear();
            retries_in_a_row = 0;
          }
        } else {
          // Choose the lowest RTT
          uint64_t lowest_rtt = measured_rtt;
          for (vector<uint64_t>::iterator retries_iterator =
                   current_retries.begin();
              retries_iterator < current_retries.end();
              ++retries_iterator) {
            if (*retries_iterator < lowest_rtt) {
              lowest_rtt = *retries_iterator;
            }
          }

          // Force recalculation after too many retries
          own_node.RecalculatePosition(*random_osd_vivaldi_coordinates,
                                       lowest_rtt,
                                       true);
          current_retries.clear();
          retries_in_a_row = 0;

          // set measured_rtt to the actually used one for trace output
          measured_rtt = lowest_rtt;
        }

        // update local coordinate copy here
        {
          boost::mutex::scoped_lock lock(coordinate_mutex_);
          my_vivaldi_coordinates_.CopyFrom(*own_node.GetCoordinates());
        }

        // Store the new coordinates in a local file
        if (Logging::log->loggingActive(LEVEL_DEBUG)) {
          Logging::log->getLog(LEVEL_DEBUG)
              << "Vivaldi: storing coordinates to file: ("
              << own_node.GetCoordinates()->x_coordinate() << ", "
              << own_node.GetCoordinates()->y_coordinate() << ")" << endl;
        }
        ofstream file_out(vivaldi_options_.vivaldi_filename.c_str(),
            ios_base::binary | ios_base::trunc);
        own_node.GetCoordinates()->SerializePartialToOstream(&file_out);
        file_out.close();

        // Update client coordinates at the DIR
        if (vivaldi_options_.vivaldi_enable_dir_updates) {
          if (Logging::log->loggingActive(LEVEL_DEBUG)) {
            Logging::log->getLog(LEVEL_DEBUG)
                << "Vivaldi: Sending coordinates to DIR." << endl;
          }
          boost::scoped_ptr<rpc::SyncCallbackBase> response;
          try {
            response.reset(
                ExecuteSyncRequest(
                    boost::bind(
                        &xtreemfs::pbrpc::DIRServiceClient
                            ::xtreemfs_vivaldi_client_update_sync,
                        dir_client_.get(),
                        _1,
                        boost::cref(auth_bogus_),
                        boost::cref(user_credentials_bogus_),
                        own_node.GetCoordinates()),
                    dir_service_addresses_.get(),
                    NULL,
                    RPCOptionsFromOptions(vivaldi_options_),
                    true));
            response->DeleteBuffers();
          } catch (const XtreemFSException& e) {
            if (response.get()) {
              response->DeleteBuffers();
            }
            if (Logging::log->loggingActive(LEVEL_INFO)) {
              Logging::log->getLog(LEVEL_INFO)
                  << "Vivaldi: Failed to send the updated client"
                      " coordinates to the DIR, error: "
                  << e.what() << endl;
            }
          }
        }
//        //Print a trace
//        char auxStr[256];
//        SPRINTF_VIV(auxStr,
//                    256,
//                    "%s:%lld(Viv:%.3f) Own:(%.3f,%.3f) lE=%.3f "
//                        "Rem:(%.3f,%.3f) rE=%.3f %s\n",
//                    retried ? "RETRY" : "RTT",
//                    static_cast<long long int> (measured_rtt),
//                    own_node.calculateDistance(
//                        (*own_node.getCoordinates()),
//                        random_osd_vivaldi_coordinates.get()),
//                    own_node.getCoordinates()->x_coordinate(),
//                    own_node.getCoordinates()->y_coordinate(),
//                    own_node.getCoordinates()->local_error(),
//                    random_osd_vivaldi_coordinates->x_coordinate(),
//                    random_osd_vivaldi_coordinates->y_coordinate(),
//                    random_osd_vivaldi_coordinates->local_error(),
//                    chosen_osd_service->get_uuid().data());
//        get_log()->getStream(YIELD::platform::Log::LOG_INFO) <<
//            "Vivaldi: " << auxStr;

        // Update OSD's coordinates
        chosen_osd_service->SetCoordinates(*random_osd_vivaldi_coordinates);

        // Re-sort known_osds
        // TODO(mno): Use a more efficient sort approach.
        list<KnownOSD> aux_osd_list(known_osds);
        KnownOSD chosen_osd_service_value = *chosen_osd_service;
        known_osds.clear();  // NOTE: this invalidates all ptrs and itrs

        for (list<KnownOSD>::reverse_iterator aux_iterator
                 = aux_osd_list.rbegin();
             aux_iterator != aux_osd_list.rend();
             aux_iterator++) {
          double new_osd_distance =
              own_node.CalculateDistance(
                  *(aux_iterator->GetCoordinates()),
                  *own_node.GetCoordinates());

          list<KnownOSD>::iterator known_iterator = known_osds.begin();

          while (known_iterator != known_osds.end()) {
            double old_osd_distance =  \
                  own_node.CalculateDistance(
                      *(known_iterator->GetCoordinates()),
                      *own_node.GetCoordinates());
            if (old_osd_distance >= new_osd_distance) {
              known_osds.insert(known_iterator, (*aux_iterator));
              break;
            } else {
              known_iterator++;
            }
          }

          if (known_iterator == known_osds.end()) {
            known_osds.push_back((*aux_iterator));
          }
        }  // end re-sorting

        // find the chosen OSD in the resorted list
        chosen_osd_service = find(known_osds.begin(),
                                  known_osds.end(),
                                  chosen_osd_service_value);
        assert(chosen_osd_service != known_osds.end());
        ping_response->DeleteBuffers();
      } else {
          if (Logging::log->loggingActive(LEVEL_WARN)) {
            Logging::log->getLog(LEVEL_WARN)
                << "Vivaldi: no OSD available." << endl;
          }
      }

      vivaldi_iterations = (vivaldi_iterations + 1) % LONG_MAX;

      // Sleep until the next iteration
      uint32_t sleep_in_s = static_cast<uint32_t>(
          vivaldi_options_.vivaldi_recalculation_interval_s -
          vivaldi_options_.vivaldi_recalculation_epsilon_s +
          (static_cast<double>(rand()) / (RAND_MAX - 1)) *
           2.0 * vivaldi_options_.vivaldi_recalculation_epsilon_s);

      if (Logging::log->loggingActive(LEVEL_DEBUG)) {
        Logging::log->getLog(LEVEL_DEBUG)
            << "Vivaldi: sleeping during " << sleep_in_s << " s." << endl;
      }

      boost::this_thread::sleep(boost::posix_time::seconds(sleep_in_s));
    } catch (const XtreemFSException& e) {
      if (ping_response.get()) {
        ping_response->DeleteBuffers();
      }

      Logging::log->getLog(LEVEL_ERROR)
            << "Vivaldi: could not ping OSDs: " << e.what() << endl;

      // We must avoid to keep retrying indefinitely against an OSD which is not
      // responding
      if (retries_in_a_row > 0
          && (++retries_in_a_row >=
              vivaldi_options_.vivaldi_max_request_retries)) {
        // If the last retry times out all the previous retries are discarded
        current_retries.clear();
        retries_in_a_row = 0;
      }
    } catch(const boost::thread_interrupted&) {
      if (ping_response.get()) {
        ping_response->DeleteBuffers();
      }
      break;
    }
  }
}  // Run()
void riesgo_quirurgico_documento::generatelatex()
{
    ofstream file_out("riesgo_quirurgico.tex");
    file_out<<"\\documentclass[10pt,a4paper]{article}"<<endl;
    file_out<<"\\usepackage[spanish]{babel}"<<endl;
    file_out<<"\\usepackage{anysize}"<<endl;
    file_out<<"\\usepackage[latin1]{inputenc}"<<endl;
    file_out<<"\\usepackage{graphicx}"<<endl;
    file_out<<"\\usepackage[light,math]{iwona}"<<endl;
    file_out<<"\\usepackage[T1]{fontenc}"<<endl;
    file_out<<"\\marginsize{1cm}{0cm}{2.55cm}{0cm} "<<endl;
    file_out<<"\\pagestyle{empty} "<<endl;
    file_out<<"\\begin{document} "<<endl;


    file_out<<"\\begin{center}"<<endl;
    file_out<<"\\begin{large}"<<endl;
    file_out<<"\\textbf{RIESGO QUIRURGICO CARDIO VASCULAR}"<<endl;
    file_out<<"\\end{large}"<<endl;

    file_out<<"\\scalebox{1.40}[1.55]{"<<endl;
    file_out<<"\\begin{tabular}{|p{2.8cm}p{2.8cm}p{2.8cm}p{2.8cm}|} "<<endl;
    file_out<<"\\hline "<<endl<<endl;
    file_out<<"\\multicolumn{2}{|l}{\\begin{minipage}[t]{5.5 cm}\\scriptsize{NOMBRE: "<<name<<"}\\end{minipage}}&\\multicolumn{2}{l|}{\\begin{minipage}[t]{5.5 cm}\\scriptsize{EDAD: "<<age<<"}\\end{minipage}}\\\\"<<endl;
    file_out<<"\\hline"<<endl;
    file_out<<"\\multicolumn{2}{|l}{\\begin{minipage}[t]{5.5 cm}\\scriptsize{PROCEDENCIA: "<<procedencia<<"}\\end{minipage}}&\\multicolumn{2}{l|}{\\begin{minipage}[t]{5.5 cm}\\scriptsize{SEXO: "<<sexo<<"}\\end{minipage}}\\\\"<<endl;
    file_out<<"\\hline"<<endl;
    file_out<<"\\multicolumn{1}{l}{\\scriptsize{" << "" <<"}}&&& \\multicolumn{1}{l}{ \\scriptsize{"<<""<<"}}\\\\"<<endl;
    file_out<<"\\multicolumn{1}{l}{\\scriptsize{\\textbf{ANTECEDENTES:}" << "" <<"}}&&& \\multicolumn{1}{l}{ \\scriptsize{"<<""<<"}}\\\\"<<endl;
    file_out<<"\\hline "<<endl;
    file_out<<"\\multicolumn{4}{|l|}{\\begin{minipage}[t]{12.5 cm}\\scriptsize{HTM: "<<HTA<<"}\\end{minipage}}\\\\"<<endl;
    file_out<<"\\hline"<<endl;
    file_out<<"\\multicolumn{4}{|l|}{\\begin{minipage}[t]{12.5 cm}\\scriptsize{ASMA: "<<ASMA<<"}\\end{minipage}}\\\\"<<endl;
    file_out<<"\\hline"<<endl;
    file_out<<"\\multicolumn{4}{|l|}{\\begin{minipage}[t]{12.5 cm}\\scriptsize{TBC: "<<TBC<<"}\\end{minipage}}\\\\"<<endl;
    file_out<<"\\hline"<<endl;
    file_out<<"\\multicolumn{4}{|l|}{\\begin{minipage}[t]{12.5 cm}\\scriptsize{DM: "<<DM<<"}\\end{minipage}}\\\\"<<endl;
    file_out<<"\\hline"<<endl;
    file_out<<"\\multicolumn{4}{|l|}{\\begin{minipage}[t]{12.5 cm}\\scriptsize{Motivo del RQCV: "<<motivo_RQCV<<"}\\end{minipage}}\\\\"<<endl;
    file_out<<"\\hline"<<endl;
    file_out<<"\\multicolumn{1}{l}{\\scriptsize{" << "" <<"}}&&& \\multicolumn{1}{l}{ \\scriptsize{"<<""<<"}}\\\\"<<endl;
    file_out<<"\\multicolumn{1}{l}{\\scriptsize{\\textbf{EXAMEN CL\\'INICO: }" << "" <<"}}&&& \\multicolumn{1}{l}{ \\scriptsize{"<<""<<"}}\\\\"<<endl;
    file_out<<"\\hline "<<endl;
    file_out<<"\\multicolumn{2}{|l}{ \\scriptsize{P.A.: "<<PA<<"} } & \\multicolumn{2}{l|}{ \\scriptsize{F.C.: "<<FC<<"}} \\\\"<<endl;
    file_out<<"\\hline"<<endl;
    file_out<<"\\multicolumn{4}{|l|}{\\begin{minipage}[t]{12.5 cm}\\scriptsize{Coraz\\'on: "<<corazon<<"}\\end{minipage}}\\\\"<<endl;
    file_out<<"\\hline"<<endl;
    file_out<<"\\multicolumn{4}{|l|}{\\begin{minipage}[t]{12.5 cm}\\scriptsize{PULMONES: "<<pulmones<<"}\\end{minipage}}\\\\"<<endl;
    file_out<<"\\hline"<<endl;
    file_out<<"\\multicolumn{4}{|l|}{\\begin{minipage}[t]{12.5 cm}\\scriptsize{PULSOS PERIF\\'ERICOS: "<<pulso_periferico<<"}\\end{minipage}}\\\\"<<endl;
    file_out<<"\\hline"<<endl;
    file_out<<"\\multicolumn{4}{|l|}{\\begin{minipage}[t]{12.5 cm}\\scriptsize{SISTEMA VENOSO: "<<sistema_venoso<<"}\\end{minipage}}\\\\"<<endl;
    file_out<<"\\hline"<<endl;
    file_out<<"\\multicolumn{2}{|l}{\\begin{minipage}[t]{5.5 cm}\\scriptsize{E.K.G.: "<<EKG<<"}\\end{minipage}}&\\multicolumn{2}{l|}{\\begin{minipage}[t]{5.5 cm}\\scriptsize{F.C.: "<<FC1<<"}\\end{minipage}}\\\\"<<endl;
    file_out<<"\\hline"<<endl;
    file_out<<"\\scriptsize{P:" << P <<"}&\\scriptsize{PR:" << PR <<"}&\\scriptsize{QRS:" << QRC <<"}&\\scriptsize{QT:"<<QT<<"}\\\\"<<endl;
    file_out<<"\\hline "<<endl;
    file_out<<"\\multicolumn{4}{|l|}{\\begin{minipage}[t]{12.5 cm}\\scriptsize{S.T.: "<<ST<<"}\\end{minipage}}\\\\"<<endl;
    file_out<<"\\hline"<<endl;
    file_out<<"\\multicolumn{4}{|l|}{\\begin{minipage}[t]{12.5 cm}\\scriptsize{ONDA T: "<<onda_T<<"}\\end{minipage}}\\\\"<<endl;
    file_out<<"\\hline"<<endl;
    file_out<<"\\multicolumn{4}{|l|}{\\begin{minipage}[t]{12.5 cm}\\scriptsize{AQRC: "<<AQRS<<"}\\end{minipage}}\\\\"<<endl;
    file_out<<"\\hline "<<endl;
    file_out<<"\\multicolumn{4}{|l|}{\\begin{minipage}[t]{12.5 cm}\\scriptsize{ID: "<<ID<<"}\\end{minipage}}\\\\"<<endl;
    file_out<<"\\hline "<<endl;
    file_out<<"\\multicolumn{4}{|l|}{\\begin{minipage}[t]{12.5 cm}\\scriptsize{R.Q.C.V.: "<<RQCV<<"}\\end{minipage}}\\\\"<<endl;
    file_out<<"\\hline "<<endl;
    file_out<<"\\multicolumn{4}{|l|}{\\begin{minipage}[t]{12.5 cm}\\scriptsize{SUGERENCIAS: "<<sugerencias<<"}\\end{minipage}}\\\\"<<endl;
    file_out<<"\\hline "<<endl;
    file_out<<"\\multicolumn{1}{l}{\\scriptsize{" << "" <<"}}&&& \\multicolumn{1}{l}{ \\scriptsize{"<<""<<"}}\\\\"<<endl;
    file_out<<"\\multicolumn{1}{l}{\\scriptsize{" << "" <<"}}&&& \\multicolumn{1}{l}{ \\scriptsize{"<<""<<"}}\\\\"<<endl;
    file_out<<"\\multicolumn{2}{l}{\\begin{minipage}[t]{5.5 cm}\\scriptsize{\\textbf{FECHA: }"<<date<<"}\\end{minipage}}&\\multicolumn{2}{l}{\\begin{minipage}[t]{5.5 cm}\\scriptsize{\\textbf{FIRMA: }"<<medic<<"}\\end{minipage}}\\\\"<<endl;
    file_out<<"\\end{tabular}}"<<endl<<endl;
    file_out<<"\\end{center}"<<endl;
    file_out<<"\\vspace{0.6cm}"<<endl;
    file_out<<"\\hspace{13cm}"<<endl;
    file_out<<"\\end{document}"<<endl;
    file_out.close();
    system("pdflatex riesgo_quirurgico.tex > pdfCompiling.txt & start riesgo_quirurgico.pdf");
}