Beispiel #1
0
bool StreamerSDL::saveBitmap(const Bitmap & bitmap, std::ostream & output) {
	if(bitmap.getPixelFormat() == PixelFormat::MONO_FLOAT) {
		Reference<Bitmap> tmp = BitmapUtils::convertBitmap(bitmap, PixelFormat::MONO);
		return saveBitmap(*tmp.get(), output);
	}
	SDL_Surface * surface = BitmapUtils::createSDLSurfaceFromBitmap(bitmap);
	if (surface == nullptr) {
		return false;
	}
	// Save the bitmap to a file temporarily.
	static TemporaryDirectory tempDir("StreamerSDL");

	FileName fileName(tempDir.getPath());
	do {
		fileName.setFile(StringUtils::createRandomString(16) + ".bmp");
	} while(FileUtils::isFile(fileName));

	int success = SDL_SaveBMP(surface, fileName.getPath().c_str());
	SDL_FreeSurface(surface);
	if(success != 0) {
		FileUtils::remove(fileName);
		return false;
	}

	std::ifstream fileInput(fileName.getPath().c_str(), std::ios_base::binary);
	output << fileInput.rdbuf();
	fileInput.close();

	FileUtils::remove(fileName);

	return true;
}
Beispiel #2
0
//Read in info from text file, add them to vector
void loadHeroes(string filename, vector<Hero*> &heroes)
{
	heroes.clear();
	string line = "";
	std::ifstream fileInput(filename);
	while (getline(fileInput, line))
	{
		heroes.push_back(new Hero(line));
	}
}
Beispiel #3
0
string SGFileBefore::readStringFromFile(const char* fileName)
{
	ifstream fileInput(fileName);
	if (!fileInput.good())
	{
		printf("File failed to load...\"%s\"\n", fileName);
		//while (1);
	}
	string returnTarget = string(istreambuf_iterator<char>(fileInput),
		istreambuf_iterator<char>());

	return returnTarget;
}
Beispiel #4
0
int main(int argc, char *argv[]) {
	char board[41][41] = {{'\0', '\0'}};
	char tempBoard[41][41] = {{'\0', '\0'}};

	if(argc == 1) { // if no other file in command line
		blankBoard(board, tempBoard);
		printBoard(board);
		while(userInput(board, tempBoard));
	}
	else { // if file in command line
		fileInput(argv[1], board, tempBoard);
	}

	return 0;
}
Beispiel #5
0
string genFileSHA1AndLen(
        const string &filePath,
        uint64_t *fileLen = NULL) {

    static char hexBytes[16] = {
    '0', '1', '2', '3', '4', '5', '6', '7', '8',
    '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    unsigned char sha1[SHA_DIGEST_LENGTH];
    ifstream fileInput(filePath.c_str(),
            ios::in | ios::binary);
    if (!fileInput) {
        return "";
    }

    if (fileLen != NULL) {
        fileInput.seekg(0 , std::ios::end);
        *fileLen = fileInput.tellg();
        fileInput.seekg(0 , std::ios::beg);
    }

    const int sliceSize = 2*1024*1024;
    char buf[sliceSize];
    SHA_CTX ctx;
    SHA1_Init(&ctx);

    uint64_t len = 0;
    while(!fileInput.eof()) {
        fileInput.read(buf, sliceSize);
        len = fileInput.gcount();
        SHA1_Update(
                &ctx, buf, len);
    }

    SHA1_Final(sha1, &ctx);

    fileInput.close();

    string shaStr = "";
    for (int i=0; i<SHA_DIGEST_LENGTH; i++) {
        shaStr += hexBytes[sha1[i] >> 4];
        shaStr += hexBytes[sha1[i] & 0x0f];
    }

    return shaStr;
}
Beispiel #6
0
void SGFileBefore::readMeshFile( const char* fileName, SGDagNodeContainer& container )
{
	ifstream fileInput(fileName, ios::binary);
	if (!fileInput.good())
	{
		printf("File failed to load...\"%s\"\n", fileName);
		return;
	}

	short sizeofInt    = sizeof(int);
	short sizeofDouble = sizeof(double);

	int numDataMesh;
	fileInput.read((char*)&numDataMesh, sizeofInt);

	for (int i = 0; i < numDataMesh; i++ )
	{
		SGDagNodeMesh* ptrDagNodeMesh = new SGDagNodeMesh;
		SGDagNodeMesh& meshData = *ptrDagNodeMesh;
		fileInput.read((char*)&meshData.m_numVertices, sizeofInt);
		fileInput.read((char*)&meshData.m_numPolygons, sizeofInt);
		fileInput.read((char*)&meshData.m_numIdArrayVertices, sizeofInt);
		fileInput.read((char*)&meshData.m_numUVs, sizeofInt);
		meshData.m_uvArrays = new vector<vector2d>[meshData.m_numUVs];
		for (int i = 0; i < meshData.m_numUVs; i++)
			meshData.m_uvArrays[i].resize(0);

		meshData.m_points.resize(meshData.m_numVertices);
		meshData.m_countArrayVertices.resize(meshData.m_numPolygons);
		meshData.m_idArrayVertices.resize(meshData.m_numIdArrayVertices);

		fileInput.read((char*)&meshData.m_matrix[0], sizeofDouble *16 );
		fileInput.read((char*)&meshData.m_points[0], sizeofDouble*meshData.m_numVertices * 3);
		fileInput.read((char*)&meshData.m_countArrayVertices[0], sizeofInt*meshData.m_numPolygons);
		fileInput.read((char*)&meshData.m_idArrayVertices[0], sizeofInt*meshData.m_numIdArrayVertices);

		meshData.updateBoundingBox();
		meshData.setDatasComopnentRelationship();
		meshData.setVertexNormals();
		meshData.setBuffer();

		container.append(ptrDagNodeMesh);
	}
	fileInput.close();
}
bool read_text_archive( const std::string& file_name,
    T& data_structure){

  int fileDescriptor = open(file_name.c_str(), O_RDONLY);
  if( fileDescriptor < 0 ) {
    LOG(INFO) << " Error opening the file "<< file_name;
    return false;
  }

  google::protobuf::io::FileInputStream fileInput(fileDescriptor);
  fileInput.SetCloseOnDelete( true );
  if(google::protobuf::TextFormat::Parse(&fileInput, &data_structure)) {
    return true;
  }else{
    LOG(INFO) << "Failed to parse file: " << file_name;
    return false;
  }
}
Beispiel #8
0
int main(int argc, const char * argv[]) {
    bool startRepl = false;
    
    if (argc == 1) {
        startRepl = true;
    }
    
    // execute any files passed on the command line
    int argpos = 1;
    while (argpos < argc) {
        std::string filename(argv[argpos]);
        
        if (filename=="-h") {
            std::cout << "help: -h prints this message, -r starts the repl, pass any files to execute" << std::endl;
            startRepl = false;
        } else if (filename=="-r") {
            // guarantee that the repl starts
            startRepl = true;
        }
        
        std::ifstream t(filename);
        std::string fileInput((std::istreambuf_iterator<char>(t)),std::istreambuf_iterator<char>());
        
        try {
            tinyclojure::TinyClojure interpreter;
            std::vector<tinyclojure::Object*> expressions;
            interpreter.parseAll(fileInput, expressions);
            
            for (int expressionIndex = 0; expressionIndex < expressions.size(); ++expressionIndex) {
                interpreter.eval(expressions[expressionIndex])->stringRepresentation();
            }            
        } catch (tinyclojure::Error error) {
            std::cout << error.position << ": " << error.message << std::endl << std::endl;
        }
        
        ++argpos;
    }
    
    if (startRepl) {
        repl();
    }
    
    return 0;
}
int main_FileCopy ()
{
	std::ifstream fileInput("RepeatArray.cpp",std::ios::binary);
	std::ofstream fileOutput("testing.txt",std::ios::binary);
	char line[10]={};
	
    int filesize;
    struct stat  results;
    
    if (stat("RepeatArray.cpp", &results) == 0)
	{ 
       filesize= results.st_size;
	}
    else
	{ 
		printf("Error\n"); 
	}

	printf("size of file %d\n",filesize);
	
	const int chunk=10;
	
	int size = filesize;
	while(size>chunk)
	{
	
	fileInput.read(line,chunk);	
	fileOutput.write(line,chunk) ;	
	size =size-chunk;
	}

	fileInput.read(line,size);		
	fileOutput.write(line,size);

	fileInput.close();
	fileOutput.close();
  return 0;
}
int main() {
    // faili lugemine
    FILE *inputFile = fopen(I_FILENAME, "r");
    
    if (inputFile == NULL) {
        printf("Faili avamine ebaõnnestus\n");
        return 0;
    }
    
    int lines = countlines(inputFile) - 1; // loeme read üle, selleks et teada massiivi suurust
    if (DEBUG) printf("Ridade arv: %d\n", lines);
       
    Isik vanemad[lines]; // loeme sisendfailist
    Isik llvanemad[lines]; // lastelastega vanemad
    
    rewind(inputFile); // resetib faili pointer tagasi algusesse. Alternatiiv oleks fail uuesti avada.
    fileInput(inputFile, vanemad);
    fclose(inputFile);

    // väljastame testimiseks
    if (DEBUG) {
       printf("\nLapsed:\n");
       printEntries(vanemad, lines);
    }
    // leiame lapselapsed
    findGrandChildren(vanemad, llvanemad, lines);
    
    // väljastame testimiseks
    if (DEBUG) {
       printf("\n=====================\n");
       printf("\nLapselapsed:\n");
       printEntries(llvanemad, lines);
    }
    
    // TODO: faili kirjutamine
    
    return 0;
}
Beispiel #11
0
int main()
{
    int fLines, start =2, i;
   char *fName = "worldcitiespoppartial.txt";
   float **fpArray;
    int childpid, fds[2];
    fpArray = fileInput(fName, &fLines);

    printf("Before it forks\n");
    pipe(fds);
    childpid = fork();

    if (childpid==0){
        printf("This is a child Process\n");
        fpArray = iSort(fpArray, (fLines/2), start);
        write(fds[1], fpArray, sizeof(long int)*3*fLines/2  );


    }
    else {
        printf("This is a parent Process\n");
        wait(NULL);
        read(fds[0], fpArray, sizeof(long int)*3*fLines/2);

        fpArray = iSort(fpArray, (fLines), (fLines/2));



    fpArray = mSort(fpArray, fLines);
    for(i=1;i<fLines; i++){
        printf("%.f %f %f\n", fpArray[i][0], fpArray[i][1], fpArray[i][2]);
    }


    }
   return(0);
}
Beispiel #12
0
void LevelManager::loadGame(){

	ifstream fileInput(FILENAME);
	string input;



	while (!fileInput.eof()){
		fileInput >> input;

		if (input == LEVEL){
			fileInput >> input;
			loadedLevel = stoi(input);
			if (loadedLevel > mLevelProgression){
				mLevelProgression = loadedLevel;
			}
		}
		if (input == COLLECT){
			fileInput >> input;
			loadedCollectibles = stoi(input);
			if (loadedCollectibles > mLevelProgression){
				mCollectibles = loadedCollectibles;
			}
		}
Beispiel #13
0
void LoggingWindow::on_loadBackupButton_clicked()
{
    QString path = QDir::currentPath();
    if (backupFolder != "") { path = backupFolder; }
    QString fileToOpen = QFileDialog::getOpenFileName(this,
                                                      "Open Backup",
                                                      path,
                                                      tr("Backup File (*.backup)"));
    if (fileToOpen != "") {
        QFile backupFile(fileToOpen);
        QTextStream fileInput(&backupFile);

        if (backupFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
            while (!fileInput.atEnd()) {
                qDebug() << "Loading line of Backup File";
                QString line = fileInput.readLine();
                data[dataPointer] = new DataPoint(this);
                data[dataPointer]->addBackupData(line);
                emit updateGraphs(data[dataPointer]);

                this->addToTable(data[dataPointer]->className(),
                                 data[dataPointer]->airQuality(),
                                 data[dataPointer]->deltaAirQuality(),
                                 data[dataPointer]->year(),
                                 data[dataPointer]->boys(),
                                 data[dataPointer]->girls(),
                                 data[dataPointer]->timeOfLog());
                lastValue = data[dataPointer]->airQuality();
                dataPointer++;


            }
        }
    }

}
//*********************************************************************************
// Start of main function 
// parameters: 
//  * filename         - name of the input-file
//*********************************************************************************
void BuildRAAStudents(TString filename = "RAABaseOutput.root"){

  //________Reset ROOT_______________________________________________________________
  gROOT->Reset();
	
  //________Set basic style setting__________________________________________________
  StyleSettings();				
  cout << "Analysing file " <<  filename.Data() << endl;
  
  //*********************************************************************************
  //Definition of number of Collisions in the different centrality classes
  //*********************************************************************************   
  Double_t nColl_0_5 =1686.87;	
  Double_t nColl_0_10 = 1502.7;
  Double_t nColl_5_10 = 1319.89;
  Double_t nColl_10_20 = 923.26;
  Double_t nColl_20_30 = 558.68;
  Double_t nColl_30_40 = 321.20;
  Double_t nColl_40_50 = 171.67;
  Double_t nColl_50_60 = 85.13;
  Double_t nColl_60_70 = 38.51;
  Double_t nColl_70_80 = 15.78;
  Double_t nColl_80_90 = 6.32;
	
  //*********************************************************************************
  //Attaching & reading the input-file
  //*********************************************************************************   
  TFile fileInput(filename.Data());  
  //____ reading the number of TPC tracks for pp events & 0-5% PbPb events___________
  TH1D *hNTracksTPCPbPb_0_5 =			(TH1D*)fileInput.Get(Form("nTracksTPC_PbPb_%i-%i",0,5));
  TH1D *hNTracksTPCPbPb_70_80 =			(TH1D*)fileInput.Get(Form("nTracksTPC_PbPb_%i-%i",70,80));
  /// To do: Do the same for the other centralities 
  
  //_____reading the pt-spectrum for 0-5% & 70-80% PbPb events, scaling it___________
  //_____by corresponding number of Collisions (nColl)_______________________________
  TH1D *hTrackPtPbPb_0_5 =			(TH1D*)fileInput.Get(Form("trackPt_PbPb_%i-%i",0,5));
  hTrackPtPbPb_0_5->Scale(1./nColl_0_5);
  TH1D *hTrackPtPbPb_70_80 =			(TH1D*)fileInput.Get(Form("trackPt_PbPb_%i-%i",70,80));
  hTrackPtPbPb_70_80->Scale(1./nColl_70_80);
  /// To do: Do the same for the other centralities 
  
  //*********************************************************************************
  // Attaching and Reading pp-reference file
  //*********************************************************************************   
  TFile *fileInputPP   = new TFile("PP_2760GeV_BaseLine.root");
  TH1F  *hNTracksTPCpp = (TH1F*)fileInputPP->Get("nTracksTPC_pp");	
  TH1D  *hTrackPtpp    = (TH1D*)fileInputPP->Get("trackPt_pp");	
  
  //*********************************************************************************
  // Building the RCP
  //*********************************************************************************
  TH1D*	hRCP_0_5 = (TH1D*)hTrackPtPbPb_0_5->Clone("RCP_vs_Pt_0-5");
  hRCP_0_5->Sumw2();
  hRCP_0_5->Divide(hTrackPtPbPb_70_80);
  /// To do: Do the same for the other centralities 
  
  //*********************************************************************************
  // Building the RAA
  //*********************************************************************************   
  
  /// To Do: Here you need to add the histograms for RAA (PbPb-pt-spectrum in a certain centrality, scaled by NColl,  devided by the pp reference spectrum
	
	
	
	
  //*********************************************************************************
  //Definition of canvas
  //*********************************************************************************
  TCanvas *c1 = new TCanvas("c1","Pt");
  TCanvas *c2 = new TCanvas("c2","nTracksTPC");
  TCanvas *c3 = new TCanvas("c3","RCP");
  TCanvas *c4 = new TCanvas("c4","RAA");
  
  //*********************************************************************************
  // * Plotting the track pt for 0-5, 70-80 PbPb events and pp events
  //*********************************************************************************	
  c1->cd(); 
  c1->SetLogy(1);
  hTrackPtpp->GetYaxis()->SetTitleOffset(1.3);
  HistoSetMarkerAndColor( hTrackPtpp, 20,0.8, kRed, kRed); 
  hTrackPtpp->Draw("e1");
  
  HistoSetMarkerAndColor( hTrackPtPbPb_0_5, 20,0.8, kBlue+2, kBlue+2); 
  hTrackPtPbPb_0_5->Draw("same,e1");
  HistoSetMarkerAndColor( hTrackPtPbPb_70_80, 20,0.8, kMagenta+2, kMagenta+2); 
  hTrackPtPbPb_70_80->Draw("same,e1");
  /// To do: Add different centralities to this plot and the legend
  
  TLegend* legendTrackPt = new TLegend(0.55,0.70,0.95,0.9);
  legendTrackPt->SetTextSize(0.03);			
  legendTrackPt->SetFillColor(0);
  legendTrackPt->SetLineColor(0);
  legendTrackPt->SetNColumns(2);
  legendTrackPt->AddEntry(hTrackPtPbPb_0_5,"PbPb 0-5 %");
  legendTrackPt->AddEntry(hTrackPtPbPb_70_80,"PbPb 70-80 %");
  legendTrackPt->AddEntry(hTrackPtpp,"pp");
  legendTrackPt->Draw();

  c1->SaveAs("trackPt_compared.eps");	
	
   
  //*********************************************************************************
  // * Plotting of the multiplicity histogram for 0-5%, 70-80% PbPb & pp
  //*********************************************************************************
			
  c2->cd(); 
  c2->SetLogy(1);
  hNTracksTPCpp->GetYaxis()->SetRangeUser(5.e-6,1.);
  hNTracksTPCpp->GetYaxis()->SetTitleOffset(1.3);
  HistoSetMarkerAndColor( hNTracksTPCpp, 20,0.8, kRed, kRed); 
  hNTracksTPCpp->Draw("e1");
  HistoSetMarkerAndColor( hNTracksTPCPbPb_0_5, 20,0.8, kBlue+2, kBlue+2); 
  hNTracksTPCPbPb_0_5->Draw("same,e1");
  HistoSetMarkerAndColor( hNTracksTPCPbPb_70_80, 20,0.8, kMagenta+2, kMagenta+2); 
  hNTracksTPCPbPb_70_80->Draw("same,e1");	
  /// To do: Add different centralities to this plot and the legend
	
  legendTrackPt->Draw();
  c2->Update();
  c2->SaveAs("nTracksTPC_compared.eps");	
			
  //**********************************************************************************
  // Axis labeling & plotting of the RCP for 0-5% 
  //**********************************************************************************
  c3->cd(); 
  c3->SetLogy(0);
  hRCP_0_5->SetTitle("R_{CP} for different centralities");
  hRCP_0_5->SetXTitle("p_{t} (GeV/c)");
  hRCP_0_5->SetYTitle("R_{CP} = #frac{1/N^{AA,X}_{evt} 1/<N_{coll,X}> dN^{AA,X}/dp_{t}}{1/N^{PbPb,per}_{evt} 1/<N_{coll,per}> dN^{PbPb,per}/dp_{t}}");
  hRCP_0_5->GetYaxis()->SetTitleOffset(1.3);
  hRCP_0_5->GetYaxis()->SetRangeUser(0.,1.5);
	
  HistoSetMarkerAndColor( hRCP_0_5, 20,0.8, kBlue+2, kBlue+2); 
  hRCP_0_5->Draw("e1");
  /// To do: Add different centralities to this plot and the legend
	
  TLegend* legendRCP = new TLegend(0.15,0.78,0.55,0.9);
  legendRCP->SetTextSize(0.03);			
  legendRCP->SetFillColor(0);
  legendRCP->SetLineColor(0);
  legendRCP->SetNColumns(4);
  legendRCP->AddEntry(hRCP_0_5,"0-5 %");
  legendRCP->Draw();

  c3->Update();
  c3->SaveAs("RCP_compared.eps");	
	
   
  //**********************************************************************************
  // Axis labeling & plotting of the RAA in the different classes
  //**********************************************************************************
  /// To do: Plot RAA in the different centrality classes, use RCP plot as an example
	
	
}
Beispiel #15
0
int main()
{


	std::ifstream fileInput("testData.txt");
	std::size_t numLines = 0;
        std::string line;
	while ( std::getline(fileInput,line) )
	{
		numLines++;
	}
	fileInput.clear();
	fileInput.seekg(0,fileInput.beg);
        std::vector<std::vector<double> > dataVec(numLines, std::vector<double> (8, 0));
        int lineNum = 0;
	double startingTime;

        while( std::getline(fileInput, line))
        {
                std::istringstream iss(line);
                for (int i = 0; i < 8; i++)
                {
                        iss >> dataVec[lineNum][i];
                }
		if ( lineNum == 0 )
		{
			startingTime = dataVec[0][0];
		}
		dataVec[lineNum][0] -= startingTime;
                lineNum++;
        }


	double diff = (dataVec[numLines-1][0] - dataVec[0][0])/(numLines);

        typedef std::chrono::high_resolution_clock Clock;
        typedef std::chrono::duration<double> secDouble;
        
        std::chrono::high_resolution_clock timer;
        
        Clock::time_point startTime = timer.now();
        secDouble secs;
	int timeIndex = 0;
	int prevValue = 0;

	std::vector<double> angles;
	angles.resize(6);
	while( true )
	{
		secs = timer.now() - startTime;
		timeIndex =  std::round( secs.count() / diff );
		if (timeIndex != prevValue)
		{

			angles.assign(dataVec[timeIndex].begin() + 1, dataVec[timeIndex].end() - 1);
			
			std::cout << '\r';
			for ( int i = 0; i < 6; i++)
			{
				std::cout << angles[i] << ", ";
			}

			std::cout << std::flush;	
			prevValue = timeIndex;
		}

		
	}
		
		
	



	return 0;
}
l1menu::ReducedSamplePrivateMembers::ReducedSamplePrivateMembers( const l1menu::ReducedSample& thisObject, const std::string& filename )
	: event(thisObject), triggerMenu(mutableTriggerMenu_), eventRate(1), sumOfWeights(0)
{
	GOOGLE_PROTOBUF_VERIFY_VERSION;

	// Open the file with read ability
	int fileDescriptor = open( filename.c_str(), O_RDONLY );
	if( fileDescriptor==0 ) throw std::runtime_error( "ReducedSample initialise from file - couldn't open file" );
	::UnixFileSentry fileSentry( fileDescriptor ); // Use this as an exception safe way of closing the input file
	google::protobuf::io::FileInputStream fileInput( fileDescriptor );

	// First read the magic number at the start of the file and make sure it
	// matches what I expect. This is uncompressed so I'll wrap it in a block
	// to make sure the CodedInputStream is destructed before creating a new
	// one with gzip input.
	{
		google::protobuf::io::CodedInputStream codedInput( &fileInput );

		// As a read buffer, I'll create a string the correct size (filled with an arbitrary
		// character) and read straight into that.
		std::string readMagicNumber;
		if( !codedInput.ReadString( &readMagicNumber, FILE_FORMAT_MAGIC_NUMBER.size() ) ) throw std::runtime_error( "ReducedSample initialise from file - error reading magic number" );
		if( readMagicNumber!=FILE_FORMAT_MAGIC_NUMBER ) throw std::runtime_error( "ReducedSample - tried to initialise with a file that is not the correct format" );

		google::protobuf::uint32 fileformatVersion;
		if( !codedInput.ReadVarint32( &fileformatVersion ) ) throw std::runtime_error( "ReducedSample initialise from file - error reading file format version" );
		// So far I only have (and ever expect to have) one version of the file
		// format, imaginatively versioned "1". You never know though...
		if( fileformatVersion>1 ) std::cerr << "Warning: Attempting to read a ReducedSample with version " << fileformatVersion << " with code that only knows up to version 1." << std::endl;
	}

	google::protobuf::io::GzipInputStream gzipInput( &fileInput );
	google::protobuf::io::CodedInputStream codedInput( &gzipInput );

	// Disable warnings on this input stream (second parameter, -1). The
	// first parameter is the default. I'll change this if necessary in
	// the loop later.
	size_t totalBytesLimit=67108864;
	codedInput.SetTotalBytesLimit( totalBytesLimit, -1 );

	google::protobuf::uint64 messageSize;

	// Read the size of the header message
	if( !codedInput.ReadVarint64( &messageSize ) ) throw std::runtime_error( "ReducedSample initialise from file - error reading message size for header" );
	google::protobuf::io::CodedInputStream::Limit readLimit=codedInput.PushLimit(messageSize);
	if( !protobufSampleHeader.ParseFromCodedStream( &codedInput ) ) throw std::runtime_error( "ReducedSample initialise from file - some unknown error while reading header" );
	codedInput.PopLimit(readLimit);

	// Keep looping until there is nothing more to be read from the file.
	while( codedInput.ReadVarint64( &messageSize ) )
	{
		readLimit=codedInput.PushLimit(messageSize);

		// Make sure the CodedInputStream doesn't refuse to read the message because it's
		// read too much already. I'll also add an arbitrary 50 on to always make sure
		// I can read the next messageSize if there is one.
		if( gzipInput.ByteCount()+messageSize+50 > totalBytesLimit )
		{
			totalBytesLimit+=messageSize*5; // Might as well set it a little higher than necessary while I'm at it.
			codedInput.SetTotalBytesLimit( totalBytesLimit, -1 );
		}
		std::unique_ptr<l1menuprotobuf::Run> pNewRun( new l1menuprotobuf::Run );
		if( !pNewRun->ParseFromCodedStream( &codedInput ) ) throw std::runtime_error( "ReducedSample initialise from file - some unknown error while reading run" );
		protobufRuns.push_back( std::move( pNewRun ) );

		codedInput.PopLimit(readLimit);
	}


	// Always make sure there is at least one Run ready to be added to. Later
	// code assumes there is already a run there.
	if( protobufRuns.empty() )
	{
		std::unique_ptr<l1menuprotobuf::Run> pNewRun( new l1menuprotobuf::Run );
		protobufRuns.push_back( std::move( pNewRun ) );
	}

	// Count up the sum of the weights of all events
	for( const auto& pRun : protobufRuns )
	{
		sumOfWeights+=sumWeights( *pRun );
	}

	// I have all of the information in the protobuf members, but I also need the trigger information
	// in the form of l1menu::TriggerMenu. Copy out the required information.
	for( int triggerNumber=0; triggerNumber<protobufSampleHeader.trigger_size(); ++triggerNumber )
	{
		const l1menuprotobuf::Trigger& inputTrigger=protobufSampleHeader.trigger(triggerNumber);

		mutableTriggerMenu_.addTrigger( inputTrigger.name(), inputTrigger.version() );
		// Get a reference to the trigger I just created
		l1menu::ITrigger& trigger=mutableTriggerMenu_.getTrigger(triggerNumber);

		// Run through all of the parameters and set them to what they were
		// when the sample was made.
		for( int parameterNumber=0; parameterNumber<inputTrigger.parameter_size(); ++parameterNumber )
		{
			const auto& inputParameter=inputTrigger.parameter(parameterNumber);
			trigger.parameter(inputParameter.name())=inputParameter.value();
		}

		// I should probably check the threshold names exist. I'll do it another time.
	}

}
Beispiel #17
0
int Video::upload_data(
        const uint64_t fileSize,
        const string &sha,
        const uint64_t sliceSize,
        const string &sign,
        const string &url,
        const string &srcPath,
        const uint64_t offset,
        const string &session
        ) {

    int ret = 0;
    char tmp_buf[1024];
    char buf[sliceSize];

    vector<string> headers;
    headers.push_back("Authorization: " + sign);

    ifstream fileInput(srcPath.c_str(),
            ios::in | ios::binary);

    fileInput.seekg(offset);

    uint64_t pos = offset;
    while (fileSize > pos) {
        reset();
        uint64_t len =0;
        fileInput.read(buf, sliceSize);
        len = fileInput.gcount();

        struct curl_httppost *firstitem = NULL,
                             *lastitem = NULL;

        ret = curl_formadd(&firstitem, &lastitem,
                CURLFORM_COPYNAME, "op",
                CURLFORM_COPYCONTENTS, "upload_slice",
                CURLFORM_END);

        snprintf(tmp_buf, sizeof(tmp_buf), 
                "%lu", pos);
        ret = curl_formadd(&firstitem, &lastitem,
                CURLFORM_COPYNAME, "offset",
                CURLFORM_COPYCONTENTS, tmp_buf,
                CURLFORM_END);

        ret = curl_formadd(&firstitem, &lastitem,
                CURLFORM_COPYNAME, "session",
                CURLFORM_COPYCONTENTS, session.c_str(),
                CURLFORM_END);

        ret = curl_formadd(&firstitem, &lastitem,
                CURLFORM_COPYNAME, "filecontent",
                CURLFORM_BUFFER, "data",
                CURLFORM_BUFFERPTR, buf,
                CURLFORM_BUFFERLENGTH, len,
                CURLFORM_END);

        int retry_times = 0;
        do {
            sendRequest(
                    url, 1, &headers, 
                    NULL, firstitem);
            dump_res();
            if (retCode == 0) {
                break;
            }
            retry_times++;
        } while(retry_times < MAX_RETRY_TIMES);

        curl_formfree(firstitem);

        if (retCode != 0) {
            return retCode;
        }

        pos += sliceSize;
    }

    return retCode;
}