Esempio n. 1
0
ofLogFatalError::ofLogFatalError(const string & module, const char* format, ...){
	if(checkLog(OF_LOG_FATAL_ERROR, module)){
		va_list args;
		va_start(args, format);
		channel->log(OF_LOG_FATAL_ERROR, module, format, args);
		va_end(args);
	}
	bPrinted = true;
}
Esempio n. 2
0
//--------------------------------------------------
ofLog::ofLog(ofLogLevel level, const char* format, ...){
	if(checkLog(level,"")){
		va_list args;
		va_start( args, format );
		channel->log(level,"",format,args);
		va_end( args );
	}
	bPrinted = true;
}
Esempio n. 3
0
ofLogNotice::ofLogNotice(const string & module, const char* format, ...){
	if(checkLog(OF_LOG_NOTICE, module)){
		va_list args;
		va_start(args, format);
		channel->log(OF_LOG_NOTICE, module, format, args);
		va_end(args);
	}
	bPrinted = true;
}
Esempio n. 4
0
ofLogWarning::ofLogWarning(const string & module, const char* format, ...){
	if(checkLog(OF_LOG_WARNING, module)){
		va_list args;
		va_start(args, format);
		channel->log(OF_LOG_WARNING, module, format, args);
		va_end(args);
	}
	bPrinted = true;
}
Esempio n. 5
0
void TransferLogManager::close() {
  if (fd_ < 0) {
    return;
  }
  checkLog();
  if (::close(fd_) != 0) {
    PLOG(ERROR) << "Failed to close wdt log " << fd_;
  } else {
    LOG(INFO) << "Transfer log closed";
  }
  fd_ = -1;
}
Esempio n. 6
0
extern "C" __declspec(dllexport) BOOL WINAPI DllMain( HINSTANCE hInstance, DWORD dwReason, LPVOID lpvReserved )
{
	checkLog(__FILE__, __LINE__, "DIRECT", "A");
	std::cout << "DllMain" << std::endl;

	static bool ownApplication = FALSE;

	switch (dwReason) {
	case DLL_PROCESS_ATTACH:
		ownApplication = QMfcApp::pluginInstance( hInstance );
		manager();
		break;
	case DLL_THREAD_ATTACH:
		manager();
		break;
	case DLL_PROCESS_DETACH:
		if (ownApplication)
			delete qApp;
	}

	return TRUE;
}
Esempio n. 7
0
/**
 * Process all actions for a single frame
 * This includes some message passing between child object
 */
void GameStatePlay::logic() {
	if (inpt->window_resized)
		refreshWidgets();

	checkCutscene();

	// check menus first (top layer gets mouse click priority)
	menu->logic();

	if (!isPaused()) {

		// these actions only occur when the game isn't paused
		if (pc->stats.alive) checkLoot();
		checkEnemyFocus();
		if (pc->stats.alive) {
			mapr->checkHotspots();
			mapr->checkNearestEvent();
			checkNPCInteraction();
		}
		checkTitle();

		menu->act->checkAction(action_queue);
		pc->logic(action_queue, restrictPowerUse(), npc_id != -1);

		// Transform powers change the actionbar layout,
		// so we need to prevent accidental clicks if a new power is placed under the slot we clicked on.
		// It's a bit hacky, but it works
		if (pc->isTransforming()) {
			menu->act->resetSlots();
		}

		// transfer hero data to enemies, for AI use
		if (pc->stats.get(STAT_STEALTH) > 100) enemies->hero_stealth = 100;
		else enemies->hero_stealth = pc->stats.get(STAT_STEALTH);

		enemies->logic();
		hazards->logic();
		loot->logic();
		enemies->checkEnemiesforXP();
		npcs->logic();

		snd->logic(pc->stats.pos);

		comb->logic(mapr->cam);
	}

	// close menus when the player dies, but still allow them to be reopened
	if (pc->close_menus) {
		pc->close_menus = false;
		menu->closeAll();
	}

	// these actions occur whether the game is paused or not.
	checkTeleport();
	checkLootDrop();
	checkLog();
	checkBook();
	checkEquipmentChange();
	checkUsedItems();
	checkStash();
	checkSaveEvent();
	checkNotifications();
	checkCancel();

	mapr->logic();
	mapr->enemies_cleared = enemies->isCleared();
	quests->logic();

	pc->checkTransform();

	// change hero powers on transformation
	if (pc->setPowers) {
		pc->setPowers = false;
		if (!pc->stats.humanoid && menu->pow->visible) menu->closeRight();
		// save ActionBar state and lock slots from removing/replacing power
		for (int i=0; i<ACTIONBAR_MAX ; i++) {
			menu->act->hotkeys_temp[i] = menu->act->hotkeys[i];
			menu->act->hotkeys[i] = 0;
		}
		int count = ACTIONBAR_MAIN;
		// put creature powers on action bar
		// TODO What if creature has more powers than the size of the action bar?
		for (size_t i=0; i<pc->charmed_stats->powers_ai.size(); i++) {
			if (pc->charmed_stats->powers_ai[i].id != 0 && powers->powers[pc->charmed_stats->powers_ai[i].id].beacon != true) {
				menu->act->hotkeys[count] = pc->charmed_stats->powers_ai[i].id;
				menu->act->locked[count] = true;
				count++;
			}
			if (count == ACTIONBAR_MAX) count = 0;
		}
		if (pc->stats.manual_untransform && pc->untransform_power > 0) {
			menu->act->hotkeys[count] = pc->untransform_power;
			menu->act->locked[count] = true;
		}
		else if (pc->stats.manual_untransform && pc->untransform_power == 0)
			logError("GameStatePlay: Untransform power not found, you can't untransform manually");

		menu->act->updated = true;

		// reapply equipment if the transformation allows it
		if (pc->stats.transform_with_equipment)
			menu->inv->applyEquipment(menu->inv->inventory[EQUIPMENT].storage);
	}
	// revert hero powers
	if (pc->revertPowers) {
		pc->revertPowers = false;

		// restore ActionBar state
		for (int i=0; i<ACTIONBAR_MAX; i++) {
			menu->act->hotkeys[i] = menu->act->hotkeys_temp[i];
			menu->act->locked[i] = false;
		}

		menu->act->updated = true;

		// also reapply equipment here, to account items that give bonuses to base stats
		menu->inv->applyEquipment(menu->inv->inventory[EQUIPMENT].storage);
	}

	// when the hero (re)spawns, reapply equipment & passive effects
	if (pc->respawn) {
		pc->stats.alive = true;
		pc->stats.corpse = false;
		pc->stats.cur_state = AVATAR_STANCE;
		menu->inv->applyEquipment(menu->inv->inventory[EQUIPMENT].storage);
		menu->inv->changed_equipment = true;
		checkEquipmentChange();
		powers->activatePassives(&pc->stats);
		pc->stats.logic();
		pc->stats.recalc();
		pc->respawn = false;
	}

	// use a normal mouse cursor is menus are open
	if (menu->menus_open) {
		curs->setCursor(CURSOR_NORMAL);
	}

	// update the action bar as it may have been changed by items
	if (menu->act->updated) {
		menu->act->updated = false;

		// set all hotkeys to their base powers
		for (unsigned i = 0; i < menu->act->slots_count; i++) {
			menu->act->hotkeys_mod[i] = menu->act->hotkeys[i];
		}

		updateActionBar();
	}

	// reload music if changed in the pause menu
	if (menu->exit->reload_music) {
		mapr->loadMusic();
		menu->exit->reload_music = false;
	}
}
void Plotter(char* name1, char* name2, char* name3, char* name4, char* titlename){

setGraphTDR();

if(name1==NULL){

	printf("\nWarning: ");
	printf("the file ");
	printf(name1);
	printf(" does not exist \n\n");
	return;
	
}

else if(name2==NULL){

	printf("\nWarning: ");
	printf("the file ");
	printf(name2);
	printf(" does not exist \n\n");
	return;
}

else if(name3==NULL){

	printf("\nWarning: ");
	printf("the file ");
	printf(name3);
	printf(" does not exist \n\n");
	return;
}

else if(name4==NULL){

	printf("\nWarning: ");
	printf("the file ");
	printf(name4);
	printf(" does not exist \n\n");
	return;
	
}

else{

	TFile *f1= new TFile(name1);
	TFile *f2= new TFile(name2);
        TFile *f3= new TFile(name3);
        TFile *f4= new TFile(name4);

}

char *hName1 = new char [80];
char *hName2 = new char [80]; 
char *hName3 = new char [80];
char *hName4 = new char [80]; 	
char *filesave = new char[80];
char *filesave1 = new char[80];
char *filesave2 = new char[80];
char *filesave3 = new char[80];
char *filesave4 = new char[80];

f1->cd();
TIter nextkey1( f1->GetListOfKeys() );
TKey *key1;

f2->cd();
TIter nextkey2( f2->GetListOfKeys() );
TKey *key2;

f3->cd();
TIter nextkey3( f3->GetListOfKeys() );
TKey *key3;

f4->cd();
TIter nextkey4( f4->GetListOfKeys() );
TKey *key4;

int i=0;

    while ((key1 = (TKey*)nextkey1())) {

       key2 = (TKey*)nextkey2();
       key3 = (TKey*)nextkey3();
       key4 = (TKey*)nextkey4();

	// read object from source file
	TObject *obj1 = key1->ReadObj();
	TH1D *h1 = (TH1D*)obj1;

	// read object from source file
	TObject *obj2 = key2->ReadObj();
	TH1D *h2 = (TH1D*)obj2;

	// read object from source file
	TObject *obj3 = key3->ReadObj();
	TH1D *h3 = (TH1D*)obj3;

	// read object from source file
	TObject *obj4 = key4->ReadObj();
	TH1D *h4 = (TH1D*)obj4;

	hName1=h1->GetName();
      	hName2=h2->GetName();
       hName3=h3->GetName();
       hName4=h4->GetName();

        // General Style
        
        h1->GetXaxis()->SetTitleOffset(1.6);
        h1->GetYaxis()->SetTitleOffset(1.6);
        h1->GetZaxis()->SetTitleOffset(2.);
        h2->GetXaxis()->SetTitleOffset(1.6);
        h2->GetYaxis()->SetTitleOffset(1.6);
        h2->GetZaxis()->SetTitleOffset(2.);
        h3->GetXaxis()->SetTitleOffset(1.6);
        h3->GetYaxis()->SetTitleOffset(1.6);
        h3->GetZaxis()->SetTitleOffset(2.);
        h4->GetXaxis()->SetTitleOffset(1.6);
        h4->GetYaxis()->SetTitleOffset(1.6);
        h4->GetZaxis()->SetTitleOffset(2.);
        

        sprintf(filesave,"%s%s.png",h1->GetName(),titlename);
        std::string checkLog(obj1->GetName());


   if (h1->GetEntries() != 0 || h2->GetEntries() != 0 || h3->GetEntries() != 0 || h4->GetEntries() != 0){ // Defense

        if (obj1->IsA()->InheritsFrom("TH1") && obj2->IsA()->InheritsFrom("TH1") && obj3->IsA()->InheritsFrom("TH1") && obj4->IsA()->InheritsFrom("TH1")){
        
           TCanvas *togetherlog = new TCanvas("canvasSamelog","canvasSamelog");
           togetherlog->cd();     

           if ( checkLog == "pTJet1wc" || checkLog == "pTJet2wc" || checkLog == "pfetamaxwc" || checkLog == "pfetaminwc" || checkLog == "deltaEtaJetwc" || checkLog == "deltaPhiJetswc" || checkLog == "deltaPtJetswc"  || checkLog == "dijetMasswc" || checkLog == "pfetamaxwc" || checkLog == "pfetaminwc" || checkLog == "deltaEtaJetswc" || checkLog == "deltaPhiJetswc" || checkLog == "deltaPtJetswc"  || checkLog == "dijetMasswc" || checkLog == "pfetamaxwc" || checkLog == "pfetaminwc" || checkLog == "deltaEtaJetswc" || checkLog == "deltaPhiJetswc" || checkLog == "deltaPtJetswc" || checkLog == "RJJwc" || checkLog == "RJJwc"|| checkLog == "trackswc") {
           togetherlog->SetLogy();
           }           


           setGraphTDR();

           h1->SetMarkerStyle(20);
           h1->SetMarkerSize(1);
    
           h2->SetMarkerStyle(20);
           h2->SetMarkerSize(1);
           h2->SetMarkerColor(2);
        
           h3->SetMarkerStyle(20);
           h3->SetMarkerSize(1);
           h3->SetMarkerColor(3);

           h4->SetMarkerStyle(20);
           h4->SetMarkerSize(1);
           h4->SetMarkerColor(4);
           
           leg = new TLegend(0.71,0.89,0.989,0.989);
           leg->SetTextSize(0.020);
           leg->SetFillColor(0);
           gStyle->SetOptStat(0);
           leg->AddEntry(h1,"Pythia6 Z2","p");
           leg->AddEntry(h2,"Exume","p");
           leg->AddEntry(h3,"Pompty","p");
           leg->AddEntry(h4,"Data 2010","p");
                   
           //h1->SetFillColor(1);
           //h1->Sumw2();
           //h1->GetYaxis()->SetTitle("Probability");
           h1->Draw("PE");
           //h1->DrawNormalized("PE");

           //h2->SetFillColor(2);
           //h2->Sumw2();
           //h2->GetYaxis()->SetTitle("Probability");
           h2->Draw("SAMEPE");
           //h2->DrawNormalized("SAMEPE");

           //h3->SetFillColor(3);
           //h3->Sumw2();
           //h3->GetYaxis()->SetTitle("Probability");
           h3->Draw("SAMEPE");
           //h3->DrawNormalized("SAMEPE");
           leg->Draw();

           //h4->SetFillColor(3);
           //h4->Sumw2();
           //h4->GetYaxis()->SetTitle("Probability");
           h4->Draw("SAMEPE");
           //h4->DrawNormalized("SAMEPE");
           leg->Draw();
           
           togetherlog->Update();
           togetherlog->SaveAs(filesave);
           delete togetherlog;

        }

        if (obj1->IsA ()->InheritsFrom ("TH2") && obj2->IsA ()->InheritsFrom ("TH2") && obj3->IsA ()->InheritsFrom ("TH2") && obj4->IsA ()->InheritsFrom ("TH2")){
     

          if ( checkLog == "ETCaloswc" || checkLog == "ETCalosJetsAtTrackerwc" ){

               TCanvas *togetherLego = new TCanvas("canvasLego","canvasLego");
               gStyle->SetOptStat(1);

               h1->SetMarkerSize(0);
               h2->SetMarkerSize(0);
               h3->SetMarkerSize(0);
               h4->SetMarkerSize(0);

               //h1->GetZaxis()->SetTitle("Probability");
               //h2->GetZaxis()->SetTitle("Probability");
               //h3->GetZaxis()->SetTitle("Probability");
               //h4->GetZaxis()->SetTitle("Probability");

               h1->GetYaxis()->SetTitle("log_{10} Castor Signal [fC]");
               h2->GetYaxis()->SetTitle("log_{10} Castor Signal [fC]");
               h3->GetYaxis()->SetTitle("log_{10} Castor Signal [fC]");
               h4->GetYaxis()->SetTitle("log_{10} Castor Signal [fC]");

               togetherLego->cd();
               togetherLego->SetLogy(1);
               //h1->SetLineColor(1);
               h1->SetFillColor(1);
               h1->Draw("LEGO1E0");
               togetherLego->Update();
               sprintf(filesave1,"%s%s-data2010.png",h1->GetName(),titlename);
               togetherLego->SaveAs(filesave1);

               togetherLego->cd();
               togetherLego->SetLogy(1);
               //h2->SetLineColor(2);
               h2->SetFillColor(2);
               h2->Draw("LEGO1E0");
               togetherLego->Update();
               sprintf(filesave2,"%s%s-exume2010.png",h2->GetName(),titlename);
               togetherLego->SaveAs(filesave2);  

               togetherLego->cd();
               togetherLego->SetLogy(1);
               //h3->SetLineColor(3);
               h3->SetFillColor(3);
               h3->Draw("LEGO1E0");
               togetherLego->Update();
               sprintf(filesave3,"%s%s-pompty2010.png",h3->GetName(),titlename);
               togetherLego->SaveAs(filesave3);   

               togetherLego->cd();
               togetherLego->SetLogy(1);
               //h4->SetLineColor(3);
               h4->SetFillColor(4);
               h4->Draw("LEGO1E0");
               togetherLego->Update();
               sprintf(filesave4,"%s%s-pythia62010.png",h4->GetName(),titlename);
               togetherLego->SaveAs(filesave4);           

               delete togetherLego;

          }
        
          else {

          TCanvas *togetherLegoAll = new TCanvas("canvasLegoAll","canvasLegoAll",1200,400);
          togetherLegoAll->Divide(4,1);

          setGraphTDR();
          //setTH2();   
          h1->SetMarkerSize(0);
          h2->SetMarkerSize(0);
          h3->SetMarkerSize(0);
          h4->SetMarkerSize(0);       

          leg2 = new TLegend(0.71,0.89,0.989,0.989);
          leg2->SetTextSize(0.020);
          leg2->SetFillColor(0);
          leg2->AddEntry(h1,"Pythia6 Z2","f");
          leg2->AddEntry(h2,"Exume","f");
          leg2->AddEntry(h3,"Pompty","f");
          leg2->AddEntry(h4,"Data 2010","f");

          //h1->GetZaxis()->SetTitle("Probability");
          //h2->GetZaxis()->SetTitle("Probability");
          //h3->GetZaxis()->SetTitle("Probability");
          //h4->GetZaxis()->SetTitle("Probability");

          h1->GetYaxis()->SetTitle("nHF^{-}");
          h2->GetYaxis()->SetTitle("nHF^{-}");
          h3->GetYaxis()->SetTitle("nHF^{-}");
          h4->GetYaxis()->SetTitle("nHF^{-}");

          togetherLegoAll->cd(1);
          h1->SetFillColor(1);
          h1->Draw("LEGO1E0");

          togetherLegoAll->cd(2);
          h2->SetFillColor(2);
          h2->Draw("LEGO1E0"); 

          togetherLegoAll->cd(3);
          h3->SetFillColor(3);
          h3->Draw("LEGO1E0");

          togetherLegoAll->cd(4);
          h4->SetFillColor(4);
          h4->Draw("LEGO1E0");

          //leg2->Draw();
          togetherLegoAll->Update();
          togetherLegoAll->SaveAs(filesave);
          delete togetherLegoAll;

          }
 
       }

       i++;

   } // if defense
       
  }

printf("\nNumber of Plots: %d\n\n",i);
       

}
Esempio n. 9
0
int main(){
	Uavcam *camera; 
 	bool camera_ok, frame_ok;
	int n_saved;
	
	std::stringstream filename;
	std::stringstream directory;

	std::vector<int> jpg_params;
	cv::Mat frame, preview;

	parseConfig();
	jpg_params.push_back(CV_IMWRITE_JPEG_QUALITY);
	jpg_params.push_back(90);

	//Set Signals
	std::signal(SIGINT,exit_signal); 	//Set up Ctrl+C signal

	//Construct Cameras
	if (cameratype == 1){
#ifdef USE_ARAVIS
		camera = new AravisCam();
		std::cout<<"Using Aravis camera"<<std::endl;
#else
		camera = new WebCam();
#endif
	}
	
	if(view)	
		cv::namedWindow("Camera Viewer", cv::WINDOW_AUTOSIZE);
	
	n_saved = checkLog(); 			//Check the log and open it
	openLogtoWrite(n_saved);

	ublox = new Gps();			//Initialize the GPS
	std::thread gps_thread(gpsUpdate);
	
	camera_ok = camera->initializeCam();  	//Initialize the camera

	if (camera_ok) {

		std::cout << "Start camera acquisition in " << start_delay << " seconds" << std::endl;
		std::this_thread::sleep_for(std::chrono::seconds(start_delay));	

		while(!finish){  //--Main Acquisition Loop

			filename.str(""); directory.str(""); //Update filenames
			filename<<"im"<<std::setfill('0')<<std::setw(4)<<++n_saved<<".jpg";
			directory<<FOLDER<<filename.str();
		
			camera->trigger(); //Send camera trigger

			if (usegps){
				if(ublox->data_is_good)	
					std::cout<<"GPS up to date"<<std::endl;
				else	
					std::cout<<"No GPS available" <<std::endl;
			}
			mtx.lock();
			writeImageInfo(ublox->current_loc, filename.str()); //Record GPS 
			mtx.unlock();

			frame_ok = camera->getImage(frame); //Acquire the image

			if(frame_ok){ //Acquired Image

				cv::resize(frame,preview,cv::Size(),sizefac,sizefac,cv::INTER_NEAREST);

				if(saveimg) {
					cv::imwrite(directory.str(), preview, jpg_params);
					std::cout<<"Saved to " << filename.str() <<std::endl;
				}

				if(view) {
					cv::imshow("Camera Viewer", preview); 
					cv::waitKey(50);
				}	
			}
			
			std::this_thread::sleep_for(std::chrono::milliseconds(250));
		} 
		//Finished photographing
		delete camera;
	}

	gps_thread.join();
	closeLog();

	return 0;
}
Esempio n. 10
0
void doVMTests(json_spirit::mValue& v, bool _fillin)
{
	processCommandLineOptions();

	for (auto& i: v.get_obj())
	{
		cnote << i.first;
		mObject& o = i.second.get_obj();

		BOOST_REQUIRE(o.count("env") > 0);
		BOOST_REQUIRE(o.count("pre") > 0);
		BOOST_REQUIRE(o.count("exec") > 0);

		FakeExtVM fev;
		fev.importEnv(o["env"].get_obj());
		fev.importState(o["pre"].get_obj());

		if (_fillin)
			o["pre"] = mValue(fev.exportState());

		fev.importExec(o["exec"].get_obj());
		if (fev.code.empty())
		{
			fev.thisTxCode = get<3>(fev.addresses.at(fev.myAddress));
			fev.code = fev.thisTxCode;
		}

		bytes output;
		u256 gas;
		bool vmExceptionOccured = false;
		auto startTime = std::chrono::high_resolution_clock::now();
		try
		{
			auto vm = eth::VMFactory::create(fev.gas);
			output = vm->go(fev, fev.simpleTrace()).toBytes();
			gas = vm->gas();
		}
		catch (VMException const& _e)
		{
			cnote << "Safe VM Exception";
			vmExceptionOccured = true;
		}
		catch (Exception const& _e)
		{
			cnote << "VM did throw an exception: " << diagnostic_information(_e);
			BOOST_ERROR("Failed VM Test with Exception: " << _e.what());
		}
		catch (std::exception const& _e)
		{
			cnote << "VM did throw an exception: " << _e.what();
			BOOST_ERROR("Failed VM Test with Exception: " << _e.what());
		}

		auto endTime = std::chrono::high_resolution_clock::now();
		auto argc = boost::unit_test::framework::master_test_suite().argc;
		auto argv = boost::unit_test::framework::master_test_suite().argv;
		for (auto i = 0; i < argc; ++i)
		{	       
			if (std::string(argv[i]) == "--show-times")
			{
				auto testDuration = endTime - startTime;
				cnote << "Execution time: "
				      << std::chrono::duration_cast<std::chrono::milliseconds>(testDuration).count()
				      << " ms";
				break;
			}
		}

		// delete null entries in storage for the sake of comparison

		for (auto  &a: fev.addresses)
		{
			vector<u256> keystoDelete;
			for (auto &s: get<2>(a.second))
			{
				if (s.second == 0)
					keystoDelete.push_back(s.first);
			}
			for (auto const key: keystoDelete )
			{
				get<2>(a.second).erase(key);
			}
		}


		if (_fillin)
		{
			o["env"] = mValue(fev.exportEnv());
			o["exec"] = mValue(fev.exportExec());
			if (!vmExceptionOccured)
			{
				o["post"] = mValue(fev.exportState());
				o["callcreates"] = fev.exportCallCreates();
				o["out"] = "0x" + toHex(output);
				fev.push(o, "gas", gas);
				o["logs"] = exportLog(fev.sub.logs);
			}
		}
		else
		{
			if (o.count("post") > 0)	// No exceptions expected
			{
				BOOST_CHECK(!vmExceptionOccured);

				BOOST_REQUIRE(o.count("post") > 0);
				BOOST_REQUIRE(o.count("callcreates") > 0);
				BOOST_REQUIRE(o.count("out") > 0);
				BOOST_REQUIRE(o.count("gas") > 0);
				BOOST_REQUIRE(o.count("logs") > 0);

				dev::test::FakeExtVM test;
				test.importState(o["post"].get_obj());
				test.importCallCreates(o["callcreates"].get_array());
				test.sub.logs = importLog(o["logs"].get_array());

				checkOutput(output, o);

				BOOST_CHECK_EQUAL(toInt(o["gas"]), gas);

				auto& expectedAddrs = test.addresses;
				auto& resultAddrs = fev.addresses;
				for (auto&& expectedPair : expectedAddrs)
				{
					auto& expectedAddr = expectedPair.first;
					auto resultAddrIt = resultAddrs.find(expectedAddr);
					if (resultAddrIt == resultAddrs.end())
						BOOST_ERROR("Missing expected address " << expectedAddr);
					else
					{
						auto& expectedState = expectedPair.second;
						auto& resultState = resultAddrIt->second;
						BOOST_CHECK_MESSAGE(std::get<0>(expectedState) == std::get<0>(resultState), expectedAddr << ": incorrect balance " << std::get<0>(resultState) << ", expected " << std::get<0>(expectedState));
						BOOST_CHECK_MESSAGE(std::get<1>(expectedState) == std::get<1>(resultState), expectedAddr << ": incorrect txCount " << std::get<1>(resultState) << ", expected " << std::get<1>(expectedState));
						BOOST_CHECK_MESSAGE(std::get<3>(expectedState) == std::get<3>(resultState), expectedAddr << ": incorrect code");

						checkStorage(std::get<2>(expectedState), std::get<2>(resultState), expectedAddr);
					}
				}

				checkAddresses<std::map<Address, std::tuple<u256, u256, std::map<u256, u256>, bytes> > >(test.addresses, fev.addresses);
				BOOST_CHECK(test.callcreates == fev.callcreates);

				checkLog(fev.sub.logs, test.sub.logs);
			}
			else	// Exception expected
				BOOST_CHECK(vmExceptionOccured);
		}
	}
}
Esempio n. 11
0
//-------------------------------------------------------
void ofLog::_log(ofLogLevel level, const string & module, const string & message){
	if(checkLog(level,module)){
		channel->log(level,module, message);
	}
}
Esempio n. 12
0
void sendResponse(char *allTokens[], char response[MAX_RESPONSE_SIZE], struct connection_bundle *connBundle, char request[MAX_REQUEST_SIZE]){
	//Selects a passed in statement and appropriately assigns a return message
	//General mechanism for message passing between server and client
	int clientSock = connBundle->clientSock;
	int isPrimary = IS_PRIMARY;
	
	/*2. Coordination: The primary takes each request atomically, in the order in which it
	receives it. It checks the unique identifier, in case it has already executed the request,
	and if so it simply resends the response.*/	
	//If request is an UPDATE
	if((strncmp(allTokens[0], "REGISTER", strlen(allTokens[0])) == 0) ||
		(strncmp(allTokens[0], "ADD_TWEET", strlen(allTokens[0])) == 0) ||
		(strncmp(allTokens[0], "ADD_FOLLOWEE", strlen(allTokens[0])) == 0) || 
		(strncmp(allTokens[0], "REMOVE_FOLLOWEE", strlen(allTokens[0])) == 0) ||
		(strncmp(allTokens[0], "DELETE_ACCOUNT", strlen(allTokens[0])) == 0)){
			//check log
			int found = checkLog(request); //stores only updates
			if(found){
				if(snprintf(response, MAX_RESPONSE_SIZE, "%i\n", found) < 0)
				{
					perror("Snprintf failed.");
					exit(SNPRINTF_FAILED);
				}
				//Make sure the back-ups have updated logs
				if(isPrimary)
				{
					notifyBackups(request);
				}
				if(send(clientSock, response, MAX_RESPONSE_SIZE, 0) == -1)
				{
					perror("Send Failed.");
				}
			}
			else
			{
				//3. Execution: The primary executes the request and stores the response.
				//Execute update
				
				handleUpdate(allTokens, response);
				//Log Response
				addLog(request);
				/*4. Agreement: If the request is an update, then the primary sends the updated state,
					the response and the unique identifier to all the backups. The backups send an
					acknowledgement.*/
				if(isPrimary)
				{
					notifyBackups(request);
				}
				/*5. Response: The primary responds to the front end, which hands the response back to the client.*/
				if(send(clientSock, response, MAX_RESPONSE_SIZE, 0) == -1)
				{
					perror("Send Failed.");
					//exit(SEND_FAILED);
				}
				
				
				
			}	  
		}
	else if((strncmp(allTokens[0], "LOGIN", strlen(allTokens[0])) == 0) ||
			(strncmp(allTokens[0], "LIST_FOLLOWEES", strlen(allTokens[0])) == 0) ||
			(strncmp(allTokens[0], "LIST_OTHERS", strlen(allTokens[0])) == 0) ||
			(strncmp(allTokens[0], "LIST_TWEETS", strlen(allTokens[0])) == 0)){
			//Execute read & respond
			handleRead(allTokens, response, clientSock);
			
	}
	else if((strncmp(allTokens[0], "GET_PRIMARY", strlen(allTokens[0])) == 0))
	{	
		int target = (int)atoi(allTokens[1]);
		printf("Target: %s", allTokens[1]);
		puts(request);
		int killed = killPort(target);
		if(killed){
			int myPort = MY_PORT;
			int otherPort1 = OTHER_PORT1;
			int otherPort2 = OTHER_PORT2;
			
			//make choice
			int candidate = selectCandidate(myPort, otherPort1, otherPort2);
			char electoralRequest[MAX_REQUEST_SIZE];
			pthread_mutex_lock(&isPrimaryMutex);
			PRIMARY = candidate;
			if(candidate == myPort)
			{
				IS_PRIMARY = 1;
			}
			pthread_mutex_unlock(&isPrimaryMutex);
			if(snprintf(electoralRequest, MAX_REQUEST_SIZE, "dd\tAPPOINT\t%i", candidate) < 0)
			{
				perror("Snprintf failed.");
				exit(SNPRINTF_FAILED);
			}
			if(otherPort1 != -1)
			{
				//Send candidate
				conductElections(electoralRequest, otherPort1);
			}
			if(otherPort2 != -1)
			{
				conductElections(electoralRequest, otherPort2);
			}
			if(snprintf(response, MAX_RESPONSE_SIZE, "%i\n", candidate) < 0)
			{
				perror("Snprintf failed.");
				exit(SNPRINTF_FAILED);
			}
		}
		else
		{
			//already dead
			int primary = PRIMARY;
			if(primary == -1)
			{
				puts("Invalid primary");
			}
			if(snprintf(response, MAX_RESPONSE_SIZE, "%i\n", primary) < 0)
			{
				perror("Snprintf failed.");
				exit(SNPRINTF_FAILED);
			}
		}
		printf("New leader: %s\n", response);
		if(send(clientSock, response, MAX_RESPONSE_SIZE, 0) == -1)
		{
			perror("Send Failed.");
		}
	}
	else if((strncmp(allTokens[0], "APPOINT", strlen(allTokens[0])) == 0))
	{
		int newPort = atoi(allTokens[1]);
		int myPort = MY_PORT;
		PRIMARY = newPort;
		if(myPort == PRIMARY)
		{
			pthread_mutex_lock(&isPrimaryMutex);
			IS_PRIMARY = 1;
			pthread_mutex_unlock(&isPrimaryMutex);
		}
		
	}
	else{
			exit(INVALID_SELECTION);
		}
}
Esempio n. 13
0
File: main.cpp Progetto: ellis/gcead
void checkFailure(const char* sFile, int iLine, const char* s)
{
	checkLog(sFile, iLine, "CHECK FAILURE", s);
}
Esempio n. 14
0
 virtual void runTests() {
     checkLog();
 }
Esempio n. 15
0
int main(){
	pid_t pid;
	int fluxo, msgKind;
	char userName[50];
	char *bufferRcv, *_bufferRcv, *msgContent;	
	
	struct userList _users;
	struct messageList _messages;
	
	int localSocket,remoteSocket,structSize;
	struct sockaddr_in local;
	struct sockaddr_in remote;
		
	//Inicio da execução
	
	system("clear");
	//Apagando todos os dados de seções passadas
	deleteFile();
	//Criando diretórios necessários
	makeDirectory();
	//Mensagem de inicio
	printf("Servidor iniciado\n");
	
	//Configurações do socket local
	//Mais detalhes consulte as manpages
	localSocket = socket(AF_INET, SOCK_STREAM, 0);
	if(localSocket == -1)
		errorSocket();
		
	//Configuração do socket local
	//Mais detalhes consulte as manpages
	local.sin_family = AF_INET; 
	local.sin_port = htons(31337);  	
	local.sin_addr.s_addr = INADDR_ANY;
	memset(local.sin_zero,0,8);

	//Associação da porta
	if(bind(localSocket, (struct sockaddr *)&local, sizeof(local)) == -1)
		errorBind();
	
	//Inicio da escuta
	if(listen (localSocket, BACKLOG) == -1)
		errorListen();
	
	structSize = sizeof(struct sockaddr_in);
	
	while(1){
		//Agurda um processo conectars-se
		remoteSocket = accept(localSocket, (struct sockaddr *)&remote, &structSize);
		
		//Após a conxão ser aceita, o processo servidor é duplicado
		pid = fork();
		if(pid == 0){
			
				//Alocação de memória necessária
				bufferRcv = (char*) calloc (MAXALLOC, sizeof(char));
				_bufferRcv = (char*) calloc (MAXALLOC, sizeof(char));	
				msgContent = (char*) calloc (MAXALLOC, sizeof(char));			
			
				fluxo = 0;
				while(!fluxo){	
					recv(remoteSocket, bufferRcv, MAXDATASIZE,  0);
					strcpy(_bufferRcv, bufferRcv);
					
					//Após a conexão de um cliente, a primeira mensagem que o servidor espera é do tipo USERNAME,
					//caso contrário o processo servidor é finalizado
					if(checkKindMessage(_bufferRcv,1) == USERNAME){
						//Resgata o conteudo da mensagem
						strcpy(_bufferRcv, bufferRcv);  		
						msgContent = checkMessage(_bufferRcv);
						
						//Verifica se o userName é válido
						if(!checkUserName(msgContent)){
							
								//Se o userName é válido o servidor guarda esse nome para o processo corrente identificar a qual usuário está associado
								strcpy(userName,msgContent);
							
								//Insere o usuário na lista de usuários ativos passando como parâmetros o seu nome e endereço
								insertUser(msgContent,inet_ntoa(remote.sin_addr));
								
								//Informa ao cliente que ele foi conectado		   
								send(remoteSocket,generateMessage("",CONNECTED,1),MAXDATASIZE,0);	
								fluxo = 1;
							}else{
							
								//Sinaliza que o nome de usuário é inválido
								send(remoteSocket,generateMessage("",INVALIDUSERNAME,1),MAXDATASIZE,0);
								fluxo = 0;
							}
					}else{
						close(remoteSocket);
						return 0;
					}
				}
			
			fluxo = 0;	
			while(!fluxo){
				
				//Recebe uma mensagem e guarda o estado de atividade do cliente
				int isActive = recv(remoteSocket, bufferRcv, MAXDATASIZE,  0);
				strcpy(_bufferRcv, bufferRcv); 		
				
				//Verifica o tipo da mensagem
				msgKind = checkKindMessage(_bufferRcv,1);
				strcpy(_bufferRcv, bufferRcv);  		
				msgContent = checkMessage(_bufferRcv);
				
				//Se o estado de conexão é ativo
				if(isActive){
					//Trata as mensagem de acordo com o seu tipo
					switch(msgKind){
						//ACTIVEUSERS: O servidor envia para o cliente a lista de usuários ativos
						case ACTIVEUSERS:{
							int i = 0;
							_users = checkActiveUsers();	
							for(i=0;i<_users.size;i++){
								send(remoteSocket,generateMessage(_users.name[i],USERNAME,1),MAXDATASIZE,0);
							}
							send(remoteSocket,generateMessage("",FINISHED,1),MAXDATASIZE,0);
							break;
						}
						//MESSAGECHAT: O servidor armazena a mensagem enviada pelo cliente	
						case MESSAGECHAT:{
							putMessageChatInLog(userName, msgContent);
							break;
						//UPDATECHAT: O servidor retorna as mensagens direcionadas ao cliente 	
						}case UPDATECHAT:{
							int i = 0;
							_messages = checkLog(userName);
							for(i=0;i<_messages.size;i++){
								send(remoteSocket,generateMessage(_messages.content[i],MESSAGECHAT,1),MAXDATASIZE,0);
							}
							send(remoteSocket,generateMessage("",FINISHED,1),MAXDATASIZE,0);
							break;
						//CLOSE: O servidor fecha a conexão 	
						}case CLOSE:{
							removeUser(userName);
							deleteUserFiles(userName);
							close(remoteSocket);
							
							free(bufferRcv);
							free(_bufferRcv);
							free(msgContent);
							return 0;
						}
					
					}
				}else{
					removeUser(userName);
					deleteUserFiles(userName);
					close(remoteSocket);
					break;
				}
				
				
			}
			
		free(bufferRcv);
		free(_bufferRcv);
		free(msgContent);	
		break;
		}		
	}
	
	return 0;
}