text
stringlengths
54
60.6k
<commit_before>//============================================================================= // // *** AddTaskSPDdNdEta.C *** // // This macro initialize a complete AnalysisTask object for SPD dNdEta analysis. // //============================================================================= AliAnalysisTaskSPDdNdEta *AddTaskSPDdNdEta() { // Creates an analysis task and adds it to the analysis manager. // A. Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskSPDdNdEta", "No analysis manager to connect to."); return NULL; } // B. Check the analysis type using the event handlers connected to the analysis // manager. The availability of MC handler cann also be checked here. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskSPDdNdEta", "This task requires an input event handler"); return NULL; } TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD" // C. Create the task, add it to manager. //============================================================================== AliAnalysisTaskSPDdNdEta *taskSPDdNdEta = new AliAnalysisTaskSPDdNdEta("TaskSPDdNdEta"); mgr->AddTask(taskSPDdNdEta); // D. Configure the analysis task. Extra parameters can be used via optional // arguments of the AddTaskXXX() function. //=========================================================================== taskSPDdNdEta->SetReadMC(kTRUE); // MC // taskSPDdNdEta->SetppAnalysis(kTRUE); //pp analysis taskSPDdNdEta->SetTrigger(1); // 0 = notrigger, 1 = MB1 trigger taskSPDdNdEta->SetEvtGen(kTRUE); //to read Pythia data (kFALSE for Phojet) // E. Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== AliAnalysisDataContainer *cout_SPDdNdEta= mgr->CreateContainer("cOutput", TList::Class(), AliAnalysisManager::kOutputContainer, "SPDdNdEtaData.root"); mgr->ConnectInput(taskSPDdNdEta, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(taskSPDdNdEta, 0, cout_SPDdNdEta); // Return task pointer at the end return taskSPDdNdEta; } <commit_msg>Implement folder structure for task output<commit_after>//============================================================================= // // *** AddTaskSPDdNdEta.C *** // // This macro initialize a complete AnalysisTask object for SPD dNdEta analysis. // //============================================================================= AliAnalysisTaskSPDdNdEta *AddTaskSPDdNdEta() { // Creates an analysis task and adds it to the analysis manager. // A. Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTaskSPDdNdEta", "No analysis manager to connect to."); return NULL; } // B. Check the analysis type using the event handlers connected to the analysis // manager. The availability of MC handler cann also be checked here. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskSPDdNdEta", "This task requires an input event handler"); return NULL; } TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD" // C. Create the task, add it to manager. //============================================================================== AliAnalysisTaskSPDdNdEta *taskSPDdNdEta = new AliAnalysisTaskSPDdNdEta("TaskSPDdNdEta"); mgr->AddTask(taskSPDdNdEta); // D. Configure the analysis task. Extra parameters can be used via optional // arguments of the AddTaskXXX() function. //=========================================================================== taskSPDdNdEta->SetReadMC(kTRUE); // MC // taskSPDdNdEta->SetppAnalysis(kTRUE); //pp analysis taskSPDdNdEta->SetTrigger(1); // 0 = notrigger, 1 = MB1 trigger taskSPDdNdEta->SetEvtGen(kTRUE); //to read Pythia data (kFALSE for Phojet) // E. Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== TString outputfile = AliAnalysisManager::GetCommonFileName(); outputfile += ":PWG2EVCHAR"; AliAnalysisDataContainer *cout_SPDdNdEta= mgr->CreateContainer("evcharlist", TList::Class(), AliAnalysisManager::kOutputContainer,outputfile); mgr->ConnectInput(taskSPDdNdEta, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(taskSPDdNdEta, 0, cout_SPDdNdEta); // Return task pointer at the end return taskSPDdNdEta; } <|endoftext|>
<commit_before>AliAnalysisTaskElectronEfficiencyV2* AddTask_dsekihat_ElectronEfficiencyV2_PbPb( Bool_t getFromAlien = kFALSE, TString configFile="Config_dsekihat_ElectronEfficiencyV2_PbPb.C", TString libFile="LMEECutLib_dsekihat.C", UInt_t trigger = AliVEvent::kINT7, const Int_t CenMin = 0, const Int_t CenMax = 10, const Float_t PtMin = 0.2, const Float_t PtMax = 10.0, const Float_t EtaMin = -0.8, const Float_t EtaMax = +0.8, const TString generators = "pizero_0;eta_1;etaprime_2;rho_3;omega_4;phi_5;jpsi_6;Pythia CC_0;Pythia BB_0;Pythia B_0;", const Bool_t isLHC19f2 = kTRUE, const std::string resolutionFilename ="", const std::string cocktailFilename ="", const std::string centralityFilename ="", const TString outname = "LMEE.root" ){ // Configuring Analysis Manager AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager(); // Creating an instance of the task AliAnalysisTaskElectronEfficiencyV2* task = new AliAnalysisTaskElectronEfficiencyV2(Form("TaskElectronEfficiencyV2_Cen%d_%d_kINT7",CenMin,CenMax)); gROOT->GetListOfSpecials()->Add(task);//this is only for ProcessLine(AddMCSignal); TString configBasePath("$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/"); //TString configBasePath("./"); if(getFromAlien && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/macrosLMEE/%s .",configFile.Data()))) && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/macrosLMEE/%s .",libFile.Data()))) ){ configBasePath=Form("%s/",gSystem->pwd()); } TString configFilePath(configBasePath + configFile); //load cut library first TString libFilePath(configBasePath + libFile); std::cout << "Configpath: " << configFilePath << std::endl; std::cout << "Libpath: " << libFilePath << std::endl; gROOT->LoadMacro(libFilePath.Data());//library first gROOT->LoadMacro(configFilePath.Data()); const Int_t nTC = Int_t(gROOT->ProcessLine("GetNTC()") ); const Int_t nPID = Int_t(gROOT->ProcessLine("GetNPID()")); const Int_t nPF = Int_t(gROOT->ProcessLine("GetNPF()") ); for (Int_t itc=0; itc<nTC; ++itc){ for (Int_t ipid=0; ipid<nPID; ++ipid){ for (Int_t ipf=0; ipf<nPF; ++ipf){ AliAnalysisFilter *filter = reinterpret_cast<AliAnalysisFilter*>(gROOT->ProcessLine(Form("Config_dsekihat_ElectronEfficiencyV2_PbPb(%d,%d,%d,%f,%f,%f,%f)",itc,ipid,ipf,PtMin,PtMax,EtaMin,EtaMax))); task->AddTrackCuts(filter); } } } // Event selection. Is the same for all the different cutsettings task->SetEnablePhysicsSelection(kTRUE);//always ON in Run2 analyses for both data and MC. task->SetTriggerMask(trigger); task->SetEventFilter(reinterpret_cast<AliDielectronEventCuts*>(gROOT->ProcessLine(Form("LMEECutLib::SetupEventCuts(%f,%f,%d,\"%s\")",(Float_t)CenMin,(Float_t)CenMax,kTRUE,"V0M"))));//kTRUE is for Run2 //task->SetCentralityEstimator("V0M"); //task->SetCentrality(CenMin, CenMax); // Set minimum and maximum values of generated tracks. Only used to save computing power. // Do not set here your analysis pt-cuts task->SetMinPtGen(0.1); task->SetMaxPtGen(1e+10); task->SetMinEtaGen(-1.5); task->SetMaxEtaGen(+1.5); // Set minimum and maximum values for pairing task->SetKinematicCuts(PtMin, PtMax, EtaMin, EtaMax); // Set Binning task->SetPtBinsLinear (0, 10, 100); task->SetEtaBinsLinear (-1, +1, 20); task->SetPhiBinsLinear (0, TMath::TwoPi(), 36); task->SetThetaBinsLinear(0, TMath::TwoPi(), 60); const Int_t Nmee = 150; Double_t mee[Nmee] = {}; for(Int_t i=0 ;i<110 ;i++) mee[i] = 0.01 * (i- 0) + 0.0;//from 0 to 1.1 GeV/c2, every 0.01 GeV/c2 for(Int_t i=110;i<Nmee;i++) mee[i] = 0.1 * (i-110) + 1.1;//from 1.1 to 5 GeV/c2, evety 0.1 GeV/c2 std::vector<double> v_mee(mee,std::end(mee)); const Int_t NpTee = 111; Double_t pTee[NpTee] = {}; for(Int_t i=0 ;i<10 ;i++) pTee[i] = 0.01 * (i- 0) + 0.0;//from 0 to 0.09 GeV/c, every 0.01 GeV/c for(Int_t i=10 ;i<100 ;i++) pTee[i] = 0.1 * (i- 10) + 0.1;//from 0.1 to 10 GeV/c, evety 0.1 GeV/c for(Int_t i=100;i<NpTee;i++) pTee[i] = 1.0 * (i-100) + 10.0;//from 10 to 20 GeV/c, evety 1.0 GeV/c std::vector<double> v_pTee(pTee,std::end(pTee)); task->SetMassBins(v_mee); task->SetPairPtBins(v_pTee); task->SetPhiVBinsLinear(0, TMath::Pi(), 72); task->SetFillPhiV(kTRUE); task->SetSmearGenerated(kFALSE); task->SetResolutionDeltaPtBinsLinear( -10, +10, 2000); task->SetResolutionRelPtBinsLinear ( 0, 2, 400); task->SetResolutionEtaBinsLinear (-0.4, +0.4, 200); task->SetResolutionPhiBinsLinear (-0.4, +0.4, 200); task->SetResolutionThetaBinsLinear (-0.4, +0.4, 200); // Set MCSignal and Cutsetting to fill the support histograms task->SetSupportHistoMCSignalAndCutsetting(0,0);//fill support histograms for first MCsignal and first cutsetting // Pairing related config task->SetDoPairing(kTRUE); //task->SetULSandLS(kTRUE); //task->SetDeactivateLS(kTRUE); //TString generators = "pizero_0;eta_1;etaprime_2;rho_3;omega_4;phi_5;jpsi_6;"; //TString generators = "pizero_0;eta_1;etaprime_2;rho_3;omega_4;phi_5;jpsi_6;Pythia CC_0;Pythia BB_0;Pythia B_0;"; //TString generators = "Pythia CC_0;Pythia BB_0;Pythia B_0;"; //TString generators = "Pythia CC_0;"; //TString generators = "Pythia BB_0;Pythia B_0;"; //TString generators = "Pythia BB_0;"; //TString generators = "Pythia B_0"; cout<<"Efficiency based on MC generators: " << generators <<endl; TString generatorsPair=generators; task->SetGeneratorMCSignalName(generatorsPair); task->SetGeneratorULSSignalName(generators); task->SetLHC19f2MC(isLHC19f2); // Resolution File, If resoFilename = "" no correction is applied task->SetResolutionFile(resolutionFilename); task->SetResolutionFileFromAlien("/alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/resolution/" + resolutionFilename); task->SetCentralityFile(centralityFilename); task->SetCocktailWeighting(cocktailFilename); task->SetCocktailWeightingFromAlien("/alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/cocktail/" + cocktailFilename); // Add MCSignals. Can be set to see differences of: // e.g. secondaries and primaries. or primaries from charm and resonances gROOT->ProcessLine(Form("AddSingleLegMCSignal(%s)",task->GetName()));//not task itself, task name gROOT->ProcessLine(Form("AddPairMCSignal(%s)" ,task->GetName()));//not task itself, task name //const TString fileName = AliAnalysisManager::GetCommonFileName(); const TString fileName = outname; //const TString dirname = Form("PWGDQ_LMEE_ElectronEfficiencyV2_Cen%d_%d_kINT7",CenMin,CenMax); mgr->AddTask(task); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 1, mgr->CreateContainer(Form("Efficiency_dsekihat_Cen%d_%d_kINT7",CenMin,CenMax), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s",fileName.Data()))); return task; } <commit_msg>PWGDQ/LMEE: change pTee binning for MC<commit_after>AliAnalysisTaskElectronEfficiencyV2* AddTask_dsekihat_ElectronEfficiencyV2_PbPb( Bool_t getFromAlien = kFALSE, TString configFile="Config_dsekihat_ElectronEfficiencyV2_PbPb.C", TString libFile="LMEECutLib_dsekihat.C", UInt_t trigger = AliVEvent::kINT7, const Int_t CenMin = 0, const Int_t CenMax = 10, const Float_t PtMin = 0.2, const Float_t PtMax = 10.0, const Float_t EtaMin = -0.8, const Float_t EtaMax = +0.8, const TString generators = "pizero_0;eta_1;etaprime_2;rho_3;omega_4;phi_5;jpsi_6;Pythia CC_0;Pythia BB_0;Pythia B_0;", const Bool_t isLHC19f2 = kTRUE, const std::string resolutionFilename ="", const std::string cocktailFilename ="", const std::string centralityFilename ="", const TString outname = "LMEE.root" ){ // Configuring Analysis Manager AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager(); // Creating an instance of the task AliAnalysisTaskElectronEfficiencyV2* task = new AliAnalysisTaskElectronEfficiencyV2(Form("TaskElectronEfficiencyV2_Cen%d_%d_kINT7",CenMin,CenMax)); gROOT->GetListOfSpecials()->Add(task);//this is only for ProcessLine(AddMCSignal); TString configBasePath("$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/"); //TString configBasePath("./"); if(getFromAlien && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/macrosLMEE/%s .",configFile.Data()))) && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/macrosLMEE/%s .",libFile.Data()))) ){ configBasePath=Form("%s/",gSystem->pwd()); } TString configFilePath(configBasePath + configFile); //load cut library first TString libFilePath(configBasePath + libFile); std::cout << "Configpath: " << configFilePath << std::endl; std::cout << "Libpath: " << libFilePath << std::endl; gROOT->LoadMacro(libFilePath.Data());//library first gROOT->LoadMacro(configFilePath.Data()); const Int_t nTC = Int_t(gROOT->ProcessLine("GetNTC()") ); const Int_t nPID = Int_t(gROOT->ProcessLine("GetNPID()")); const Int_t nPF = Int_t(gROOT->ProcessLine("GetNPF()") ); for (Int_t itc=0; itc<nTC; ++itc){ for (Int_t ipid=0; ipid<nPID; ++ipid){ for (Int_t ipf=0; ipf<nPF; ++ipf){ AliAnalysisFilter *filter = reinterpret_cast<AliAnalysisFilter*>(gROOT->ProcessLine(Form("Config_dsekihat_ElectronEfficiencyV2_PbPb(%d,%d,%d,%f,%f,%f,%f)",itc,ipid,ipf,PtMin,PtMax,EtaMin,EtaMax))); task->AddTrackCuts(filter); } } } // Event selection. Is the same for all the different cutsettings task->SetEnablePhysicsSelection(kTRUE);//always ON in Run2 analyses for both data and MC. task->SetTriggerMask(trigger); task->SetEventFilter(reinterpret_cast<AliDielectronEventCuts*>(gROOT->ProcessLine(Form("LMEECutLib::SetupEventCuts(%f,%f,%d,\"%s\")",(Float_t)CenMin,(Float_t)CenMax,kTRUE,"V0M"))));//kTRUE is for Run2 //task->SetCentralityEstimator("V0M"); //task->SetCentrality(CenMin, CenMax); // Set minimum and maximum values of generated tracks. Only used to save computing power. // Do not set here your analysis pt-cuts task->SetMinPtGen(0.1); task->SetMaxPtGen(1e+10); task->SetMinEtaGen(-1.5); task->SetMaxEtaGen(+1.5); // Set minimum and maximum values for pairing task->SetKinematicCuts(PtMin, PtMax, EtaMin, EtaMax); // Set Binning task->SetPtBinsLinear (0, 10, 100); task->SetEtaBinsLinear (-1, +1, 20); task->SetPhiBinsLinear (0, TMath::TwoPi(), 36); task->SetThetaBinsLinear(0, TMath::TwoPi(), 60); const Int_t Nmee = 150; Double_t mee[Nmee] = {}; for(Int_t i=0 ;i<110 ;i++) mee[i] = 0.01 * (i- 0) + 0.0;//from 0 to 1.1 GeV/c2, every 0.01 GeV/c2 for(Int_t i=110;i<Nmee;i++) mee[i] = 0.1 * (i-110) + 1.1;//from 1.1 to 5 GeV/c2, evety 0.1 GeV/c2 std::vector<double> v_mee(mee,std::end(mee)); const Int_t NpTee = 121; Double_t pTee[NpTee] = {}; for(Int_t i=0 ;i<10 ;i++) pTee[i] = 0.01 * (i- 0) + 0.0;//from 0 to 0.09 GeV/c, every 0.01 GeV/c for(Int_t i=10 ;i<110 ;i++) pTee[i] = 0.1 * (i- 10) + 0.1;//from 0.1 to 10 GeV/c, evety 0.1 GeV/c for(Int_t i=110;i<NpTee;i++) pTee[i] = 1.0 * (i-110) + 10.0;//from 10 to 20 GeV/c, evety 1.0 GeV/c std::vector<double> v_pTee(pTee,std::end(pTee)); task->SetMassBins(v_mee); task->SetPairPtBins(v_pTee); task->SetPhiVBinsLinear(0, TMath::Pi(), 100); task->SetFillPhiV(kTRUE); task->SetSmearGenerated(kFALSE); task->SetResolutionDeltaPtBinsLinear( -10, +10, 2000); task->SetResolutionRelPtBinsLinear ( 0, 2, 400); task->SetResolutionEtaBinsLinear (-0.4, +0.4, 200); task->SetResolutionPhiBinsLinear (-0.4, +0.4, 200); task->SetResolutionThetaBinsLinear (-0.4, +0.4, 200); // Set MCSignal and Cutsetting to fill the support histograms task->SetSupportHistoMCSignalAndCutsetting(0,0);//fill support histograms for first MCsignal and first cutsetting // Pairing related config task->SetDoPairing(kTRUE); //task->SetULSandLS(kTRUE); //task->SetDeactivateLS(kTRUE); //TString generators = "pizero_0;eta_1;etaprime_2;rho_3;omega_4;phi_5;jpsi_6;"; //TString generators = "pizero_0;eta_1;etaprime_2;rho_3;omega_4;phi_5;jpsi_6;Pythia CC_0;Pythia BB_0;Pythia B_0;"; //TString generators = "Pythia CC_0;Pythia BB_0;Pythia B_0;"; //TString generators = "Pythia CC_0;"; //TString generators = "Pythia BB_0;Pythia B_0;"; //TString generators = "Pythia BB_0;"; //TString generators = "Pythia B_0"; cout<<"Efficiency based on MC generators: " << generators <<endl; TString generatorsPair=generators; task->SetGeneratorMCSignalName(generatorsPair); task->SetGeneratorULSSignalName(generators); task->SetLHC19f2MC(isLHC19f2); // Resolution File, If resoFilename = "" no correction is applied task->SetResolutionFile(resolutionFilename); task->SetResolutionFileFromAlien("/alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/resolution/" + resolutionFilename); task->SetCentralityFile(centralityFilename); task->SetCocktailWeighting(cocktailFilename); task->SetCocktailWeightingFromAlien("/alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/cocktail/" + cocktailFilename); // Add MCSignals. Can be set to see differences of: // e.g. secondaries and primaries. or primaries from charm and resonances gROOT->ProcessLine(Form("AddSingleLegMCSignal(%s)",task->GetName()));//not task itself, task name gROOT->ProcessLine(Form("AddPairMCSignal(%s)" ,task->GetName()));//not task itself, task name //const TString fileName = AliAnalysisManager::GetCommonFileName(); const TString fileName = outname; //const TString dirname = Form("PWGDQ_LMEE_ElectronEfficiencyV2_Cen%d_%d_kINT7",CenMin,CenMax); mgr->AddTask(task); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 1, mgr->CreateContainer(Form("Efficiency_dsekihat_Cen%d_%d_kINT7",CenMin,CenMax), TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s",fileName.Data()))); return task; } <|endoftext|>
<commit_before>//---------------------------- data_out_01.cc --------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2003, 2004 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- data_out_01.cc --------------------------- #include "../tests.h" #include "data_out_common.cc" #include <lac/sparsity_pattern.h> #include <numerics/data_out.h> std::string output_file_name = "data_out_01.output"; template <int dim> void check_this (const DoFHandler<dim> &dof_handler, const Vector<double> &v_node, const Vector<double> &v_cell) { DataOut<dim> data_out; data_out.attach_dof_handler (dof_handler); data_out.add_data_vector (v_node, "node_data"); data_out.add_data_vector (v_cell, "cell_data"); data_out.build_patches (); data_out.write_dx (deallog.get_file_stream()); data_out.write_ucd (deallog.get_file_stream()); data_out.write_gmv (deallog.get_file_stream()); data_out.write_tecplot (deallog.get_file_stream()); data_out.write_vtk (deallog.get_file_stream()); data_out.write_gnuplot (deallog.get_file_stream()); data_out.write_deal_II_intermediate (deallog.get_file_stream()); // the following is only // implemented for 2d if (dim == 2) { data_out.write_povray (deallog.get_file_stream()); data_out.write_eps (deallog.get_file_stream()); } } <commit_msg>remove redundancy<commit_after>//---------------------------------------------------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2003, 2004, 2005 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------------------------------------------------- #include "../tests.h" #include "data_out_common.cc" #include <lac/sparsity_pattern.h> #include <numerics/data_out.h> std::string output_file_name = "data_out_01.output"; template <int dim> void check_this (const DoFHandler<dim> &dof_handler, const Vector<double> &v_node, const Vector<double> &v_cell) { DataOut<dim> data_out; data_out.attach_dof_handler (dof_handler); data_out.add_data_vector (v_node, "node_data"); data_out.add_data_vector (v_cell, "cell_data"); data_out.build_patches (); data_out.write_dx (deallog.get_file_stream()); data_out.write_ucd (deallog.get_file_stream()); data_out.write_gmv (deallog.get_file_stream()); data_out.write_tecplot (deallog.get_file_stream()); data_out.write_vtk (deallog.get_file_stream()); data_out.write_gnuplot (deallog.get_file_stream()); data_out.write_deal_II_intermediate (deallog.get_file_stream()); // the following is only // implemented for 2d if (dim == 2) { data_out.write_povray (deallog.get_file_stream()); data_out.write_eps (deallog.get_file_stream()); } } <|endoftext|>
<commit_before>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include <algorithm> #include "Engine.h" #include "CompileConfig.h" #include "Cache.h" #include "Localization.h" #if defined(OUZEL_PLATFORM_OSX) #include "osx/WindowOSX.h" #elif defined(OUZEL_PLATFORM_IOS) #include "ios/WindowIOS.h" #elif defined(OUZEL_PLATFORM_TVOS) #include "tvos/WindowTVOS.h" #elif defined(OUZEL_PLATFORM_ANDROID) #include "android/WindowAndroid.h" #elif defined(OUZEL_PLATFORM_LINUX) #include "linux/WindowLinux.h" #elif defined(OUZEL_PLATFORM_WINDOWS) #include "win/WindowWin.h" #endif #if defined(OUZEL_SUPPORTS_OPENGL) || defined(OUZEL_SUPPORTS_OPENGLES) #include "opengl/RendererOGL.h" #endif #if defined(OUZEL_SUPPORTS_DIRECT3D11) #include "direct3d11/RendererD3D11.h" #endif #if defined(OUZEL_SUPPORTS_METAL) #include "metal/RendererMetal.h" #endif #include "Utils.h" #include "Renderer.h" #include "FileSystem.h" #if defined(OUZEL_PLATFORM_OSX) || defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS) #include "apple/InputApple.h" #elif defined(OUZEL_PLATFORM_WINDOWS) #include "win/InputWin.h" #endif namespace ouzel { ouzel::Engine* sharedEngine = nullptr; Engine::Engine() { sharedEngine = this; } Engine::~Engine() { if (sceneManager) { sceneManager->setScene(nullptr); } } std::set<graphics::Renderer::Driver> Engine::getAvailableDrivers() { std::set<graphics::Renderer::Driver> availableDrivers; #if defined(OUZEL_SUPPORTS_OPENGL) || defined(OUZEL_SUPPORTS_OPENGLES) availableDrivers.insert(graphics::Renderer::Driver::OPENGL2); #endif #if defined(OUZEL_SUPPORTS_DIRECT3D11) availableDrivers.insert(graphics::Renderer::Driver::DIRECT3D11); #endif #if defined(OUZEL_SUPPORTS_METAL) if (graphics::RendererMetal::available()) { availableDrivers.insert(graphics::Renderer::Driver::METAL); } #endif return availableDrivers; } bool Engine::init(Settings& settings) { targetFPS = settings.targetFPS; if (settings.driver == graphics::Renderer::Driver::DEFAULT) { #if defined(OUZEL_SUPPORTS_METAL) if (graphics::RendererMetal::available()) { settings.driver = graphics::Renderer::Driver::METAL; } #if defined(OUZEL_SUPPORTS_OPENGL) || defined(OUZEL_SUPPORTS_OPENGLES) else { settings.driver = graphics::Renderer::Driver::OPENGL2; } #endif #elif defined(OUZEL_SUPPORTS_DIRECT3D11) settings.driver = graphics::Renderer::Driver::DIRECT3D11; #elif defined(OUZEL_SUPPORTS_OPENGL) || defined(OUZEL_SUPPORTS_OPENGLES) settings.driver = graphics::Renderer::Driver::OPENGL; #endif } if (settings.driver == graphics::Renderer::Driver::DEFAULT) { log("Failed to select render driver"); return false; } #if defined(OUZEL_PLATFORM_OSX) window.reset(new WindowOSX(settings.size, settings.resizable, settings.fullscreen, settings.sampleCount, settings.title)); #elif defined(OUZEL_PLATFORM_IOS) window.reset(new WindowIOS(settings.size, settings.resizable, settings.fullscreen, settings.sampleCount, settings.title)); #elif defined(OUZEL_PLATFORM_TVOS) window.reset(new WindowTVOS(settings.size, settings.resizable, settings.fullscreen, settings.sampleCount, settings.title)); #elif defined(OUZEL_PLATFORM_ANDROID) window.reset(new WindowAndroid(settings.size, settings.resizable, settings.fullscreen, settings.sampleCount, settings.title)); #elif defined(OUZEL_PLATFORM_LINUX) window.reset(new WindowLinux(settings.size, settings.resizable, settings.fullscreen, settings.sampleCount, settings.title)); #elif defined(OUZEL_PLATFORM_WINDOWS) window.reset(new WindowWin(settings.size, settings.resizable, settings.fullscreen, settings.sampleCount, settings.title)); #endif eventDispatcher.reset(new EventDispatcher()); cache.reset(new Cache()); fileSystem.reset(new FileSystem()); sceneManager.reset(new scene::SceneManager()); #if defined(OUZEL_PLATFORM_OSX) || defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS) input.reset(new input::InputApple()); #elif defined(OUZEL_PLATFORM_WINDOWS) input.reset(new input::InputWin()); #else input.reset(new input::Input()); #endif localization.reset(new Localization()); switch (settings.driver) { #if defined(OUZEL_SUPPORTS_OPENGL) || defined(OUZEL_SUPPORTS_OPENGLES) case graphics::Renderer::Driver::OPENGL2: log("Using OpenGL 2 render driver"); renderer.reset(new graphics::RendererOGL(graphics::Renderer::Driver::OPENGL2)); break; #if defined(OUZEL_SUPPORTS_OPENGL3) case graphics::Renderer::Driver::OPENGL3: log("Using OpenGL 3 render driver"); renderer.reset(new graphics::RendererOGL(graphics::Renderer::Driver::OPENGL3)); break; #endif #endif #if defined(OUZEL_SUPPORTS_DIRECT3D11) case graphics::Renderer::Driver::DIRECT3D11: log("Using Direct3D 11 render driver"); renderer.reset(new graphics::RendererD3D11()); break; #endif #if defined(OUZEL_SUPPORTS_METAL) case graphics::Renderer::Driver::METAL: log("Using Metal render driver"); renderer.reset(new graphics::RendererMetal()); break; #endif default: log("Unsupported render driver"); return false; } if (!window->init()) { return false; } previousFrameTime = getCurrentMicroSeconds(); return true; } void Engine::exit() { active = false; } void Engine::begin() { running = true; } void Engine::end() { } bool Engine::run() { uint64_t currentTime = getCurrentMicroSeconds(); float delta = static_cast<float>((currentTime - previousFrameTime)) / 1000000.0f; previousFrameTime = currentTime; currentFPS = 1.0f / delta; input->update(); eventDispatcher->update(); lock(); for (const UpdateCallbackPtr& updateCallback : updateCallbacks) { if (!updateCallback->remove && updateCallback->callback) { updateCallback->callback(delta); } } unlock(); renderer->clear(); sceneManager->draw(); renderer->present(); return active; } void Engine::scheduleUpdate(const UpdateCallbackPtr& callback) { if (locked) { updateCallbackAddList.insert(callback); } else { std::vector<UpdateCallbackPtr>::iterator i = std::find(updateCallbacks.begin(), updateCallbacks.end(), callback); if (i == updateCallbacks.end()) { callback->remove = false; updateCallbacks.push_back(callback); } } } void Engine::unscheduleUpdate(const UpdateCallbackPtr& callback) { if (locked) { callback->remove = true; updateCallbackRemoveList.insert(callback); } else { std::vector<UpdateCallbackPtr>::iterator i = std::find(updateCallbacks.begin(), updateCallbacks.end(), callback); if (i != updateCallbacks.end()) { updateCallbacks.erase(i); } } } void Engine::lock() { ++locked; } void Engine::unlock() { if (--locked == 0) { if (!updateCallbackAddList.empty()) { for (const UpdateCallbackPtr& updateCallback : updateCallbackAddList) { scheduleUpdate(updateCallback); } updateCallbackAddList.clear(); } if (!updateCallbackRemoveList.empty()) { for (const UpdateCallbackPtr& updateCallback : updateCallbackRemoveList) { unscheduleUpdate(updateCallback); } updateCallbackRemoveList.clear(); } } } } <commit_msg>Use correct OpenGL driver constant for Linux target<commit_after>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include <algorithm> #include "Engine.h" #include "CompileConfig.h" #include "Cache.h" #include "Localization.h" #if defined(OUZEL_PLATFORM_OSX) #include "osx/WindowOSX.h" #elif defined(OUZEL_PLATFORM_IOS) #include "ios/WindowIOS.h" #elif defined(OUZEL_PLATFORM_TVOS) #include "tvos/WindowTVOS.h" #elif defined(OUZEL_PLATFORM_ANDROID) #include "android/WindowAndroid.h" #elif defined(OUZEL_PLATFORM_LINUX) #include "linux/WindowLinux.h" #elif defined(OUZEL_PLATFORM_WINDOWS) #include "win/WindowWin.h" #endif #if defined(OUZEL_SUPPORTS_OPENGL) || defined(OUZEL_SUPPORTS_OPENGLES) #include "opengl/RendererOGL.h" #endif #if defined(OUZEL_SUPPORTS_DIRECT3D11) #include "direct3d11/RendererD3D11.h" #endif #if defined(OUZEL_SUPPORTS_METAL) #include "metal/RendererMetal.h" #endif #include "Utils.h" #include "Renderer.h" #include "FileSystem.h" #if defined(OUZEL_PLATFORM_OSX) || defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS) #include "apple/InputApple.h" #elif defined(OUZEL_PLATFORM_WINDOWS) #include "win/InputWin.h" #endif namespace ouzel { ouzel::Engine* sharedEngine = nullptr; Engine::Engine() { sharedEngine = this; } Engine::~Engine() { if (sceneManager) { sceneManager->setScene(nullptr); } } std::set<graphics::Renderer::Driver> Engine::getAvailableDrivers() { std::set<graphics::Renderer::Driver> availableDrivers; #if defined(OUZEL_SUPPORTS_OPENGL) || defined(OUZEL_SUPPORTS_OPENGLES) availableDrivers.insert(graphics::Renderer::Driver::OPENGL2); #endif #if defined(OUZEL_SUPPORTS_DIRECT3D11) availableDrivers.insert(graphics::Renderer::Driver::DIRECT3D11); #endif #if defined(OUZEL_SUPPORTS_METAL) if (graphics::RendererMetal::available()) { availableDrivers.insert(graphics::Renderer::Driver::METAL); } #endif return availableDrivers; } bool Engine::init(Settings& settings) { targetFPS = settings.targetFPS; if (settings.driver == graphics::Renderer::Driver::DEFAULT) { #if defined(OUZEL_SUPPORTS_METAL) if (graphics::RendererMetal::available()) { settings.driver = graphics::Renderer::Driver::METAL; } #if defined(OUZEL_SUPPORTS_OPENGL) || defined(OUZEL_SUPPORTS_OPENGLES) else { settings.driver = graphics::Renderer::Driver::OPENGL2; } #endif #elif defined(OUZEL_SUPPORTS_DIRECT3D11) settings.driver = graphics::Renderer::Driver::DIRECT3D11; #elif defined(OUZEL_SUPPORTS_OPENGL) || defined(OUZEL_SUPPORTS_OPENGLES) settings.driver = graphics::Renderer::Driver::OPENGL2; #endif } if (settings.driver == graphics::Renderer::Driver::DEFAULT) { log("Failed to select render driver"); return false; } #if defined(OUZEL_PLATFORM_OSX) window.reset(new WindowOSX(settings.size, settings.resizable, settings.fullscreen, settings.sampleCount, settings.title)); #elif defined(OUZEL_PLATFORM_IOS) window.reset(new WindowIOS(settings.size, settings.resizable, settings.fullscreen, settings.sampleCount, settings.title)); #elif defined(OUZEL_PLATFORM_TVOS) window.reset(new WindowTVOS(settings.size, settings.resizable, settings.fullscreen, settings.sampleCount, settings.title)); #elif defined(OUZEL_PLATFORM_ANDROID) window.reset(new WindowAndroid(settings.size, settings.resizable, settings.fullscreen, settings.sampleCount, settings.title)); #elif defined(OUZEL_PLATFORM_LINUX) window.reset(new WindowLinux(settings.size, settings.resizable, settings.fullscreen, settings.sampleCount, settings.title)); #elif defined(OUZEL_PLATFORM_WINDOWS) window.reset(new WindowWin(settings.size, settings.resizable, settings.fullscreen, settings.sampleCount, settings.title)); #endif eventDispatcher.reset(new EventDispatcher()); cache.reset(new Cache()); fileSystem.reset(new FileSystem()); sceneManager.reset(new scene::SceneManager()); #if defined(OUZEL_PLATFORM_OSX) || defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS) input.reset(new input::InputApple()); #elif defined(OUZEL_PLATFORM_WINDOWS) input.reset(new input::InputWin()); #else input.reset(new input::Input()); #endif localization.reset(new Localization()); switch (settings.driver) { #if defined(OUZEL_SUPPORTS_OPENGL) || defined(OUZEL_SUPPORTS_OPENGLES) case graphics::Renderer::Driver::OPENGL2: log("Using OpenGL 2 render driver"); renderer.reset(new graphics::RendererOGL(graphics::Renderer::Driver::OPENGL2)); break; #if defined(OUZEL_SUPPORTS_OPENGL3) case graphics::Renderer::Driver::OPENGL3: log("Using OpenGL 3 render driver"); renderer.reset(new graphics::RendererOGL(graphics::Renderer::Driver::OPENGL3)); break; #endif #endif #if defined(OUZEL_SUPPORTS_DIRECT3D11) case graphics::Renderer::Driver::DIRECT3D11: log("Using Direct3D 11 render driver"); renderer.reset(new graphics::RendererD3D11()); break; #endif #if defined(OUZEL_SUPPORTS_METAL) case graphics::Renderer::Driver::METAL: log("Using Metal render driver"); renderer.reset(new graphics::RendererMetal()); break; #endif default: log("Unsupported render driver"); return false; } if (!window->init()) { return false; } previousFrameTime = getCurrentMicroSeconds(); return true; } void Engine::exit() { active = false; } void Engine::begin() { running = true; } void Engine::end() { } bool Engine::run() { uint64_t currentTime = getCurrentMicroSeconds(); float delta = static_cast<float>((currentTime - previousFrameTime)) / 1000000.0f; previousFrameTime = currentTime; currentFPS = 1.0f / delta; input->update(); eventDispatcher->update(); lock(); for (const UpdateCallbackPtr& updateCallback : updateCallbacks) { if (!updateCallback->remove && updateCallback->callback) { updateCallback->callback(delta); } } unlock(); renderer->clear(); sceneManager->draw(); renderer->present(); return active; } void Engine::scheduleUpdate(const UpdateCallbackPtr& callback) { if (locked) { updateCallbackAddList.insert(callback); } else { std::vector<UpdateCallbackPtr>::iterator i = std::find(updateCallbacks.begin(), updateCallbacks.end(), callback); if (i == updateCallbacks.end()) { callback->remove = false; updateCallbacks.push_back(callback); } } } void Engine::unscheduleUpdate(const UpdateCallbackPtr& callback) { if (locked) { callback->remove = true; updateCallbackRemoveList.insert(callback); } else { std::vector<UpdateCallbackPtr>::iterator i = std::find(updateCallbacks.begin(), updateCallbacks.end(), callback); if (i != updateCallbacks.end()) { updateCallbacks.erase(i); } } } void Engine::lock() { ++locked; } void Engine::unlock() { if (--locked == 0) { if (!updateCallbackAddList.empty()) { for (const UpdateCallbackPtr& updateCallback : updateCallbackAddList) { scheduleUpdate(updateCallback); } updateCallbackAddList.clear(); } if (!updateCallbackRemoveList.empty()) { for (const UpdateCallbackPtr& updateCallback : updateCallbackRemoveList) { unscheduleUpdate(updateCallback); } updateCallbackRemoveList.clear(); } } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: mphndl.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-09 10:25:12 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef UUI_IAHNDL_HXX #define UUI_IAHNDL_HXX #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_ #include <com/sun/star/lang/XTypeProvider.hpp> #endif #ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_ #include <com/sun/star/task/XInteractionHandler.hpp> #endif #ifndef _COM_SUN_STAR_TASK_XPASSWORDCONTAINER_HPP_ #include <com/sun/star/task/XPasswordContainer.hpp> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif //============================================================================ class UUIInteractionHandler: public cppu::OWeakObject, public com::sun::star::lang::XServiceInfo, public com::sun::star::lang::XTypeProvider, public com::sun::star::task::XInteractionHandler { ::com::sun::star::uno::Reference< ::com::sun::star::task::XPasswordContainer > mPContainer; public: static sal_Char const m_aImplementationName[]; UUIInteractionHandler( com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > const & ); virtual com::sun::star::uno::Any SAL_CALL queryInterface(com::sun::star::uno::Type const & rType) throw (com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire() throw (com::sun::star::uno::RuntimeException); virtual void SAL_CALL release() throw (com::sun::star::uno::RuntimeException); virtual rtl::OUString SAL_CALL getImplementationName() throw (com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService(rtl::OUString const & rServiceName) throw (com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames() throw (com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Sequence< com::sun::star::uno::Type > SAL_CALL getTypes() throw (com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (com::sun::star::uno::RuntimeException); virtual void SAL_CALL handle(com::sun::star::uno::Reference< com::sun::star::task::XInteractionRequest > const & rRequest) throw (com::sun::star::uno::RuntimeException); static com::sun::star::uno::Sequence< rtl::OUString > getSupportedServiceNames_static(); static com::sun::star::uno::Reference< com::sun::star::uno::XInterface > #if SUPD >= 590 SAL_CALL #endif // SUPD 590 createInstance(com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > const &); }; #endif // UUI_IAHNDL_HXX <commit_msg>INTEGRATION: CWS supdremove (1.2.136); FILE MERGED 2007/11/16 10:23:42 vg 1.2.136.1: #i83674# cleanup: remove obsolete SUPD macro use<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: mphndl.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2008-01-07 08:43:03 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef UUI_IAHNDL_HXX #define UUI_IAHNDL_HXX #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_ #include <com/sun/star/lang/XTypeProvider.hpp> #endif #ifndef _COM_SUN_STAR_TASK_XINTERACTIONHANDLER_HPP_ #include <com/sun/star/task/XInteractionHandler.hpp> #endif #ifndef _COM_SUN_STAR_TASK_XPASSWORDCONTAINER_HPP_ #include <com/sun/star/task/XPasswordContainer.hpp> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif //============================================================================ class UUIInteractionHandler: public cppu::OWeakObject, public com::sun::star::lang::XServiceInfo, public com::sun::star::lang::XTypeProvider, public com::sun::star::task::XInteractionHandler { ::com::sun::star::uno::Reference< ::com::sun::star::task::XPasswordContainer > mPContainer; public: static sal_Char const m_aImplementationName[]; UUIInteractionHandler( com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > const & ); virtual com::sun::star::uno::Any SAL_CALL queryInterface(com::sun::star::uno::Type const & rType) throw (com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire() throw (com::sun::star::uno::RuntimeException); virtual void SAL_CALL release() throw (com::sun::star::uno::RuntimeException); virtual rtl::OUString SAL_CALL getImplementationName() throw (com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService(rtl::OUString const & rServiceName) throw (com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames() throw (com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Sequence< com::sun::star::uno::Type > SAL_CALL getTypes() throw (com::sun::star::uno::RuntimeException); virtual com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (com::sun::star::uno::RuntimeException); virtual void SAL_CALL handle(com::sun::star::uno::Reference< com::sun::star::task::XInteractionRequest > const & rRequest) throw (com::sun::star::uno::RuntimeException); static com::sun::star::uno::Sequence< rtl::OUString > getSupportedServiceNames_static(); static com::sun::star::uno::Reference< com::sun::star::uno::XInterface > SAL_CALL createInstance(com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > const &); }; #endif // UUI_IAHNDL_HXX <|endoftext|>
<commit_before>// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "session_connection.h" #include "flutter/fml/make_copyable.h" #include "lib/fidl/cpp/optional.h" #include "lib/ui/scenic/cpp/commands.h" #include "vsync_recorder.h" #include "vsync_waiter.h" namespace flutter_runner { SessionConnection::SessionConnection( std::string debug_label, fuchsia::ui::views::ViewToken view_token, fidl::InterfaceHandle<fuchsia::ui::scenic::Session> session, fml::closure session_error_callback, zx_handle_t vsync_event_handle) : debug_label_(std::move(debug_label)), session_wrapper_(session.Bind(), nullptr), root_view_(&session_wrapper_, std::move(view_token.value), debug_label), root_node_(&session_wrapper_), surface_producer_( std::make_unique<VulkanSurfaceProducer>(&session_wrapper_)), scene_update_context_(&session_wrapper_, surface_producer_.get()), vsync_event_handle_(vsync_event_handle) { session_wrapper_.set_error_handler( [callback = session_error_callback](zx_status_t status) { callback(); }); session_wrapper_.SetDebugName(debug_label_); // TODO(SCN-975): Re-enable. // view_->GetToken(std::bind(&PlatformView::ConnectSemanticsProvider, this, // std::placeholders::_1)); root_view_.AddChild(root_node_); root_node_.SetEventMask(fuchsia::ui::gfx::kMetricsEventMask | fuchsia::ui::gfx::kSizeChangeHintEventMask); // Signal is initially high indicating availability of the session. ToggleSignal(vsync_event_handle_, true); PresentSession(); } SessionConnection::~SessionConnection() = default; void SessionConnection::Present( flutter::CompositorContext::ScopedFrame& frame) { TRACE_EVENT0("gfx", "SessionConnection::Present"); TRACE_FLOW_BEGIN("gfx", "SessionConnection::PresentSession", next_present_session_trace_id_); // Throttle vsync if presentation callback is already pending. This allows // the paint tasks for this frame to execute in parallel with presentation // of last frame but still provides back-pressure to prevent us from queuing // even more work. if (presentation_callback_pending_) { present_session_pending_ = true; ToggleSignal(vsync_event_handle_, false); } else { PresentSession(); } // Flush all session ops. Paint tasks have not yet executed but those are // fenced. The compositor can start processing ops while we finalize paint // tasks. PresentSession(); // Execute paint tasks and signal fences. auto surfaces_to_submit = scene_update_context_.ExecutePaintTasks(frame); // Tell the surface producer that a present has occurred so it can perform // book-keeping on buffer caches. surface_producer_->OnSurfacesPresented(std::move(surfaces_to_submit)); } void SessionConnection::OnSessionSizeChangeHint(float width_change_factor, float height_change_factor) { surface_producer_->OnSessionSizeChangeHint(width_change_factor, height_change_factor); } void SessionConnection::EnqueueClearOps() { // We are going to be sending down a fresh node hierarchy every frame. So just // enqueue a detach op on the imported root node. session_wrapper_.Enqueue(scenic::NewDetachChildrenCmd(root_node_.id())); } void SessionConnection::PresentSession() { TRACE_EVENT0("gfx", "SessionConnection::PresentSession"); while (processed_present_session_trace_id_ < next_present_session_trace_id_) { TRACE_FLOW_END("gfx", "SessionConnection::PresentSession", processed_present_session_trace_id_); processed_present_session_trace_id_++; } TRACE_FLOW_BEGIN("gfx", "Session::Present", next_present_trace_id_); next_present_trace_id_++; // Presentation callback is pending as a result of Present() call below. presentation_callback_pending_ = true; // Flush all session ops. Paint tasks may not yet have executed but those are // fenced. The compositor can start processing ops while we finalize paint // tasks. session_wrapper_.Present( 0, // presentation_time. (placeholder). [this, handle = vsync_event_handle_]( fuchsia::images::PresentationInfo presentation_info) { presentation_callback_pending_ = false; VsyncRecorder::GetInstance().UpdateVsyncInfo(presentation_info); // Process pending PresentSession() calls. if (present_session_pending_) { present_session_pending_ = false; PresentSession(); } ToggleSignal(handle, true); } // callback ); // Prepare for the next frame. These ops won't be processed till the next // present. EnqueueClearOps(); } void SessionConnection::ToggleSignal(zx_handle_t handle, bool set) { const auto signal = VsyncWaiter::SessionPresentSignal; auto status = zx_object_signal(handle, // handle set ? 0 : signal, // clear mask set ? signal : 0 // set mask ); if (status != ZX_OK) { FML_LOG(ERROR) << "Could not toggle vsync signal: " << set; } } } // namespace flutter_runner <commit_msg>[b/139487101] Dont present session twice (#11222)<commit_after>// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "session_connection.h" #include "flutter/fml/make_copyable.h" #include "lib/fidl/cpp/optional.h" #include "lib/ui/scenic/cpp/commands.h" #include "vsync_recorder.h" #include "vsync_waiter.h" namespace flutter_runner { SessionConnection::SessionConnection( std::string debug_label, fuchsia::ui::views::ViewToken view_token, fidl::InterfaceHandle<fuchsia::ui::scenic::Session> session, fml::closure session_error_callback, zx_handle_t vsync_event_handle) : debug_label_(std::move(debug_label)), session_wrapper_(session.Bind(), nullptr), root_view_(&session_wrapper_, std::move(view_token.value), debug_label), root_node_(&session_wrapper_), surface_producer_( std::make_unique<VulkanSurfaceProducer>(&session_wrapper_)), scene_update_context_(&session_wrapper_, surface_producer_.get()), vsync_event_handle_(vsync_event_handle) { session_wrapper_.set_error_handler( [callback = session_error_callback](zx_status_t status) { callback(); }); session_wrapper_.SetDebugName(debug_label_); // TODO(SCN-975): Re-enable. // view_->GetToken(std::bind(&PlatformView::ConnectSemanticsProvider, this, // std::placeholders::_1)); root_view_.AddChild(root_node_); root_node_.SetEventMask(fuchsia::ui::gfx::kMetricsEventMask | fuchsia::ui::gfx::kSizeChangeHintEventMask); // Signal is initially high indicating availability of the session. ToggleSignal(vsync_event_handle_, true); PresentSession(); } SessionConnection::~SessionConnection() = default; void SessionConnection::Present( flutter::CompositorContext::ScopedFrame& frame) { TRACE_EVENT0("gfx", "SessionConnection::Present"); TRACE_FLOW_BEGIN("gfx", "SessionConnection::PresentSession", next_present_session_trace_id_); next_present_session_trace_id_++; // Throttle vsync if presentation callback is already pending. This allows // the paint tasks for this frame to execute in parallel with presentation // of last frame but still provides back-pressure to prevent us from queuing // even more work. if (presentation_callback_pending_) { present_session_pending_ = true; ToggleSignal(vsync_event_handle_, false); } else { PresentSession(); } // Execute paint tasks and signal fences. auto surfaces_to_submit = scene_update_context_.ExecutePaintTasks(frame); // Tell the surface producer that a present has occurred so it can perform // book-keeping on buffer caches. surface_producer_->OnSurfacesPresented(std::move(surfaces_to_submit)); } void SessionConnection::OnSessionSizeChangeHint(float width_change_factor, float height_change_factor) { surface_producer_->OnSessionSizeChangeHint(width_change_factor, height_change_factor); } void SessionConnection::EnqueueClearOps() { // We are going to be sending down a fresh node hierarchy every frame. So just // enqueue a detach op on the imported root node. session_wrapper_.Enqueue(scenic::NewDetachChildrenCmd(root_node_.id())); } void SessionConnection::PresentSession() { TRACE_EVENT0("gfx", "SessionConnection::PresentSession"); while (processed_present_session_trace_id_ < next_present_session_trace_id_) { TRACE_FLOW_END("gfx", "SessionConnection::PresentSession", processed_present_session_trace_id_); processed_present_session_trace_id_++; } TRACE_FLOW_BEGIN("gfx", "Session::Present", next_present_trace_id_); next_present_trace_id_++; // Presentation callback is pending as a result of Present() call below. presentation_callback_pending_ = true; // Flush all session ops. Paint tasks may not yet have executed but those are // fenced. The compositor can start processing ops while we finalize paint // tasks. session_wrapper_.Present( 0, // presentation_time. (placeholder). [this, handle = vsync_event_handle_]( fuchsia::images::PresentationInfo presentation_info) { presentation_callback_pending_ = false; VsyncRecorder::GetInstance().UpdateVsyncInfo(presentation_info); // Process pending PresentSession() calls. if (present_session_pending_) { present_session_pending_ = false; PresentSession(); } ToggleSignal(handle, true); } // callback ); // Prepare for the next frame. These ops won't be processed till the next // present. EnqueueClearOps(); } void SessionConnection::ToggleSignal(zx_handle_t handle, bool set) { const auto signal = VsyncWaiter::SessionPresentSignal; auto status = zx_object_signal(handle, // handle set ? 0 : signal, // clear mask set ? signal : 0 // set mask ); if (status != ZX_OK) { FML_LOG(ERROR) << "Could not toggle vsync signal: " << set; } } } // namespace flutter_runner <|endoftext|>
<commit_before>// // Copyright (C) 2007-2010 SIPez LLC. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Keith Kyzivat <kkyzivat AT SIPez DOT com> #include <os/OsIntTypes.h> #include <sipxunittests.h> #include <mp/MpBufPool.h> #include <mp/MpArrayBuf.h> #include <mp/MpAudioBuf.h> #include <mp/MpInputDeviceManager.h> #ifdef WIN32 #include <mp/MpidWinMM.h> #elif defined __linux__ #include <mp/MpidOss.h> #elif defined __APPLE__ #include <mp/MpidCoreAudio.h> #else #include <mp/MpSineWaveGeneratorDeviceDriver.h> #endif #include <os/OsTask.h> #include <utl/UtlString.h> #define MIDDT_SAMPLES_PER_FRAME 80 #define MIDDT_NBUFS 20 class MpInputDeviceDriverTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(MpInputDeviceDriverTest); CPPUNIT_TEST(testSetup); CPPUNIT_TEST_SUITE_END(); private: MpBufPool* mpBufPool; MpBufPool* mpHeadersPool; int mNumBufferedFrames; unsigned int mSamplesPerSecond; unsigned int mFramePeriodMSecs; public: void setUp() { mpBufPool = new MpBufPool(MIDDT_SAMPLES_PER_FRAME * sizeof(MpAudioSample) + MpArrayBuf::getHeaderSize(), MIDDT_NBUFS); CPPUNIT_ASSERT(mpBufPool != NULL); // Create pool for buffer headers mpHeadersPool = new MpBufPool(sizeof(MpAudioBuf), MIDDT_NBUFS); CPPUNIT_ASSERT(mpHeadersPool != NULL); // Set mpHeadersPool as default pool for audio and data pools. MpAudioBuf::smpDefaultPool = mpHeadersPool; MpDataBuf::smpDefaultPool = mpHeadersPool; mNumBufferedFrames = 5; mSamplesPerSecond = 8000; mFramePeriodMSecs = MIDDT_SAMPLES_PER_FRAME * 1000 / mSamplesPerSecond; } void testSetup() { MpInputDeviceManager inDevMgr(MIDDT_SAMPLES_PER_FRAME, mSamplesPerSecond, mNumBufferedFrames, *mpBufPool); // Buffer for recorded data. MpAudioSample* pRecordBuffer = new MpAudioSample[mNumBufferedFrames* MIDDT_SAMPLES_PER_FRAME]; int pRecordBufferPointer = 0; MpInputDeviceDriver* pInDevDriver = #ifdef WIN32 new MpidWinMM(MpidWinMM::getDefaultDeviceName(), inDevMgr); #elif defined __linux__ new MpidOss("/dev/dsp", inDevMgr); #elif defined __APPLE__ new MpidCoreAudio("[default]", inDevMgr); #else new MpSineWaveGeneratorDeviceDriver("SineWaveDriver", inDevMgr, 3000, 3000, 0); #endif if (pInDevDriver != NULL) { // Verify that our device is indeed valid and, if not using the test // driver, is indeed pointing at an actual device in the OS. CPPUNIT_ASSERT(pInDevDriver->isDeviceValid()); // Since we've only just created this device, it shouldn't be enabled. CPPUNIT_ASSERT(!pInDevDriver->isEnabled()); // And shouldn't have a valid device handle/ID. CPPUNIT_ASSERT(pInDevDriver->getDeviceId() < 0); // Try to enable the device when it isn't added to a manager.. // SHOULDN'T DO THIS - Only the manager should be able to do this.. // perhaps enabling should be protected, and manager be friended? //CPPUNIT_ASSERT(iDrv->enableDevice(10,10,10) != OS_SUCCESS); // Add the device to an input manager. MpInputDeviceHandle iDrvHnd = inDevMgr.addDevice(*pInDevDriver); // Verify it has a valid handle/ID. CPPUNIT_ASSERT(iDrvHnd > 0); // Try to disable it -- this should fail, since it isn't enabled yet. // Also note that one should be disabling/enabling via the manager.. // I'm just verifying that disabling the device itself when it isn't // set up doesn't kill things. CPPUNIT_ASSERT(pInDevDriver->disableDevice() != OS_SUCCESS); // Now enable it via the manager -- this should succeed. CPPUNIT_ASSERT(inDevMgr.enableDevice(iDrvHnd) == OS_SUCCESS); int nMSPerBuffer = mNumBufferedFrames * mFramePeriodMSecs; unsigned nMSecsToRecord = 5000; double* derivs = new double[(mNumBufferedFrames-1)*(nMSecsToRecord/nMSPerBuffer)]; // Round nMSecsToRecord to nMSPerBuffer boundary. nMSecsToRecord = (nMSecsToRecord/nMSPerBuffer) * nMSPerBuffer; UtlString derivPlotStr; derivPlotStr.capacity((nMSecsToRecord/mFramePeriodMSecs) << 2); UtlString derivWAvgStr; unsigned i; for(i=0;i<(mNumBufferedFrames-1)*(nMSecsToRecord/nMSPerBuffer);i++) derivs[i] = -1; unsigned derivBufPos; unsigned derivBufSz = 0; unsigned nDerivsPerBuf = mNumBufferedFrames-1; for(i = 0, derivBufPos = 0; i < nMSecsToRecord; i = i+nMSPerBuffer, derivBufPos += nDerivsPerBuf) { // Reset nDerivsPerBuf, as getting time derivs could have changed it. nDerivsPerBuf = mNumBufferedFrames-1; // Sleep till when the input buffer should be full OsTask::delay(nMSPerBuffer); // Grab time derivative statistics.. double* curDerivFramePtr = (double*)(derivs + derivBufPos); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, inDevMgr.getTimeDerivatives(iDrvHnd, nDerivsPerBuf, curDerivFramePtr)); derivBufSz += nDerivsPerBuf; } // Define weighted average accumulator and period. double derivWeightedAverage = 0; int derivWAvgPeriod = 5; // Now that we have all the derivatives, // make a string out of em.. for(i = 0; i < derivBufSz; i++) { // Prepare the derivative line to print. # define NUMSTRSZ 32 char tmpBuf[NUMSTRSZ]; // Add derivative to our big-long string that can be used for plotting. snprintf(tmpBuf, NUMSTRSZ, "%.2f", derivs[i]); derivPlotStr.append(tmpBuf); if(i < derivBufSz-1) // While there's still one more, put a comma derivPlotStr.append(", "); if ((i != 0) && (i % derivWAvgPeriod) == 0) { // Now that we have derivWAvgPeriod samples, // calculate and assign the actual weighted average. derivWeightedAverage = derivWeightedAverage / derivWAvgPeriod; // Now append this to our weighted average string. snprintf(tmpBuf, NUMSTRSZ, "%.2f", derivWeightedAverage); derivWAvgStr.append(tmpBuf); derivWAvgStr.append(", "); // reset the weighted average collector. derivWeightedAverage = 0; } derivWeightedAverage += derivs[i]; CPPUNIT_ASSERT(derivs[i] <= 4); } // Ok, now disable it via the manager -- this time it should succeed. CPPUNIT_ASSERT(inDevMgr.disableDevice(iDrvHnd) == OS_SUCCESS); // Remove the device from the manager explicitly, // Otherwise the manager will assert fail if there are devices // still present when the manager is destroyed inDevMgr.removeDevice(iDrvHnd); // Now print out our derivative results. printf(" derivatives: %s\n", derivPlotStr.data()); printf("weighted avg: %s\n", derivWAvgStr.data()); } // if pInDevDriver != NULL } void tearDown() { if (mpBufPool != NULL) { delete mpBufPool; } if (mpHeadersPool != NULL) { delete mpHeadersPool; } } }; CPPUNIT_TEST_SUITE_REGISTRATION(MpInputDeviceDriverTest); <commit_msg>sipXmediaLibTest: Support Android in MpInputDeviceDriverTest.<commit_after>// // Copyright (C) 2007-2010 SIPez LLC. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Keith Kyzivat <kkyzivat AT SIPez DOT com> #include <os/OsIntTypes.h> #include <sipxunittests.h> #include <mp/MpBufPool.h> #include <mp/MpArrayBuf.h> #include <mp/MpAudioBuf.h> #include <mp/MpInputDeviceManager.h> #ifdef WIN32 #include <mp/MpidWinMM.h> #elif defined ANDROID #include <mp/MpidAndroid.h> #elif defined __linux__ #include <mp/MpidOss.h> #elif defined __APPLE__ #include <mp/MpidCoreAudio.h> #else #include <mp/MpSineWaveGeneratorDeviceDriver.h> #endif #include <os/OsTask.h> #include <utl/UtlString.h> #define MIDDT_SAMPLES_PER_FRAME 80 #define MIDDT_NBUFS 20 class MpInputDeviceDriverTest : public SIPX_UNIT_BASE_CLASS { CPPUNIT_TEST_SUITE(MpInputDeviceDriverTest); CPPUNIT_TEST(testSetup); CPPUNIT_TEST_SUITE_END(); private: MpBufPool* mpBufPool; MpBufPool* mpHeadersPool; int mNumBufferedFrames; unsigned int mSamplesPerSecond; unsigned int mFramePeriodMSecs; public: void setUp() { mpBufPool = new MpBufPool(MIDDT_SAMPLES_PER_FRAME * sizeof(MpAudioSample) + MpArrayBuf::getHeaderSize(), MIDDT_NBUFS); CPPUNIT_ASSERT(mpBufPool != NULL); // Create pool for buffer headers mpHeadersPool = new MpBufPool(sizeof(MpAudioBuf), MIDDT_NBUFS); CPPUNIT_ASSERT(mpHeadersPool != NULL); // Set mpHeadersPool as default pool for audio and data pools. MpAudioBuf::smpDefaultPool = mpHeadersPool; MpDataBuf::smpDefaultPool = mpHeadersPool; mNumBufferedFrames = 5; mSamplesPerSecond = 8000; mFramePeriodMSecs = MIDDT_SAMPLES_PER_FRAME * 1000 / mSamplesPerSecond; } void testSetup() { MpInputDeviceManager inDevMgr(MIDDT_SAMPLES_PER_FRAME, mSamplesPerSecond, mNumBufferedFrames, *mpBufPool); // Buffer for recorded data. MpAudioSample* pRecordBuffer = new MpAudioSample[mNumBufferedFrames* MIDDT_SAMPLES_PER_FRAME]; int pRecordBufferPointer = 0; MpInputDeviceDriver* pInDevDriver = #ifdef WIN32 new MpidWinMM(MpidWinMM::getDefaultDeviceName(), inDevMgr); #elif defined ANDROID new MpidAndroid(MpidAndroid::AUDIO_SOURCE_DEFAULT, inDevMgr); #elif defined __linux__ new MpidOss("/dev/dsp", inDevMgr); #elif defined __APPLE__ new MpidCoreAudio("[default]", inDevMgr); #else new MpSineWaveGeneratorDeviceDriver("SineWaveDriver", inDevMgr, 3000, 3000, 0); #endif if (pInDevDriver != NULL) { // Verify that our device is indeed valid and, if not using the test // driver, is indeed pointing at an actual device in the OS. CPPUNIT_ASSERT(pInDevDriver->isDeviceValid()); // Since we've only just created this device, it shouldn't be enabled. CPPUNIT_ASSERT(!pInDevDriver->isEnabled()); // And shouldn't have a valid device handle/ID. CPPUNIT_ASSERT(pInDevDriver->getDeviceId() < 0); // Try to enable the device when it isn't added to a manager.. // SHOULDN'T DO THIS - Only the manager should be able to do this.. // perhaps enabling should be protected, and manager be friended? //CPPUNIT_ASSERT(iDrv->enableDevice(10,10,10) != OS_SUCCESS); // Add the device to an input manager. MpInputDeviceHandle iDrvHnd = inDevMgr.addDevice(*pInDevDriver); // Verify it has a valid handle/ID. CPPUNIT_ASSERT(iDrvHnd > 0); // Try to disable it -- this should fail, since it isn't enabled yet. // Also note that one should be disabling/enabling via the manager.. // I'm just verifying that disabling the device itself when it isn't // set up doesn't kill things. CPPUNIT_ASSERT(pInDevDriver->disableDevice() != OS_SUCCESS); // Now enable it via the manager -- this should succeed. CPPUNIT_ASSERT(inDevMgr.enableDevice(iDrvHnd) == OS_SUCCESS); int nMSPerBuffer = mNumBufferedFrames * mFramePeriodMSecs; unsigned nMSecsToRecord = 5000; double* derivs = new double[(mNumBufferedFrames-1)*(nMSecsToRecord/nMSPerBuffer)]; // Round nMSecsToRecord to nMSPerBuffer boundary. nMSecsToRecord = (nMSecsToRecord/nMSPerBuffer) * nMSPerBuffer; UtlString derivPlotStr; derivPlotStr.capacity((nMSecsToRecord/mFramePeriodMSecs) << 2); UtlString derivWAvgStr; unsigned i; for(i=0;i<(mNumBufferedFrames-1)*(nMSecsToRecord/nMSPerBuffer);i++) derivs[i] = -1; unsigned derivBufPos; unsigned derivBufSz = 0; unsigned nDerivsPerBuf = mNumBufferedFrames-1; for(i = 0, derivBufPos = 0; i < nMSecsToRecord; i = i+nMSPerBuffer, derivBufPos += nDerivsPerBuf) { // Reset nDerivsPerBuf, as getting time derivs could have changed it. nDerivsPerBuf = mNumBufferedFrames-1; // Sleep till when the input buffer should be full OsTask::delay(nMSPerBuffer); // Grab time derivative statistics.. double* curDerivFramePtr = (double*)(derivs + derivBufPos); CPPUNIT_ASSERT_EQUAL(OS_SUCCESS, inDevMgr.getTimeDerivatives(iDrvHnd, nDerivsPerBuf, curDerivFramePtr)); derivBufSz += nDerivsPerBuf; } // Ok, now disable it via the manager -- this time it should succeed. CPPUNIT_ASSERT(inDevMgr.disableDevice(iDrvHnd) == OS_SUCCESS); // Define weighted average accumulator and period. double derivWeightedAverage = 0; int derivWAvgPeriod = 5; // Now that we have all the derivatives, // make a string out of em.. for(i = 0; i < derivBufSz; i++) { // Prepare the derivative line to print. # define NUMSTRSZ 32 char tmpBuf[NUMSTRSZ]; // Add derivative to our big-long string that can be used for plotting. snprintf(tmpBuf, NUMSTRSZ, "%.2f", derivs[i]); derivPlotStr.append(tmpBuf); if(i < derivBufSz-1) // While there's still one more, put a comma derivPlotStr.append(", "); if ((i != 0) && (i % derivWAvgPeriod) == 0) { // Now that we have derivWAvgPeriod samples, // calculate and assign the actual weighted average. derivWeightedAverage = derivWeightedAverage / derivWAvgPeriod; // Now append this to our weighted average string. snprintf(tmpBuf, NUMSTRSZ, "%.2f", derivWeightedAverage); derivWAvgStr.append(tmpBuf); derivWAvgStr.append(", "); // reset the weighted average collector. derivWeightedAverage = 0; } derivWeightedAverage += derivs[i]; CPPUNIT_ASSERT(derivs[i] <= 4); } // Remove the device from the manager explicitly, // Otherwise the manager will assert fail if there are devices // still present when the manager is destroyed inDevMgr.removeDevice(iDrvHnd); // Now print out our derivative results. printf(" derivatives: %s\n", derivPlotStr.data()); printf("weighted avg: %s\n", derivWAvgStr.data()); } // if pInDevDriver != NULL } void tearDown() { if (mpBufPool != NULL) { delete mpBufPool; } if (mpHeadersPool != NULL) { delete mpHeadersPool; } } }; CPPUNIT_TEST_SUITE_REGISTRATION(MpInputDeviceDriverTest); <|endoftext|>
<commit_before>/* Copyright 2016 Stanford University * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cstdio> #include <cassert> #include <cstdlib> #include "legion.h" <<<<<<< HEAD #include "wrapper_mapper.h" #include "default_mapper.h" using namespace LegionRuntime::HighLevel; ======= using namespace Legion; >>>>>>> master /* * To illustrate task launches and futures in Legion * we implement a program to compute the first N * Fibonacci numbers. While we note that this is not * the fastest way to compute Fibonacci numbers, it * is designed to showcase the functional nature of * Legion tasks and futures. */ enum TaskIDs { TOP_LEVEL_TASK_ID, FIBONACCI_TASK_ID, SUM_TASK_ID, }; void mapper_registration(Machine machine, HighLevelRuntime *rt, const std::set<Processor> &local_procs) { for (std::set<Processor>::const_iterator it = local_procs.begin(); it != local_procs.end(); it++) { rt->replace_default_mapper( new Legion::Mapping::WrapperMapper(new DefaultMapper(machine, *it) ,machine, *it), *it); } } void top_level_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime *runtime) { int num_fibonacci = 7; // The command line arguments to a Legion application are // available through the runtime 'get_input_args' call. We'll // use this to get the number of Fibonacci numbers to compute. const InputArgs &command_args = Runtime::get_input_args(); if (command_args.argc > 1) { num_fibonacci = atoi(command_args.argv[1]); assert(num_fibonacci >= 0); } printf("Computing the first %d Fibonacci numbers...\n", num_fibonacci); // This is a vector which we'll use to store the future // results of all the tasks that we launch. The goal here // is to launch all of our tasks up front to get them in // flight before waiting on a future value. This exposes // as many tasks as possible to the Legion runtime to // maximize performance. std::vector<Future> fib_results; // Compute the first num_fibonacci numbers for (int i = 0; i < num_fibonacci; i++) { // All Legion tasks are spawned from a launcher object. A // 'TaskLauncher' is a struct used for specifying the arguments // necessary for launching a task. Launchers contain many // fields which we will explore throughout the examples. Here // we look at the first two arguments: the ID of the kind of // task to launch and a 'TaskArgument'. The ID of the task // must correspond to one of the IDs registered with the Legion // runtime before the application began. A 'TaskArgument' points // to a buffer and specifies the size in bytes to copy by value // from the buffer. It is important to note that this buffer is // not actually copied until 'execute_task' is called. The buffer // should remain live until the launcher goes out of scope. TaskLauncher launcher(FIBONACCI_TASK_ID, TaskArgument(&i,sizeof(i))); // To launch a task, a TaskLauncher object is passed to the runtime // along with the context. Legion tasks are asynchronous which means // that this call returns immediately and returns a future value which // we store in our vector of future results. Note that launchers can // be reused to launch as many tasks as desired, and can be modified // immediately after the 'execute_task' call returns. fib_results.push_back(runtime->execute_task(ctx, launcher)); } // Print out our results for (int i = 0; i < num_fibonacci; i++) { // One way to use a future is to explicitly ask for its value using // the 'get_result' method. This is a blocking call which will cause // this task (the top-level task) to pause until the sub-task which // is generating the future returns. Note that waiting on a future // that is not ready blocks this task, but does not block the processor // on which the task is running. If additional tasks have been mapped // onto this processor and they are ready to execute, then they will // begin running as soon as the call to 'get_result' is made. // // The 'get_result' method is templated on the type of the return // value which tells the Legion runtime how to interpret the bits // being returned. In most cases the bits are cast, however, if // the type passed in the template has the methods 'legion_buffer_size', // 'legion_serialize', and 'legion_deserialize' defined, then Legion // automatically supports deep copies of more complex types (see the // ColoringSerializer class in legion.h for an example). While this // way of using features requires blocking this task, we examine a // non-blocking way of using future below. int result = fib_results[i].get_result<int>(); printf("Fibonacci(%d) = %d\n", i, result); } // Implementation detail for those who are interested: since futures // are shared between the runtime and the application, we reference // count them and automatically delete their resources when there // are no longer any references to them. The 'Future' type is // actually a light-weight handle which simply contains a pointer // to the actual future implementation, so copying future values // around is inexpensive. Here we explicitly clear the vector // which invokes the Future destructor and removes the references. // This would have happened anyway when the vector went out of // scope, but we have the statement so we could put this comment here. fib_results.clear(); } int fibonacci_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime *runtime) { // The 'TaskArgument' value passed to a task and its size // in bytes is available in the 'args' and 'arglen' fields // on the 'Task' object. // // Since there is no type checking when writing to // the runtime API (a benefit provided by our Legion compiler) // we encourage programmers to check that they are getting // what they expect in their values. assert(task->arglen == sizeof(int)); int fib_num = *(const int*)task->args; // Fibonacci base cases // Note that tasks return values the same as C functions. // If a task is running remotely from its parent task then // Legion automatically packages up the result and returns // it to the origin location. if (fib_num == 0) return 0; if (fib_num == 1) return 1; // Launch fib-1 const int fib1 = fib_num-1; TaskLauncher t1(FIBONACCI_TASK_ID, TaskArgument(&fib1,sizeof(fib1))); Future f1 = runtime->execute_task(ctx, t1); // Launch fib-2 const int fib2 = fib_num-2; TaskLauncher t2(FIBONACCI_TASK_ID, TaskArgument(&fib2,sizeof(fib2))); Future f2 = runtime->execute_task(ctx, t2); // Here will illustrate a non-blocking way of using a future. // Rather than waiting for the values and passing the results // directly to the summation task, we instead pass the futures // through the TaskLauncher object. Legion then will // ensure that the sum task does not begin until both futures // are ready and that the future values are available wherever // the sum task is run (even if it is run remotely). Futures // should NEVER be passed through a TaskArgument. TaskLauncher sum(SUM_TASK_ID, TaskArgument(NULL, 0)); sum.add_future(f1); sum.add_future(f2); Future result = runtime->execute_task(ctx, sum); // Our API does not permit returning Futures as the result of // a task. Any attempt to do so will result in a failed static // assertion at compile-time. In general, waiting for one or // more futures at the end of a task is inexpensive since we // have already exposed the available sub-tasks for execution // to the Legion runtime so we can extract as much task-level // parallelism as possible from the application. return result.get_result<int>(); } int sum_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime *runtime) { assert(task->futures.size() == 2); // Note that even though it looks like we are performing // blocking calls to get these future results, the // Legion runtime is smart enough to not run this task // until all the future values passed through the // task launcher have completed. Future f1 = task->futures[0]; int r1 = f1.get_result<int>(); Future f2 = task->futures[1]; int r2 = f2.get_result<int>(); return (r1 + r2); } int main(int argc, char **argv) { Runtime::set_top_level_task_id(TOP_LEVEL_TASK_ID); Runtime::register_legion_task<top_level_task>(TOP_LEVEL_TASK_ID, Processor::LOC_PROC, true/*single*/, false/*index*/); // Note that tasks which return values must pass the type of // the return argument as the first template paramenter. Runtime::register_legion_task<int,fibonacci_task>(FIBONACCI_TASK_ID, Processor::LOC_PROC, true/*single*/, false/*index*/); // The sum-task has a very special property which is that it is // guaranteed never to make any runtime calls. We call these // kinds of tasks "leaf" tasks and tell the runtime system // about them using the 'TaskConfigOptions' struct. Being // a leaf task allows the runtime to perform significant // optimizations that minimize the overhead of leaf task // execution. Note that we also tell the runtime to // automatically generate the variant ID for this task // with the 'AUTO_GENERATE_ID' argument. Runtime::register_legion_task<int,sum_task>(SUM_TASK_ID, Processor::LOC_PROC, true/*single*/, false/*index*/, AUTO_GENERATE_ID, TaskConfigOptions(true/*leaf*/), "sum_task"); <<<<<<< HEAD HighLevelRuntime::set_registration_callback(mapper_registration); return HighLevelRuntime::start(argc, argv); ======= return Runtime::start(argc, argv); >>>>>>> master } <commit_msg>trying to convert to the latest mapper interface<commit_after>/* Copyright 2016 Stanford University * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cstdio> #include <cassert> #include <cstdlib> #include "legion.h" #include "default_mapper.h" using namespace Legion; /* * To illustrate task launches and futures in Legion * we implement a program to compute the first N * Fibonacci numbers. While we note that this is not * the fastest way to compute Fibonacci numbers, it * is designed to showcase the functional nature of * Legion tasks and futures. */ enum TaskIDs { TOP_LEVEL_TASK_ID, FIBONACCI_TASK_ID, SUM_TASK_ID, }; void top_level_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime *runtime) { int num_fibonacci = 7; // The command line arguments to a Legion application are // available through the runtime 'get_input_args' call. We'll // use this to get the number of Fibonacci numbers to compute. const InputArgs &command_args = Runtime::get_input_args(); if (command_args.argc > 1) { num_fibonacci = atoi(command_args.argv[1]); assert(num_fibonacci >= 0); } printf("Computing the first %d Fibonacci numbers...\n", num_fibonacci); // This is a vector which we'll use to store the future // results of all the tasks that we launch. The goal here // is to launch all of our tasks up front to get them in // flight before waiting on a future value. This exposes // as many tasks as possible to the Legion runtime to // maximize performance. std::vector<Future> fib_results; // Compute the first num_fibonacci numbers for (int i = 0; i < num_fibonacci; i++) { // All Legion tasks are spawned from a launcher object. A // 'TaskLauncher' is a struct used for specifying the arguments // necessary for launching a task. Launchers contain many // fields which we will explore throughout the examples. Here // we look at the first two arguments: the ID of the kind of // task to launch and a 'TaskArgument'. The ID of the task // must correspond to one of the IDs registered with the Legion // runtime before the application began. A 'TaskArgument' points // to a buffer and specifies the size in bytes to copy by value // from the buffer. It is important to note that this buffer is // not actually copied until 'execute_task' is called. The buffer // should remain live until the launcher goes out of scope. TaskLauncher launcher(FIBONACCI_TASK_ID, TaskArgument(&i,sizeof(i))); // To launch a task, a TaskLauncher object is passed to the runtime // along with the context. Legion tasks are asynchronous which means // that this call returns immediately and returns a future value which // we store in our vector of future results. Note that launchers can // be reused to launch as many tasks as desired, and can be modified // immediately after the 'execute_task' call returns. fib_results.push_back(runtime->execute_task(ctx, launcher)); } // Print out our results for (int i = 0; i < num_fibonacci; i++) { // One way to use a future is to explicitly ask for its value using // the 'get_result' method. This is a blocking call which will cause // this task (the top-level task) to pause until the sub-task which // is generating the future returns. Note that waiting on a future // that is not ready blocks this task, but does not block the processor // on which the task is running. If additional tasks have been mapped // onto this processor and they are ready to execute, then they will // begin running as soon as the call to 'get_result' is made. // // The 'get_result' method is templated on the type of the return // value which tells the Legion runtime how to interpret the bits // being returned. In most cases the bits are cast, however, if // the type passed in the template has the methods 'legion_buffer_size', // 'legion_serialize', and 'legion_deserialize' defined, then Legion // automatically supports deep copies of more complex types (see the // ColoringSerializer class in legion.h for an example). While this // way of using features requires blocking this task, we examine a // non-blocking way of using future below. int result = fib_results[i].get_result<int>(); printf("Fibonacci(%d) = %d\n", i, result); } // Implementation detail for those who are interested: since futures // are shared between the runtime and the application, we reference // count them and automatically delete their resources when there // are no longer any references to them. The 'Future' type is // actually a light-weight handle which simply contains a pointer // to the actual future implementation, so copying future values // around is inexpensive. Here we explicitly clear the vector // which invokes the Future destructor and removes the references. // This would have happened anyway when the vector went out of // scope, but we have the statement so we could put this comment here. fib_results.clear(); } int fibonacci_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime *runtime) { // The 'TaskArgument' value passed to a task and its size // in bytes is available in the 'args' and 'arglen' fields // on the 'Task' object. // // Since there is no type checking when writing to // the runtime API (a benefit provided by our Legion compiler) // we encourage programmers to check that they are getting // what they expect in their values. assert(task->arglen == sizeof(int)); int fib_num = *(const int*)task->args; // Fibonacci base cases // Note that tasks return values the same as C functions. // If a task is running remotely from its parent task then // Legion automatically packages up the result and returns // it to the origin location. if (fib_num == 0) return 0; if (fib_num == 1) return 1; // Launch fib-1 const int fib1 = fib_num-1; TaskLauncher t1(FIBONACCI_TASK_ID, TaskArgument(&fib1,sizeof(fib1))); Future f1 = runtime->execute_task(ctx, t1); // Launch fib-2 const int fib2 = fib_num-2; TaskLauncher t2(FIBONACCI_TASK_ID, TaskArgument(&fib2,sizeof(fib2))); Future f2 = runtime->execute_task(ctx, t2); // Here will illustrate a non-blocking way of using a future. // Rather than waiting for the values and passing the results // directly to the summation task, we instead pass the futures // through the TaskLauncher object. Legion then will // ensure that the sum task does not begin until both futures // are ready and that the future values are available wherever // the sum task is run (even if it is run remotely). Futures // should NEVER be passed through a TaskArgument. TaskLauncher sum(SUM_TASK_ID, TaskArgument(NULL, 0)); sum.add_future(f1); sum.add_future(f2); Future result = runtime->execute_task(ctx, sum); // Our API does not permit returning Futures as the result of // a task. Any attempt to do so will result in a failed static // assertion at compile-time. In general, waiting for one or // more futures at the end of a task is inexpensive since we // have already exposed the available sub-tasks for execution // to the Legion runtime so we can extract as much task-level // parallelism as possible from the application. return result.get_result<int>(); } int sum_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime *runtime) { assert(task->futures.size() == 2); // Note that even though it looks like we are performing // blocking calls to get these future results, the // Legion runtime is smart enough to not run this task // until all the future values passed through the // task launcher have completed. Future f1 = task->futures[0]; int r1 = f1.get_result<int>(); Future f2 = task->futures[1]; int r2 = f2.get_result<int>(); return (r1 + r2); } int main(int argc, char **argv) { Runtime::set_top_level_task_id(TOP_LEVEL_TASK_ID); Runtime::register_legion_task<top_level_task>(TOP_LEVEL_TASK_ID, Processor::LOC_PROC, true/*single*/, false/*index*/); // Note that tasks which return values must pass the type of // the return argument as the first template paramenter. Runtime::register_legion_task<int,fibonacci_task>(FIBONACCI_TASK_ID, Processor::LOC_PROC, true/*single*/, false/*index*/); // The sum-task has a very special property which is that it is // guaranteed never to make any runtime calls. We call these // kinds of tasks "leaf" tasks and tell the runtime system // about them using the 'TaskConfigOptions' struct. Being // a leaf task allows the runtime to perform significant // optimizations that minimize the overhead of leaf task // execution. Note that we also tell the runtime to // automatically generate the variant ID for this task // with the 'AUTO_GENERATE_ID' argument. Runtime::register_legion_task<int,sum_task>(SUM_TASK_ID, Processor::LOC_PROC, true/*single*/, false/*index*/, AUTO_GENERATE_ID, TaskConfigOptions(true/*leaf*/), "sum_task"); return Runtime::start(argc, argv); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QLabel> #include <QPainter> #include <QPushButton> #include <QApplication> #include <QGraphicsView> #include <QGraphicsScene> #include <QGraphicsWidget> #include <QGraphicsProxyWidget> #include <QGraphicsAnchorLayout> #include <QGraphicsSceneResizeEvent> class PixmapWidget : public QGraphicsLayoutItem { public: PixmapWidget(const QPixmap &pix) : QGraphicsLayoutItem() { original = new QGraphicsPixmapItem(pix); setGraphicsItem(original); original->show(); r = QRectF(QPointF(0, 0), pix.size()); } ~PixmapWidget() { setGraphicsItem(0); delete original; } void setZValue(qreal z) { original->setZValue(z); } void setGeometry (const QRectF &rect) { original->scale(rect.width() / r.width(), rect.height() / r.height()); original->setPos(rect.x(), rect.y()); r = rect; } protected: QSizeF sizeHint(Qt::SizeHint which, const QSizeF &constraint = QSizeF()) const { Q_UNUSED(constraint); QSizeF sh; switch (which) { case Qt::MinimumSize: sh = QSizeF(0, 0); break; case Qt::PreferredSize: sh = QSizeF(50, 50); break; case Qt::MaximumSize: sh = QSizeF(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX); break; } return sh; } private: QGraphicsPixmapItem *original; QRectF r; }; class PlaceWidget : public QGraphicsWidget { Q_OBJECT public: PlaceWidget(const QPixmap &pix) : QGraphicsWidget(), original(pix), scaled(pix) { } void paint(QPainter *painter, const QStyleOptionGraphicsItem*, QWidget*) { QPointF reflection = QPointF(); reflection.setY(scaled.height() + 2); painter->drawPixmap(QPointF(), scaled); QPixmap tmp(scaled.size()); QPainter p(&tmp); // create gradient QPoint p1(scaled.width() / 2, 0); QPoint p2(scaled.width() / 2, scaled.height()); QLinearGradient linearGrad(p1, p2); linearGrad.setColorAt(0, QColor(0, 0, 0, 0)); linearGrad.setColorAt(0.65, QColor(0, 0, 0, 127)); linearGrad.setColorAt(1, QColor(0, 0, 0, 255)); // apply 'mask' p.setBrush(linearGrad); p.fillRect(0, 0, tmp.width(), tmp.height(), QBrush(linearGrad)); p.fillRect(0, 0, tmp.width(), tmp.height(), QBrush(linearGrad)); // paint the image flipped p.setCompositionMode(QPainter::CompositionMode_DestinationOver); p.drawPixmap(0, 0, QPixmap::fromImage(scaled.toImage().mirrored(false, true))); p.end(); painter->drawPixmap(reflection, tmp); } void resizeEvent(QGraphicsSceneResizeEvent *event) { QSize newSize = event->newSize().toSize(); newSize.setHeight(newSize.height() / 2); scaled = original.scaled(newSize); } QRectF boundingRect() const { QSize size(scaled.width(), scaled.height() * 2 + 2); return QRectF(QPointF(0, 0), size); } private: QPixmap original; QPixmap scaled; }; static QGraphicsProxyWidget *createItem(const QString &name = "Unnamed") { QGraphicsProxyWidget *w = new QGraphicsProxyWidget; w->setWidget(new QPushButton(name)); w->setData(0, name); w->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); return w; } int main(int argc, char **argv) { Q_INIT_RESOURCE(weatheranchorlayout); QApplication app(argc, argv); QGraphicsScene scene; scene.setSceneRect(0, 0, 800, 480); #ifdef DEBUG_MODE QGraphicsProxyWidget *title = createItem("Title"); QGraphicsProxyWidget *place = createItem("Place"); QGraphicsProxyWidget *sun = createItem("Sun"); QGraphicsProxyWidget *details = createItem("Details"); QGraphicsProxyWidget *tabbar = createItem("Tabbar"); #else // pixmaps widgets PixmapWidget *title = new PixmapWidget(QPixmap(":/images/title.jpg")); PlaceWidget *place = new PlaceWidget(QPixmap(":/images/place.jpg")); PixmapWidget *details = new PixmapWidget(QPixmap(":/images/5days.jpg")); PixmapWidget *sun = new PixmapWidget(QPixmap(":/images/weather-few-clouds.png")); PixmapWidget *tabbar = new PixmapWidget(QPixmap(":/images/tabbar.jpg")); #endif // setup sizes title->setPreferredSize(QSizeF(348, 45)); title->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); place->setPreferredSize(QSizeF(96, 72)); place->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); details->setMinimumSize(QSizeF(200, 112)); details->setPreferredSize(QSizeF(200, 112)); details->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); tabbar->setPreferredSize(QSizeF(70, 24)); tabbar->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); sun->setPreferredSize(QSizeF(128, 97)); sun->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); sun->setZValue(9999); // start anchor layout QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout; l->setSpacing(0); // setup the main widget QGraphicsWidget *w = new QGraphicsWidget(0, Qt::Window); QPalette p; p.setColor(QPalette::Window, Qt::black); w->setPalette(p); w->setPos(20, 20); w->setLayout(l); // vertical anchors QGraphicsAnchor *anchor = l->addAnchor(title, Qt::AnchorTop, l, Qt::AnchorTop); anchor = l->addAnchor(place, Qt::AnchorTop, title, Qt::AnchorBottom); anchor->setSpacing(12); anchor = l->addAnchor(place, Qt::AnchorBottom, l, Qt::AnchorBottom); anchor->setSpacing(12); anchor = l->addAnchor(sun, Qt::AnchorTop, title, Qt::AnchorTop); anchor = l->addAnchor(sun, Qt::AnchorBottom, l, Qt::AnchorVerticalCenter); anchor = l->addAnchor(tabbar, Qt::AnchorTop, title, Qt::AnchorBottom); anchor->setSpacing(5); anchor = l->addAnchor(details, Qt::AnchorTop, tabbar, Qt::AnchorBottom); anchor->setSpacing(2); anchor = l->addAnchor(details, Qt::AnchorBottom, l, Qt::AnchorBottom); anchor->setSpacing(12); // horizontal anchors anchor = l->addAnchor(l, Qt::AnchorLeft, title, Qt::AnchorLeft); anchor = l->addAnchor(title, Qt::AnchorRight, l, Qt::AnchorRight); anchor = l->addAnchor(place, Qt::AnchorLeft, l, Qt::AnchorLeft); anchor->setSpacing(15); anchor = l->addAnchor(place, Qt::AnchorRight, details, Qt::AnchorLeft); anchor->setSpacing(35); anchor = l->addAnchor(sun, Qt::AnchorLeft, place, Qt::AnchorHorizontalCenter); anchor = l->addAnchor(sun, Qt::AnchorRight, l, Qt::AnchorHorizontalCenter); anchor = l->addAnchor(tabbar, Qt::AnchorHorizontalCenter, details, Qt::AnchorHorizontalCenter); anchor = l->addAnchor(details, Qt::AnchorRight, l, Qt::AnchorRight); // QGV setup scene.addItem(w); scene.setBackgroundBrush(Qt::white); QGraphicsView *view = new QGraphicsView(&scene); view->show(); return app.exec(); } #include "main.moc" <commit_msg>Make sure the pixmap is properly initialized.<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QLabel> #include <QPainter> #include <QPushButton> #include <QApplication> #include <QGraphicsView> #include <QGraphicsScene> #include <QGraphicsWidget> #include <QGraphicsProxyWidget> #include <QGraphicsAnchorLayout> #include <QGraphicsSceneResizeEvent> class PixmapWidget : public QGraphicsLayoutItem { public: PixmapWidget(const QPixmap &pix) : QGraphicsLayoutItem() { original = new QGraphicsPixmapItem(pix); setGraphicsItem(original); original->show(); r = QRectF(QPointF(0, 0), pix.size()); } ~PixmapWidget() { setGraphicsItem(0); delete original; } void setZValue(qreal z) { original->setZValue(z); } void setGeometry (const QRectF &rect) { original->scale(rect.width() / r.width(), rect.height() / r.height()); original->setPos(rect.x(), rect.y()); r = rect; } protected: QSizeF sizeHint(Qt::SizeHint which, const QSizeF &constraint = QSizeF()) const { Q_UNUSED(constraint); QSizeF sh; switch (which) { case Qt::MinimumSize: sh = QSizeF(0, 0); break; case Qt::PreferredSize: sh = QSizeF(50, 50); break; case Qt::MaximumSize: sh = QSizeF(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX); break; } return sh; } private: QGraphicsPixmapItem *original; QRectF r; }; class PlaceWidget : public QGraphicsWidget { Q_OBJECT public: PlaceWidget(const QPixmap &pix) : QGraphicsWidget(), original(pix), scaled(pix) { } void paint(QPainter *painter, const QStyleOptionGraphicsItem*, QWidget*) { QPointF reflection = QPointF(); reflection.setY(scaled.height() + 2); painter->drawPixmap(QPointF(), scaled); QPixmap tmp(scaled.size()); tmp.fill(Qt::transparent); QPainter p(&tmp); // create gradient QPoint p1(scaled.width() / 2, 0); QPoint p2(scaled.width() / 2, scaled.height()); QLinearGradient linearGrad(p1, p2); linearGrad.setColorAt(0, QColor(0, 0, 0, 0)); linearGrad.setColorAt(0.65, QColor(0, 0, 0, 127)); linearGrad.setColorAt(1, QColor(0, 0, 0, 255)); // apply 'mask' p.setBrush(linearGrad); p.fillRect(0, 0, tmp.width(), tmp.height(), QBrush(linearGrad)); p.fillRect(0, 0, tmp.width(), tmp.height(), QBrush(linearGrad)); // paint the image flipped p.setCompositionMode(QPainter::CompositionMode_DestinationOver); p.drawPixmap(0, 0, QPixmap::fromImage(scaled.toImage().mirrored(false, true))); p.end(); painter->drawPixmap(reflection, tmp); } void resizeEvent(QGraphicsSceneResizeEvent *event) { QSize newSize = event->newSize().toSize(); newSize.setHeight(newSize.height() / 2); scaled = original.scaled(newSize); } QRectF boundingRect() const { QSize size(scaled.width(), scaled.height() * 2 + 2); return QRectF(QPointF(0, 0), size); } private: QPixmap original; QPixmap scaled; }; static QGraphicsProxyWidget *createItem(const QString &name = "Unnamed") { QGraphicsProxyWidget *w = new QGraphicsProxyWidget; w->setWidget(new QPushButton(name)); w->setData(0, name); w->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); return w; } int main(int argc, char **argv) { Q_INIT_RESOURCE(weatheranchorlayout); QApplication app(argc, argv); QGraphicsScene scene; scene.setSceneRect(0, 0, 800, 480); #ifdef DEBUG_MODE QGraphicsProxyWidget *title = createItem("Title"); QGraphicsProxyWidget *place = createItem("Place"); QGraphicsProxyWidget *sun = createItem("Sun"); QGraphicsProxyWidget *details = createItem("Details"); QGraphicsProxyWidget *tabbar = createItem("Tabbar"); #else // pixmaps widgets PixmapWidget *title = new PixmapWidget(QPixmap(":/images/title.jpg")); PlaceWidget *place = new PlaceWidget(QPixmap(":/images/place.jpg")); PixmapWidget *details = new PixmapWidget(QPixmap(":/images/5days.jpg")); PixmapWidget *sun = new PixmapWidget(QPixmap(":/images/weather-few-clouds.png")); PixmapWidget *tabbar = new PixmapWidget(QPixmap(":/images/tabbar.jpg")); #endif // setup sizes title->setPreferredSize(QSizeF(348, 45)); title->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); place->setPreferredSize(QSizeF(96, 72)); place->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); details->setMinimumSize(QSizeF(200, 112)); details->setPreferredSize(QSizeF(200, 112)); details->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); tabbar->setPreferredSize(QSizeF(70, 24)); tabbar->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); sun->setPreferredSize(QSizeF(128, 97)); sun->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); sun->setZValue(9999); // start anchor layout QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout; l->setSpacing(0); // setup the main widget QGraphicsWidget *w = new QGraphicsWidget(0, Qt::Window); QPalette p; p.setColor(QPalette::Window, Qt::black); w->setPalette(p); w->setPos(20, 20); w->setLayout(l); // vertical anchors QGraphicsAnchor *anchor = l->addAnchor(title, Qt::AnchorTop, l, Qt::AnchorTop); anchor = l->addAnchor(place, Qt::AnchorTop, title, Qt::AnchorBottom); anchor->setSpacing(12); anchor = l->addAnchor(place, Qt::AnchorBottom, l, Qt::AnchorBottom); anchor->setSpacing(12); anchor = l->addAnchor(sun, Qt::AnchorTop, title, Qt::AnchorTop); anchor = l->addAnchor(sun, Qt::AnchorBottom, l, Qt::AnchorVerticalCenter); anchor = l->addAnchor(tabbar, Qt::AnchorTop, title, Qt::AnchorBottom); anchor->setSpacing(5); anchor = l->addAnchor(details, Qt::AnchorTop, tabbar, Qt::AnchorBottom); anchor->setSpacing(2); anchor = l->addAnchor(details, Qt::AnchorBottom, l, Qt::AnchorBottom); anchor->setSpacing(12); // horizontal anchors anchor = l->addAnchor(l, Qt::AnchorLeft, title, Qt::AnchorLeft); anchor = l->addAnchor(title, Qt::AnchorRight, l, Qt::AnchorRight); anchor = l->addAnchor(place, Qt::AnchorLeft, l, Qt::AnchorLeft); anchor->setSpacing(15); anchor = l->addAnchor(place, Qt::AnchorRight, details, Qt::AnchorLeft); anchor->setSpacing(35); anchor = l->addAnchor(sun, Qt::AnchorLeft, place, Qt::AnchorHorizontalCenter); anchor = l->addAnchor(sun, Qt::AnchorRight, l, Qt::AnchorHorizontalCenter); anchor = l->addAnchor(tabbar, Qt::AnchorHorizontalCenter, details, Qt::AnchorHorizontalCenter); anchor = l->addAnchor(details, Qt::AnchorRight, l, Qt::AnchorRight); // QGV setup scene.addItem(w); scene.setBackgroundBrush(Qt::white); QGraphicsView *view = new QGraphicsView(&scene); view->show(); return app.exec(); } #include "main.moc" <|endoftext|>
<commit_before>#include <iostream> #include <fstream> using namespace std; // This program defines a class called Inventory that has itemnumber (which // contains the id number of a product) and numofitem (which contains the // quantity on hand of the corresponding product)as private data members. // The program will read these values from a file and store them in an // array of objects (of type Inventory). It will then print these values // to the screen. // Example: Given the following data file: // 986 8 // 432 24 // This program reads these values into an array of objects and prints the // following: // Item number 986 has 8 items in stock // Item number 432 has 24 items in stock const NUMOFPROD = 10; // This holds the number of products a store sells class Inventory { public: void getId(int item); // This puts item in the private data member // itemnumber of the object that calls it. void getAmount(int num); // This puts num in the private data member // numofitem of the object that calls it. void display(); // This prints to the screen // the value of itemnumber and numofitem of the // object that calls it. private: int itemNumber; // This is an id number of the product int numOfItem; // This is the number of items in stock }; int main() { ifstream infile; // Input file to read values into array infile.open("Inventory.dat"); // Fill in the code that declares an array of objects of class Inventory // called products. The array should be of size NUMOFPROD Inventory products[NUMOFPROD] = {"Product ID", "Product Quantity"}; //Array of objects int pos; // loop counter int id; // variable holding the id number int total; // variable holding the total for each id number // Fill in the code that will read inventory numbers and number of items // from a file into the array of objects. There should be calls to both // getId and getAmount member functions somewhere in this code. // Example: products[pos].getId(id); will be somewhere in this code for(pos=0; pos<NUMOFPROD; pos++){ infile >> id; infile >> total; products[pos].getId(id); products[pos].getAmount(total); infile.getLine(); } // Fill in the code to print out the values (itemNumber and numOfItem) for // each object in the array products. // This should be done by calling the member function display within a loop for (pos = 0; pos < NUMOFPROD; pos++) { products[pos].display(); } return 0; } // Write the implementations for all the member functions of the class. void Inventory::getId(int item) { itemNumber = item; } void Inventory::getAmount(int num) { numOfItem = num; } void Inventory::display() { cout << "Item number " << products[i].getId() << " has " << products[i].getAmount() << "items in stock."; } <commit_msg>Update inventory.cpp<commit_after>#include <iostream> #include <fstream> using namespace std; // This program defines a class called Inventory that has itemnumber (which // contains the id number of a product) and numofitem (which contains the // quantity on hand of the corresponding product)as private data members. // The program will read these values from a file and store them in an // array of objects (of type Inventory). It will then print these values // to the screen. // Example: Given the following data file: // 986 8 // 432 24 // This program reads these values into an array of objects and prints the // following: // Item number 986 has 8 items in stock // Item number 432 has 24 items in stock const int NUMOFPROD = 10; // This holds the number of products a store sells class Inventory { public: void getId(int item); // This puts item in the private data member // itemnumber of the object that calls it. void getAmount(int num); // This puts num in the private data member // numofitem of the object that calls it. void display(); // This prints to the screen // the value of itemnumber and numofitem of the // object that calls it. private: int itemNumber; // This is an id number of the product int numOfItem; // This is the number of items in stock }; int main() { ifstream infile; // Input file to read values into array infile.open("Inventory.dat"); // Fill in the code that declares an array of objects of class Inventory // called products. The array should be of size NUMOFPROD Inventory products[NUMOFPROD]; //Array of objects int pos; // loop counter int id; // variable holding the id number int total; // variable holding the total for each id number // Fill in the code that will read inventory numbers and number of items // from a file into the array of objects. There should be calls to both // getId and getAmount member functions somewhere in this code. // Example: products[pos].getId(id); will be somewhere in this code for(pos=0; pos<NUMOFPROD; pos++){ infile >> id; infile >> total; products[pos].getId(id); products[pos].getAmount(total); } // Fill in the code to print out the values (itemNumber and numOfItem) for // each object in the array products. // This should be done by calling the member function display within a loop for (pos = 0; pos < NUMOFPROD; pos++) { products[pos].display(); } return 0; } // Write the implementations for all the member functions of the class. void Inventory::getId(int item) { itemNumber = item; } void Inventory::getAmount(int num) { numOfItem = num; } void Inventory::display() { cout << "Item number " << itemNumber << " has " << numOfItem << " items in stock." << endl; } <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osgUtil/Optimizer> #include <osgDB/ReadFile> #include <osg/Material> #include <osg/Geode> #include <osg/BlendFunc> #include <osg/Depth> #include <osg/Projection> #include <osg/PolygonOffset> #include <osg/MatrixTransform> #include <osg/Camera> #include <osg/FrontFace> #include <osgText/Text> #include <osgGA/TrackballManipulator> #include <osgGA/FlightManipulator> #include <osgViewer/CompositeViewer> int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // read the scene from the list of file specified commandline args. osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments); if (!scene) return 1; // construct the viewer. osgViewer::CompositeViewer viewer; if (arguments.read("-1")) { #if 1 osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface(); if (!wsi) { osg::notify(osg::NOTICE)<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl; return 1; } unsigned int width, height; wsi->getScreenResolution(osg::GraphicsContext::ScreenIdentifier(0), width, height); osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits; traits->x = 0; traits->y = 0; traits->width = width; traits->height = height; traits->windowDecoration = true; traits->doubleBuffer = true; traits->sharedContext = 0; osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get()); if (gc.valid()) { osg::notify(osg::INFO)<<" GraphicsWindow has been created successfully."<<std::endl; // need to ensure that the window is cleared make sure that the complete window is set the correct colour // rather than just the parts of the window that are under the camera's viewports gc->setClearColor(osg::Vec4f(0.2f,0.2f,0.6f,1.0f)); gc->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } else { osg::notify(osg::NOTICE)<<" GraphicsWindow has not been created successfully."<<std::endl; } osgViewer::View* view_one = new osgViewer::View; view_one->setSceneData(scene.get()); view_one->getCamera()->setViewport(new osg::Viewport(0,0, width/2, height/2)); view_one->getCamera()->setGraphicsContext(gc.get()); view_one->setCameraManipulator(new osgGA::TrackballManipulator); viewer.addView(view_one); osgViewer::View* view_two = new osgViewer::View; view_two->setSceneData(scene.get()); view_two->getCamera()->setViewport(new osg::Viewport(width/2,0, width/2, height/2)); view_two->getCamera()->setGraphicsContext(gc.get()); view_two->setCameraManipulator(new osgGA::TrackballManipulator); viewer.addView(view_two); #endif osgViewer::View* view_three = new osgViewer::View; view_three->setSceneData(osgDB::readNodeFile("town.ive")); view_three->setUpViewAcrossAllScreens(); #if 0 view_three->getCamera()->setViewport(new osg::Viewport(0, height/2, width, height/2)); view_three->getCamera()->setGraphicsContext(gc.get()); #endif view_three->setCameraManipulator(new osgGA::FlightManipulator); viewer.addView(view_three); } else { osgViewer::View* view_one = new osgViewer::View; view_one->setUpViewOnSingleScreen(0); view_one->setSceneData(scene.get()); view_one->setCameraManipulator(new osgGA::TrackballManipulator); viewer.addView(view_one); osgViewer::View* view_two = new osgViewer::View; view_two->setUpViewOnSingleScreen(1); view_two->setSceneData(scene.get()); view_two->setCameraManipulator(new osgGA::TrackballManipulator); viewer.addView(view_two); } while (arguments.read("-s")) { viewer.setThreadingModel(osgViewer::CompositeViewer::SingleThreaded); } while (arguments.read("-g")) { viewer.setThreadingModel(osgViewer::CompositeViewer::ThreadPerContext); } while (arguments.read("-c")) { viewer.setThreadingModel(osgViewer::CompositeViewer::ThreadPerCamera); } return viewer.run(); } <commit_msg>Added extra view combinations too commandline<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osgUtil/Optimizer> #include <osgDB/ReadFile> #include <osg/Material> #include <osg/Geode> #include <osg/BlendFunc> #include <osg/Depth> #include <osg/Projection> #include <osg/PolygonOffset> #include <osg/MatrixTransform> #include <osg/Camera> #include <osg/FrontFace> #include <osgText/Text> #include <osgGA/TrackballManipulator> #include <osgGA/FlightManipulator> #include <osgGA/StateSetManipulator> #include <osgViewer/CompositeViewer> int main( int argc, char **argv ) { // use an ArgumentParser object to manage the program arguments. osg::ArgumentParser arguments(&argc,argv); // read the scene from the list of file specified commandline args. osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments); if (!scene) return 1; // construct the viewer. osgViewer::CompositeViewer viewer; if (arguments.read("-1")) { osg::GraphicsContext::WindowingSystemInterface* wsi = osg::GraphicsContext::getWindowingSystemInterface(); if (!wsi) { osg::notify(osg::NOTICE)<<"Error, no WindowSystemInterface available, cannot create windows."<<std::endl; return 1; } unsigned int width, height; wsi->getScreenResolution(osg::GraphicsContext::ScreenIdentifier(0), width, height); osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits; traits->x = 0; traits->y = 0; traits->width = width; traits->height = height; traits->windowDecoration = true; traits->doubleBuffer = true; traits->sharedContext = 0; osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get()); if (gc.valid()) { osg::notify(osg::INFO)<<" GraphicsWindow has been created successfully."<<std::endl; // need to ensure that the window is cleared make sure that the complete window is set the correct colour // rather than just the parts of the window that are under the camera's viewports gc->setClearColor(osg::Vec4f(0.2f,0.2f,0.6f,1.0f)); gc->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } else { osg::notify(osg::NOTICE)<<" GraphicsWindow has not been created successfully."<<std::endl; } // view one { osgViewer::View* view = new osgViewer::View; view->setSceneData(scene.get()); view->getCamera()->setViewport(new osg::Viewport(0,0, width/2, height/2)); view->getCamera()->setGraphicsContext(gc.get()); view->setCameraManipulator(new osgGA::TrackballManipulator); viewer.addView(view); // add the state manipulator osg::ref_ptr<osgGA::StateSetManipulator> statesetManipulator = new osgGA::StateSetManipulator; statesetManipulator->setStateSet(view->getCamera()->getOrCreateStateSet()); view->addEventHandler( statesetManipulator.get() ); } // view two { osgViewer::View* view = new osgViewer::View; view->setSceneData(scene.get()); view->getCamera()->setViewport(new osg::Viewport(width/2,0, width/2, height/2)); view->getCamera()->setGraphicsContext(gc.get()); view->setCameraManipulator(new osgGA::TrackballManipulator); viewer.addView(view); } // view three if (false) { osgViewer::View* view = new osgViewer::View; view->setSceneData(osgDB::readNodeFile("town.ive")); view->setUpViewAcrossAllScreens(); viewer.addView(view); } else { osgViewer::View* view = new osgViewer::View; view->setSceneData(osgDB::readNodeFile("town.ive")); view->getCamera()->setProjectionMatrixAsPerspective(30.0, double(width) / double(height/2), 1.0, 1000.0); view->getCamera()->setViewport(new osg::Viewport(0, height/2, width, height/2)); view->getCamera()->setGraphicsContext(gc.get()); view->setCameraManipulator(new osgGA::FlightManipulator); viewer.addView(view); } } if (arguments.read("-2")) { { osgViewer::View* view = new osgViewer::View; view->setSceneData(osgDB::readNodeFile("town.ive")); view->setUpViewAcrossAllScreens(); view->setCameraManipulator(new osgGA::FlightManipulator); viewer.addView(view); } } if (arguments.read("-3") || viewer.getNumViews()==0) { // view one { osgViewer::View* view = new osgViewer::View; viewer.addView(view); view->setUpViewOnSingleScreen(0); view->setSceneData(scene.get()); view->setCameraManipulator(new osgGA::TrackballManipulator); // add the state manipulator osg::ref_ptr<osgGA::StateSetManipulator> statesetManipulator = new osgGA::StateSetManipulator; statesetManipulator->setStateSet(view->getCamera()->getOrCreateStateSet()); view->addEventHandler( statesetManipulator.get() ); } // view two { osgViewer::View* view = new osgViewer::View; viewer.addView(view); view->setUpViewOnSingleScreen(1); view->setSceneData(scene.get()); view->setCameraManipulator(new osgGA::TrackballManipulator); } } while (arguments.read("-s")) { viewer.setThreadingModel(osgViewer::CompositeViewer::SingleThreaded); } while (arguments.read("-g")) { viewer.setThreadingModel(osgViewer::CompositeViewer::ThreadPerContext); } while (arguments.read("-c")) { viewer.setThreadingModel(osgViewer::CompositeViewer::ThreadPerCamera); } return viewer.run(); } <|endoftext|>
<commit_before>#include <string> #include <iostream> #if defined(_MSC_VER) #include <SDL.h> #else #include <SDL2/SDL.h> #endif /** * Lesson 2: Don't Put Everything in Main */ //Screen attributes const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; /** * Log an SDL error with some error message to the output stream of our choice * @param os The output stream to write the message too * @param msg The error message to write, format will be msg error: SDL_GetError() */ void logSDLError(std::ostream &os, const std::string &msg){ os << msg << " error: " << SDL_GetError() << std::endl; } /** * Loads a BMP image into a texture on the rendering device * @param file The BMP image file to load * @param ren The renderer to load the texture onto * @return the loaded texture, or nullptr if something went wrong. */ SDL_Texture* loadTexture(const std::string &file, SDL_Renderer *ren){ SDL_Texture *texture = nullptr; //Load the image SDL_Surface *loadedImage = SDL_LoadBMP(file.c_str()); //If the loading went ok, convert to texture and return the texture if (loadedImage != nullptr){ texture = SDL_CreateTextureFromSurface(ren, loadedImage); SDL_FreeSurface(loadedImage); //Make sure converting went ok too if (texture == nullptr) logSDLError(std::cout, "CreateTextureFromSurface"); } else logSDLError(std::cout, "LoadBMP"); return texture; } /** * Draw an SDL_Texture to an SDL_Renderer at position x, y, preserving * the texture's width and height * @param tex The source texture we want to draw * @param rend The renderer we want to draw too * @param x The x coordinate to draw too * @param y The y coordinate to draw too */ void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, int x, int y){ //Setup the destination rectangle to be at the position we want SDL_Rect dst; dst.x = x; dst.y = y; //Query the texture to get its width and height to use SDL_QueryTexture(tex, NULL, NULL, &dst.w, &dst.h); SDL_RenderCopy(ren, tex, NULL, &dst); } int main(int argc, char** argv){ //Start up SDL and make sure it went ok if (SDL_Init(SDL_INIT_EVERYTHING) != 0){ logSDLError(std::cout, "SDL_Init"); return 1; } //Setup our window and renderer SDL_Window *window = SDL_CreateWindow("Lesson 2", 100, 100, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (window == nullptr){ logSDLError(std::cout, "CreateWindow"); return 2; } SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (renderer == nullptr){ logSDLError(std::cout, "CreateRenderer"); return 3; } //The textures we'll be using SDL_Texture *background = loadTexture("../res/Lesson2/background.bmp", renderer); SDL_Texture *image = loadTexture("../res/Lesson2/image.bmp", renderer); //Make sure they both loaded ok if (background == nullptr || image == nullptr) return 4; //Clear the window SDL_RenderClear(renderer); //Get the width and height from the texture so we know how much to move x,y by //to tile it correctly int bW, bH; SDL_QueryTexture(background, NULL, NULL, &bW, &bH); //We want to tile our background so draw it 4 times renderTexture(background, renderer, 0, 0); renderTexture(background, renderer, bW, 0); renderTexture(background, renderer, 0, bH); renderTexture(background, renderer, bW, bH); //Draw our image in the center of the window //We need the foreground image's width to properly compute the position //of it's top left corner so that the image will be centered int iW, iH; SDL_QueryTexture(image, NULL, NULL, &iW, &iH); int x = SCREEN_WIDTH / 2 - iW / 2; int y = SCREEN_HEIGHT / 2 - iH / 2; renderTexture(image, renderer, x, y); //Update the screen SDL_RenderPresent(renderer); SDL_Delay(2000); //Destroy the various items SDL_DestroyTexture(background); SDL_DestroyTexture(image); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return 0; } <commit_msg>Also need to update the comment<commit_after>#include <string> #include <iostream> #if defined(_MSC_VER) #include <SDL.h> #else #include <SDL2/SDL.h> #endif /** * Lesson 2: Don't Put Everything in Main */ //Screen attributes const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; /** * Log an SDL error with some error message to the output stream of our choice * @param os The output stream to write the message too * @param msg The error message to write, format will be msg error: SDL_GetError() */ void logSDLError(std::ostream &os, const std::string &msg){ os << msg << " error: " << SDL_GetError() << std::endl; } /** * Loads a BMP image into a texture on the rendering device * @param file The BMP image file to load * @param ren The renderer to load the texture onto * @return the loaded texture, or nullptr if something went wrong. */ SDL_Texture* loadTexture(const std::string &file, SDL_Renderer *ren){ SDL_Texture *texture = nullptr; //Load the image SDL_Surface *loadedImage = SDL_LoadBMP(file.c_str()); //If the loading went ok, convert to texture and return the texture if (loadedImage != nullptr){ texture = SDL_CreateTextureFromSurface(ren, loadedImage); SDL_FreeSurface(loadedImage); //Make sure converting went ok too if (texture == nullptr) logSDLError(std::cout, "CreateTextureFromSurface"); } else logSDLError(std::cout, "LoadBMP"); return texture; } /** * Draw an SDL_Texture to an SDL_Renderer at position x, y, preserving * the texture's width and height * @param tex The source texture we want to draw * @param ren The renderer we want to draw too * @param x The x coordinate to draw too * @param y The y coordinate to draw too */ void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, int x, int y){ //Setup the destination rectangle to be at the position we want SDL_Rect dst; dst.x = x; dst.y = y; //Query the texture to get its width and height to use SDL_QueryTexture(tex, NULL, NULL, &dst.w, &dst.h); SDL_RenderCopy(ren, tex, NULL, &dst); } int main(int argc, char** argv){ //Start up SDL and make sure it went ok if (SDL_Init(SDL_INIT_EVERYTHING) != 0){ logSDLError(std::cout, "SDL_Init"); return 1; } //Setup our window and renderer SDL_Window *window = SDL_CreateWindow("Lesson 2", 100, 100, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (window == nullptr){ logSDLError(std::cout, "CreateWindow"); return 2; } SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (renderer == nullptr){ logSDLError(std::cout, "CreateRenderer"); return 3; } //The textures we'll be using SDL_Texture *background = loadTexture("../res/Lesson2/background.bmp", renderer); SDL_Texture *image = loadTexture("../res/Lesson2/image.bmp", renderer); //Make sure they both loaded ok if (background == nullptr || image == nullptr) return 4; //Clear the window SDL_RenderClear(renderer); //Get the width and height from the texture so we know how much to move x,y by //to tile it correctly int bW, bH; SDL_QueryTexture(background, NULL, NULL, &bW, &bH); //We want to tile our background so draw it 4 times renderTexture(background, renderer, 0, 0); renderTexture(background, renderer, bW, 0); renderTexture(background, renderer, 0, bH); renderTexture(background, renderer, bW, bH); //Draw our image in the center of the window //We need the foreground image's width to properly compute the position //of it's top left corner so that the image will be centered int iW, iH; SDL_QueryTexture(image, NULL, NULL, &iW, &iH); int x = SCREEN_WIDTH / 2 - iW / 2; int y = SCREEN_HEIGHT / 2 - iH / 2; renderTexture(image, renderer, x, y); //Update the screen SDL_RenderPresent(renderer); SDL_Delay(2000); //Destroy the various items SDL_DestroyTexture(background); SDL_DestroyTexture(image); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return 0; } <|endoftext|>
<commit_before>/*------------------------------------------------------------------------- * Vulkan CTS Framework * -------------------- * * Copyright (c) 2015 Google Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and/or associated documentation files (the * "Materials"), to deal in the Materials without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Materials, and to * permit persons to whom the Materials are furnished to do so, subject to * the following conditions: * * The above copyright notice(s) and this permission notice shall be * included in all copies or substantial portions of the Materials. * * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. * *//*! * \file * \brief SPIR-V assembly to binary. *//*--------------------------------------------------------------------*/ #include "vkSpirVAsm.hpp" #include "vkSpirVProgram.hpp" #include "deArrayUtil.hpp" #include "deMemory.h" #include "deClock.h" #include "qpDebugOut.h" #if defined(DEQP_HAVE_SPIRV_TOOLS) # include "libspirv/libspirv.h" #endif namespace vk { using std::string; using std::vector; #if defined(DEQP_HAVE_SPIRV_TOOLS) void assembleSpirV (const SpirVAsmSource* program, std::vector<deUint8>* dst, SpirVProgramInfo* buildInfo) { spv_context context = spvContextCreate(); const std::string& spvSource = program->program.str(); spv_binary binary = DE_NULL; spv_diagnostic diagnostic = DE_NULL; const deUint64 compileStartTime = deGetMicroseconds(); const spv_result_t compileOk = spvTextToBinary(context, spvSource.c_str(), spvSource.size(), &binary, &diagnostic); { buildInfo->source = program; buildInfo->infoLog = diagnostic? diagnostic->error : ""; // \todo [2015-07-13 pyry] Include debug log? buildInfo->compileTimeUs = deGetMicroseconds() - compileStartTime; buildInfo->compileOk = (compileOk == SPV_SUCCESS); } if (compileOk != SPV_SUCCESS) TCU_FAIL("Failed to compile shader"); dst->resize((int)binary->wordCount * sizeof(deUint32)); #if (DE_ENDIANNESS == DE_LITTLE_ENDIAN) deMemcpy(&(*dst)[0], &binary->code[0], dst->size()); #else # error "Big-endian not supported" #endif spvBinaryDestroy(binary); spvDiagnosticDestroy(diagnostic); spvContextDestroy(context); return; } bool validateSpirV (const std::vector<deUint8>& spirv, std::string* infoLog) { const size_t bytesPerWord = sizeof(uint32_t) / sizeof(deUint8); DE_ASSERT(spirv.size() % bytesPerWord == 0); std::vector<uint32_t> words(spirv.size() / bytesPerWord); deMemcpy(words.data(), spirv.data(), spirv.size()); spv_const_binary_t cbinary = { words.data(), words.size() }; spv_diagnostic diagnostic = DE_NULL; spv_context context = spvContextCreate(); const spv_result_t valid = spvValidate(context, &cbinary, SPV_VALIDATE_ALL, &diagnostic); if (diagnostic) *infoLog += diagnostic->error; spvContextDestroy(context); spvDiagnosticDestroy(diagnostic); return valid == SPV_SUCCESS; } #else // defined(DEQP_HAVE_SPIRV_TOOLS) void assembleSpirV (const SpirVAsmSource*, std::vector<deUint8>*, SpirVProgramInfo*) { TCU_THROW(NotSupportedError, "SPIR-V assembly not supported (DEQP_HAVE_SPIRV_TOOLS not defined)"); } bool validateSpirV (std::vector<deUint8>*, std::string*) { TCU_THROW(NotSupportedError, "SPIR-V validation not supported (DEQP_HAVE_SPIRV_TOOLS not defined)"); } #endif } // vk <commit_msg>Fix debug build when spirv-tools is not available<commit_after>/*------------------------------------------------------------------------- * Vulkan CTS Framework * -------------------- * * Copyright (c) 2015 Google Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and/or associated documentation files (the * "Materials"), to deal in the Materials without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Materials, and to * permit persons to whom the Materials are furnished to do so, subject to * the following conditions: * * The above copyright notice(s) and this permission notice shall be * included in all copies or substantial portions of the Materials. * * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. * *//*! * \file * \brief SPIR-V assembly to binary. *//*--------------------------------------------------------------------*/ #include "vkSpirVAsm.hpp" #include "vkSpirVProgram.hpp" #include "deArrayUtil.hpp" #include "deMemory.h" #include "deClock.h" #include "qpDebugOut.h" #if defined(DEQP_HAVE_SPIRV_TOOLS) # include "libspirv/libspirv.h" #endif namespace vk { using std::string; using std::vector; #if defined(DEQP_HAVE_SPIRV_TOOLS) void assembleSpirV (const SpirVAsmSource* program, std::vector<deUint8>* dst, SpirVProgramInfo* buildInfo) { spv_context context = spvContextCreate(); const std::string& spvSource = program->program.str(); spv_binary binary = DE_NULL; spv_diagnostic diagnostic = DE_NULL; const deUint64 compileStartTime = deGetMicroseconds(); const spv_result_t compileOk = spvTextToBinary(context, spvSource.c_str(), spvSource.size(), &binary, &diagnostic); { buildInfo->source = program; buildInfo->infoLog = diagnostic? diagnostic->error : ""; // \todo [2015-07-13 pyry] Include debug log? buildInfo->compileTimeUs = deGetMicroseconds() - compileStartTime; buildInfo->compileOk = (compileOk == SPV_SUCCESS); } if (compileOk != SPV_SUCCESS) TCU_FAIL("Failed to compile shader"); dst->resize((int)binary->wordCount * sizeof(deUint32)); #if (DE_ENDIANNESS == DE_LITTLE_ENDIAN) deMemcpy(&(*dst)[0], &binary->code[0], dst->size()); #else # error "Big-endian not supported" #endif spvBinaryDestroy(binary); spvDiagnosticDestroy(diagnostic); spvContextDestroy(context); return; } bool validateSpirV (const std::vector<deUint8>& spirv, std::string* infoLog) { const size_t bytesPerWord = sizeof(uint32_t) / sizeof(deUint8); DE_ASSERT(spirv.size() % bytesPerWord == 0); std::vector<uint32_t> words(spirv.size() / bytesPerWord); deMemcpy(words.data(), spirv.data(), spirv.size()); spv_const_binary_t cbinary = { words.data(), words.size() }; spv_diagnostic diagnostic = DE_NULL; spv_context context = spvContextCreate(); const spv_result_t valid = spvValidate(context, &cbinary, SPV_VALIDATE_ALL, &diagnostic); if (diagnostic) *infoLog += diagnostic->error; spvContextDestroy(context); spvDiagnosticDestroy(diagnostic); return valid == SPV_SUCCESS; } #else // defined(DEQP_HAVE_SPIRV_TOOLS) void assembleSpirV (const SpirVAsmSource*, std::vector<deUint8>*, SpirVProgramInfo*) { TCU_THROW(NotSupportedError, "SPIR-V assembly not supported (DEQP_HAVE_SPIRV_TOOLS not defined)"); } bool validateSpirV (const std::vector<deUint8>&, std::string*) { TCU_THROW(NotSupportedError, "SPIR-V validation not supported (DEQP_HAVE_SPIRV_TOOLS not defined)"); } #endif } // vk <|endoftext|>
<commit_before>#include "optionshierarchy.h" #include "io.h" #include <string> #include <iostream> #include <sys/time.h> #include <typeinfo> #define DEFAULT_INT 42 #define BOOST_TEST_MODULE Something #include <boost/test/unit_test.hpp> using namespace mlpack; /* PROGRAM_INFO("MLPACK IO Test", "This is a simple test of the IO framework for input options and timers. " "This particular text can be seen if you type --help.") PARAM(int, "gint", "global desc", "global", 42, false); PARAM(int, "req", "required", "global", 23, true); PARAM_INT("something_long_long_long", "A particularly long and needlessly " "verbose description ensures that my line hyphenator is working correctly " "but to test we need a " "really_really_really_long_long_long_long_long_long_long_long_word.", "", 10); */ /** * @brief Tests that inserting elements into an OptionsHierarchy * properly updates the tree. * * @return True indicating all is well with OptionsHierarchy */ BOOST_AUTO_TEST_CASE(TestHierarchy) { bool success = true; OptionsHierarchy tmp = OptionsHierarchy("UTest"); std::string testName = std::string("UTest/test"); std::string testDesc = std::string("Test description."); std::string testTID = TYPENAME(int); //Check that the hierarchy is properly named. std::string str = std::string("UTest"); OptionsData node = tmp.GetNodeData(); BOOST_REQUIRE_EQUAL(str.compare(node.node), 0); //Check that inserting a node actually inserts the node. // Note, that since all versions of append simply call the most qualified // overload, we will only test that one. tmp.AppendNode(testName, testTID, testDesc); BOOST_REQUIRE(tmp.FindNode(testName) != NULL); //Now check that the inserted node has the correct data. OptionsHierarchy* testHierarchy = tmp.FindNode(testName); OptionsData testData; if (testHierarchy != NULL) { node = testHierarchy->GetNodeData(); BOOST_REQUIRE(testName.compare(node.node) == 0); BOOST_REQUIRE(testDesc.compare(node.desc) == 0); BOOST_REQUIRE(testTID.compare(node.tname) == 0); } else } /** * @brief Tests that IO works as intended, namely that IO::Add * propogates successfully. * * @return True indicating all is well with IO, false otherwise. */ BOOST_AUTO_TEST_CASE(TestIO) { // BOOST_REQUIRE_CLOSE(IO::GetParam<int>("global/gint") + 1e-6, // DEFAULT_INT + 1e-6, 1e-5); //Check that the IO::HasParam returns false if no value has been specified //On the commandline or programmatically. IO::Add<bool>("bool", "True or False", "global"); BOOST_REQUIRE_EQUAL(IO::HasParam("global/bool"), false); IO::GetParam<bool>("global/bool") = true; //IO::HasParam should return true now. BOOST_REQUIRE_EQUAL(IO::HasParam("global/bool"), true); BOOST_REQUIRE_EQUAL(IO::GetDescription("global/bool").compare( std::string("True or False")) , 0); //Check that SanitizeString is sanitary. std::string tmp = IO::SanitizeString("/foo/bar/fizz"); BOOST_REQUIRE_EQUAL(tmp.compare(std::string("foo/bar/fizz/")),0); //Now lets test the output functions. Will have to eyeball it manually. IO::Debug << "Test the new lines..."; IO::Debug << "shouldn't get 'Info' here." << std::endl; IO::Debug << "But now I should." << std::endl << std::endl; //Test IO::Debug IO::Debug << "You shouldn't see this when DEBUG=OFF" << std::endl; } /** * @brief Tests that the various PARAM_* macros work properly * @return True indicating that all is well with IO & Options. */ BOOST_AUTO_TEST_CASE(TestOption) { //This test will involve creating an option, and making sure IO reflects this. PARAM(int, "test", "test desc", "test_parent", DEFAULT_INT, false); //Does IO reflect this? BOOST_REQUIRE_EQUAL(IO::HasParam("test_parent/test"), true); std::string desc = std::string("test desc"); BOOST_REQUIRE(desc.compare(IO::GetDescription("test_parent/test"))==0); BOOST_REQUIRE(IO::GetParam<int>("test_parent/test") == DEFAULT_INT); } <commit_msg>-- undo changes from last build<commit_after>#include "io.h" #include "optionshierarchy.h" #include <string> #include <iostream> #include <sys/time.h> #include <typeinfo> #define DEFAULT_INT 42 // namespace mlpack { namespace io { PROGRAM_INFO("MLPACK IO Test", "This is a simple test of the IO framework for input options and timers. " "This particular text can be seen if you type --help.") PARAM(int, "gint", "global desc", "global", 42, false); PARAM(int, "req", "required", "global", 23, true); PARAM_INT("something_long_long_long", "A particularly long and needlessly " "verbose description ensures that my line hyphenator is working correctly " "but to test we need a " "really_really_really_long_long_long_long_long_long_long_long_word.", "", 10); bool ASSERT(bool expression, const char* msg); void TestAll(); bool TestHierarchy(); bool TestIO(); bool TestOption(); /** * @brief Runs all the other tests, printing output as appropriate. */ void TestAll() { IO::StartTimer("TestTimer"); if (TestIO()) IO::Info << "Test IO Succeeded." << std::endl; else IO::Fatal << "Test IO Failed." << std::endl; if (TestHierarchy()) IO::Info << "Test Hierarchy Passed." << std::endl; else IO::Fatal << "Test Hierarchy Failed." << std::endl; if (TestOption()) IO::Info << "Test Option Passed." << std::endl; else IO::Fatal << "Test Option Failed." << std::endl; IO::StopTimer("TestTimer"); IO::Info << "Elapsed uSecs: " << IO::GetParam<timeval>("TestTimer").tv_usec << std::endl; } /** * @brief Tests that IO works as intended, namely that IO::Add * propogates successfully. * * @return True indicating all is well with IO, false otherwise. */ bool TestIO() { bool success = true; success = success & ASSERT(IO::GetParam<int>("global/gint") == DEFAULT_INT, "IO::GetParam failed on gint"); //Check that the IO::HasParam returns false if no value has been specified //On the commandline or programmatically. IO::Add<bool>("bool", "True or False", "global"); success = success & ASSERT(IO::HasParam("global/bool") == false, "IO::HasParam failed on global/bool"); IO::GetParam<bool>("global/bool") = true; //IO::HasParam should return true now. success = success & ASSERT(IO::HasParam("global/bool") == true, "IO::HasParam failed on global/bool #2"); success = success & ASSERT(IO::GetParam<bool>("global/bool") == true, "IO::GetParam failed on global/bool"); success = success & ASSERT(IO::GetDescription("global/bool").compare( std::string("True or False")) == 0, "IO::GetDescription failed on global/bool"); //Check that SanitizeString is sanitary. std::string tmp = IO::SanitizeString("/foo/bar/fizz"); success = success & ASSERT(tmp.compare(std::string("foo/bar/fizz/")) == 0, "IO::SanitizeString failed on 'foo/bar/fizz'"); //Now lets test the output functions. Will have to eyeball it manually. IO::Debug << "Test the new lines..."; IO::Debug << "shouldn't get 'Info' here." << std::endl; IO::Debug << "But now I should." << std::endl << std::endl; //Test IO::Debug IO::Debug << "You shouldn't see this when DEBUG=OFF" << std::endl; return success; } /** * @brief Tests that inserting elements into an OptionsHierarchy * properly updates the tree. * * @return True indicating all is well with OptionsHierarchy */ bool TestHierarchy() { bool success = true; OptionsHierarchy tmp = OptionsHierarchy("UTest"); std::string testName = std::string("UTest/test"); std::string testDesc = std::string("Test description."); std::string testTID = TYPENAME(int); //Check that the hierarchy is properly named. std::string str = std::string("UTest"); OptionsData node = tmp.GetNodeData(); success = success & ASSERT(str.compare(node.node) == 0, "OptionsHierarchy::GetNodeData failed on UTest"); //Check that inserting a node actually inserts the node. /* Note, that since all versions of append simply call the most qualified overload, we will only test that one. */ tmp.AppendNode(testName, testTID, testDesc); success = success & ASSERT(tmp.FindNode(testName) != NULL, "OptionsHierarchy::FindNode failed on UTest/test"); //Now check that the inserted node has the correct data. OptionsHierarchy* testHierarchy = tmp.FindNode(testName); OptionsData testData; if (testHierarchy != NULL) { node = testHierarchy->GetNodeData(); success = success & ASSERT(testName.compare(node.node) == 0 && testDesc.compare(node.desc) == 0 && testTID.compare(node.tname) == 0, "OptionsHierarchy::GetNodeData failed on UTest/test"); } else success = false; return success; } /** * @brief Tests that the various PARAM_* macros work properly. * * @return True indicating that all is well with IO & Options. */ bool TestOption() { bool success = true; //This test will involve creating an option, and making sure IO reflects this. PARAM(int, "test", "test desc", "test_parent", DEFAULT_INT, false); //Does IO reflect this? success = success & ASSERT(IO::HasParam("test_parent/test"), "IO::HasParam failed on parent/test"); std::string desc = std::string("test desc"); success = success & ASSERT(desc.compare(IO::GetDescription("test_parent/test")) == 0, "IO::GetDescription fails on test_parent/test"); success = success & ASSERT(IO::GetParam<int>("test_parent/test") == DEFAULT_INT, "IO::GetParam fails on test_parent/test"); return success; } /** * @brief If the expression is true, true is returned. Otherwise * an error message is printed and failure is returned. * * @param expression The expression to be evaluated. * @param msg The error message printed on failure. * * @return True indicating success and false indicates failure. */ bool ASSERT(bool expression, const char* msg) { if (!expression) { IO::Fatal << msg << std::endl; return false; } return true; } }; //namespace io }; //namespace mlpack int main(int argc, char** argv) { mlpack::io::TestAll(); mlpack::IO::ParseCommandLine(argc, argv); mlpack::IO::Warn << "Application did not terminate..." << std::endl; } <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2009, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder(s) nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id: extract_indices.hpp 1897 2011-07-26 20:35:49Z rusu $ * */ #ifndef PCL_FILTERS_IMPL_RANDOM_SAMPLE_H_ #define PCL_FILTERS_IMPL_RANDOM_SAMPLE_H_ #include <pcl/filters/random_sample.h> #include <pcl/common/io.h> #include <pcl/point_traits.h> /////////////////////////////////////////////////////////////////////////////// template<typename PointT> void pcl::RandomSample<PointT>::applyFilter (PointCloud &output) { std::vector<int> indices; if (keep_organized_) { bool temp = extract_removed_indices_; extract_removed_indices_ = true; applyFilter (indices); extract_removed_indices_ = temp; copyPointCloud (*input_, output); // Get all floating point fields std::vector<sensor_msgs::PointField> fields; pcl::getFields (output, fields); std::vector<sensor_msgs::PointField> float_fields; for (size_t i = 0; i < fields.size (); ++i) { if (fields[i].datatype == sensor_msgs::PointField::FLOAT32) float_fields.push_back (fields[i]); } // For every "removed" point, set all floating point fields to NaN for (size_t rii = 0; rii < removed_indices_->size (); ++rii) { uint8_t* pt_data = reinterpret_cast<uint8_t*> (&output.at ((*removed_indices_)[rii])); for (size_t i = 0; i < float_fields.size (); ++i) { memcpy (pt_data + float_fields[i].offset, &user_filter_value_, sizeof (float)); } if (!pcl_isfinite (user_filter_value_)) output.is_dense = false; } } else { output.is_dense = true; applyFilter (indices); copyPointCloud (*input_, indices, output); } } /////////////////////////////////////////////////////////////////////////////// template<typename PointT> void pcl::RandomSample<PointT>::applyFilter (std::vector<int> &indices) { unsigned N = static_cast<unsigned> (indices_->size ()); float one_over_N = 1.0f / float (N); unsigned int sample_size = negative_ ? N - sample_ : sample_; // If sample size is 0 or if the sample size is greater then input cloud size // then return all indices if (sample_size >= N) { indices = *indices_; removed_indices_->clear (); } else { // Resize output indices to sample size indices.resize (sample_size); if (extract_removed_indices_) removed_indices_->resize (N - sample_size); // Set random seed so derived indices are the same each time the filter runs std::srand (seed_); // Algorithm A unsigned top = N - sample_size; unsigned i = 0; unsigned index = 0; std::vector<bool> added; if (extract_removed_indices_) added.resize (indices_->size (), false); for (size_t n = sample_size; n >= 2; n--) { unsigned int V = static_cast<unsigned int>( unifRand () ); unsigned S = 0; float quot = float (top) * one_over_N; while (quot > V) { S++; top--; N--; quot = quot * float (top) * one_over_N; } index += S; indices[i++] = (*indices_)[index++]; if (extract_removed_indices_) added[index] = true; N--; } index += N * static_cast<unsigned> (unifRand ()); indices[i++] = (*indices_)[index++]; if (extract_removed_indices_) added[index] = true; // Now populate removed_indices_ appropriately if (extract_removed_indices_) { unsigned ri = 0; for (size_t i = 0; i < added.size (); i++) { if (!added[i]) { (*removed_indices_)[ri++] = (*indices_)[i]; } } } } } #define PCL_INSTANTIATE_RandomSample(T) template class PCL_EXPORTS pcl::RandomSample<T>; #endif // PCL_FILTERS_IMPL_RANDOM_SAMPLE_H_ <commit_msg>Attempting to fix 32-bit Linux segfault<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2009, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder(s) nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id: extract_indices.hpp 1897 2011-07-26 20:35:49Z rusu $ * */ #ifndef PCL_FILTERS_IMPL_RANDOM_SAMPLE_H_ #define PCL_FILTERS_IMPL_RANDOM_SAMPLE_H_ #include <pcl/filters/random_sample.h> #include <pcl/common/io.h> #include <pcl/point_traits.h> /////////////////////////////////////////////////////////////////////////////// template<typename PointT> void pcl::RandomSample<PointT>::applyFilter (PointCloud &output) { std::vector<int> indices; if (keep_organized_) { bool temp = extract_removed_indices_; extract_removed_indices_ = true; applyFilter (indices); extract_removed_indices_ = temp; copyPointCloud (*input_, output); // Get all floating point fields std::vector<sensor_msgs::PointField> fields; pcl::getFields (output, fields); std::vector<sensor_msgs::PointField> float_fields; for (size_t i = 0; i < fields.size (); ++i) { if (fields[i].datatype == sensor_msgs::PointField::FLOAT32) float_fields.push_back (fields[i]); } // For every "removed" point, set all floating point fields to NaN const static float user_filter_value = user_filter_value_; for (size_t rii = 0; rii < removed_indices_->size (); ++rii) { uint8_t* pt_data = reinterpret_cast<uint8_t*> (&output.at ((*removed_indices_)[rii])); for (size_t i = 0; i < float_fields.size (); ++i) { memcpy (pt_data + float_fields[i].offset, reinterpret_cast<const char*> (&user_filter_value), sizeof (float)); } if (!pcl_isfinite (user_filter_value_)) output.is_dense = false; } } else { output.is_dense = true; applyFilter (indices); copyPointCloud (*input_, indices, output); } } /////////////////////////////////////////////////////////////////////////////// template<typename PointT> void pcl::RandomSample<PointT>::applyFilter (std::vector<int> &indices) { unsigned N = static_cast<unsigned> (indices_->size ()); float one_over_N = 1.0f / float (N); unsigned int sample_size = negative_ ? N - sample_ : sample_; // If sample size is 0 or if the sample size is greater then input cloud size // then return all indices if (sample_size >= N) { indices = *indices_; removed_indices_->clear (); } else { // Resize output indices to sample size indices.resize (sample_size); if (extract_removed_indices_) removed_indices_->resize (N - sample_size); // Set random seed so derived indices are the same each time the filter runs std::srand (seed_); // Algorithm A unsigned top = N - sample_size; unsigned i = 0; unsigned index = 0; std::vector<bool> added; if (extract_removed_indices_) added.resize (indices_->size (), false); for (size_t n = sample_size; n >= 2; n--) { unsigned int V = static_cast<unsigned int>( unifRand () ); unsigned S = 0; float quot = float (top) * one_over_N; while (quot > V) { S++; top--; N--; quot = quot * float (top) * one_over_N; } index += S; indices[i++] = (*indices_)[index++]; if (extract_removed_indices_) added[index] = true; N--; } index += N * static_cast<unsigned> (unifRand ()); indices[i++] = (*indices_)[index++]; if (extract_removed_indices_) added[index] = true; // Now populate removed_indices_ appropriately if (extract_removed_indices_) { unsigned ri = 0; for (size_t i = 0; i < added.size (); i++) { if (!added[i]) { (*removed_indices_)[ri++] = (*indices_)[i]; } } } } } #define PCL_INSTANTIATE_RandomSample(T) template class PCL_EXPORTS pcl::RandomSample<T>; #endif // PCL_FILTERS_IMPL_RANDOM_SAMPLE_H_ <|endoftext|>
<commit_before><commit_msg>Added failsafe output of the round start by the auctioneer<commit_after><|endoftext|>
<commit_before><commit_msg>Let's verify that set_node_processor_ids worked<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: SlsCacheConfiguration.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-10-24 07:40:27 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "SlsCacheConfiguration.hxx" #include <vos/mutex.hxx> #include <vcl/svapp.hxx> #include <comphelper/processfactory.hxx> #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XHIERARCHICALNAMEACCESS_HPP_ #include <com/sun/star/container/XHierarchicalNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif using namespace ::com::sun::star; using namespace ::com::sun::star::uno; namespace sd { namespace slidesorter { namespace cache { ::boost::shared_ptr<CacheConfiguration> CacheConfiguration::mpInstance; ::boost::weak_ptr<CacheConfiguration> CacheConfiguration::mpWeakInstance; Timer CacheConfiguration::maReleaseTimer; ::boost::shared_ptr<CacheConfiguration> CacheConfiguration::Instance (void) { ::vos::OGuard aSolarGuard (Application::GetSolarMutex()); if (mpInstance.get() == NULL) { // Maybe somebody else kept a previously created instance alive. if ( ! mpWeakInstance.expired()) mpInstance = ::boost::shared_ptr<CacheConfiguration>(mpWeakInstance); if (mpInstance.get() == NULL) { // We have to create a new instance. mpInstance.reset(new CacheConfiguration()); mpWeakInstance = mpInstance; // Prepare to release this instance in the near future. maReleaseTimer.SetTimeoutHdl( LINK(mpInstance.get(),CacheConfiguration,TimerCallback)); maReleaseTimer.SetTimeout(5000 /* 5s */); maReleaseTimer.Start(); } } return mpInstance; } CacheConfiguration::CacheConfiguration (void) { // Get the cache size from configuration. const ::rtl::OUString sConfigurationProviderServiceName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.ConfigurationProvider")); const ::rtl::OUString sPathToImpressConfigurationRoot( RTL_CONSTASCII_USTRINGPARAM("/org.openoffice.Office.Impress/")); const ::rtl::OUString sPathToNode( RTL_CONSTASCII_USTRINGPARAM( "MultiPaneGUI/SlideSorter/PreviewCache")); try { do { // Obtain access to the configuration. Reference<lang::XMultiServiceFactory> xProvider ( ::comphelper::getProcessServiceFactory()->createInstance( sConfigurationProviderServiceName), UNO_QUERY); if ( ! xProvider.is()) break; // Obtain access to Impress configuration. Sequence<Any> aCreationArguments(3); aCreationArguments[0] = makeAny(beans::PropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("nodepath")), 0, makeAny(sPathToImpressConfigurationRoot), beans::PropertyState_DIRECT_VALUE)); aCreationArguments[1] = makeAny(beans::PropertyValue( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("depth")), 0, makeAny((sal_Int32)-1), beans::PropertyState_DIRECT_VALUE)); aCreationArguments[2] = makeAny(beans::PropertyValue( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("lazywrite")), 0, makeAny(true), beans::PropertyState_DIRECT_VALUE)); ::rtl::OUString sAccessService (::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.ConfigurationAccess"))); Reference<XInterface> xRoot (xProvider->createInstanceWithArguments( sAccessService, aCreationArguments)); if ( ! xRoot.is()) break; Reference<container::XHierarchicalNameAccess> xHierarchy (xRoot, UNO_QUERY); if ( ! xHierarchy.is()) break; // Get the node for the slide sorter preview cache. mxCacheNode = Reference<container::XNameAccess>( xHierarchy->getByHierarchicalName(sPathToNode), UNO_QUERY); } while (false); } catch (RuntimeException aException) { (void)aException; } catch (Exception aException) { (void)aException; } } Any CacheConfiguration::GetValue (const ::rtl::OUString& rName) { Any aResult; if (mxCacheNode != NULL) { try { aResult = mxCacheNode->getByName(rName); } catch (Exception aException) { (void)aException; } } return aResult; } IMPL_LINK(CacheConfiguration,TimerCallback, Timer*,pTimer) { // Release out reference to the instance. mpInstance.reset(); return 0; } } } } // end of namespace ::sd::slidesorter::cache <commit_msg>INTEGRATION: CWS pj42 (1.2.20); FILE MERGED 2005/11/10 21:59:11 pjanik 1.2.20.1: #i57567#: Remove SISSL license.<commit_after>/************************************************************************* * * $RCSfile: SlsCacheConfiguration.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-11-11 10:47:58 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "SlsCacheConfiguration.hxx" #include <vos/mutex.hxx> #include <vcl/svapp.hxx> #include <comphelper/processfactory.hxx> #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XHIERARCHICALNAMEACCESS_HPP_ #include <com/sun/star/container/XHierarchicalNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif using namespace ::com::sun::star; using namespace ::com::sun::star::uno; namespace sd { namespace slidesorter { namespace cache { ::boost::shared_ptr<CacheConfiguration> CacheConfiguration::mpInstance; ::boost::weak_ptr<CacheConfiguration> CacheConfiguration::mpWeakInstance; Timer CacheConfiguration::maReleaseTimer; ::boost::shared_ptr<CacheConfiguration> CacheConfiguration::Instance (void) { ::vos::OGuard aSolarGuard (Application::GetSolarMutex()); if (mpInstance.get() == NULL) { // Maybe somebody else kept a previously created instance alive. if ( ! mpWeakInstance.expired()) mpInstance = ::boost::shared_ptr<CacheConfiguration>(mpWeakInstance); if (mpInstance.get() == NULL) { // We have to create a new instance. mpInstance.reset(new CacheConfiguration()); mpWeakInstance = mpInstance; // Prepare to release this instance in the near future. maReleaseTimer.SetTimeoutHdl( LINK(mpInstance.get(),CacheConfiguration,TimerCallback)); maReleaseTimer.SetTimeout(5000 /* 5s */); maReleaseTimer.Start(); } } return mpInstance; } CacheConfiguration::CacheConfiguration (void) { // Get the cache size from configuration. const ::rtl::OUString sConfigurationProviderServiceName( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.ConfigurationProvider")); const ::rtl::OUString sPathToImpressConfigurationRoot( RTL_CONSTASCII_USTRINGPARAM("/org.openoffice.Office.Impress/")); const ::rtl::OUString sPathToNode( RTL_CONSTASCII_USTRINGPARAM( "MultiPaneGUI/SlideSorter/PreviewCache")); try { do { // Obtain access to the configuration. Reference<lang::XMultiServiceFactory> xProvider ( ::comphelper::getProcessServiceFactory()->createInstance( sConfigurationProviderServiceName), UNO_QUERY); if ( ! xProvider.is()) break; // Obtain access to Impress configuration. Sequence<Any> aCreationArguments(3); aCreationArguments[0] = makeAny(beans::PropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("nodepath")), 0, makeAny(sPathToImpressConfigurationRoot), beans::PropertyState_DIRECT_VALUE)); aCreationArguments[1] = makeAny(beans::PropertyValue( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("depth")), 0, makeAny((sal_Int32)-1), beans::PropertyState_DIRECT_VALUE)); aCreationArguments[2] = makeAny(beans::PropertyValue( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("lazywrite")), 0, makeAny(true), beans::PropertyState_DIRECT_VALUE)); ::rtl::OUString sAccessService (::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.configuration.ConfigurationAccess"))); Reference<XInterface> xRoot (xProvider->createInstanceWithArguments( sAccessService, aCreationArguments)); if ( ! xRoot.is()) break; Reference<container::XHierarchicalNameAccess> xHierarchy (xRoot, UNO_QUERY); if ( ! xHierarchy.is()) break; // Get the node for the slide sorter preview cache. mxCacheNode = Reference<container::XNameAccess>( xHierarchy->getByHierarchicalName(sPathToNode), UNO_QUERY); } while (false); } catch (RuntimeException aException) { (void)aException; } catch (Exception aException) { (void)aException; } } Any CacheConfiguration::GetValue (const ::rtl::OUString& rName) { Any aResult; if (mxCacheNode != NULL) { try { aResult = mxCacheNode->getByName(rName); } catch (Exception aException) { (void)aException; } } return aResult; } IMPL_LINK(CacheConfiguration,TimerCallback, Timer*,pTimer) { // Release out reference to the instance. mpInstance.reset(); return 0; } } } } // end of namespace ::sd::slidesorter::cache <|endoftext|>
<commit_before>// a helper library for using ZMQ with ALIROOT, focussed on multipart messaging // this lib implements the HLT specific interface, for general use cases // see AliZMQhelpers.h // blame: Mikolaj Krzewicki, [email protected] // some of it might be inspired by czmq.h (http://czmq.zeromq.org) // // Copyright (C) 2015 Goethe University Frankfurt // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // #include "AliHLTZMQhelpers.h" #include "AliHLTMessage.h" #include "TObjArray.h" #include "TFile.h" #include "TKey.h" #include "zmq.h" #include "AliRawData.h" #include "TSystem.h" #include <exception> using namespace AliZMQhelpers; //_______________________________________________________________________________________ int AliZMQhelpers::alizmq_msg_iter_check_id(aliZMQmsg::iterator it, const AliHLTDataTopic& topic) { AliHLTDataTopic actualTopic; alizmq_msg_iter_topic(it, actualTopic); if (actualTopic.GetID() == topic.GetID()) return 0; return 1; } //_______________________________________________________________________________________ int AliZMQhelpers::alizmq_msg_send(const AliHLTDataTopic& topic, TObject* object, void* socket, int flags, int compression, aliZMQrootStreamerInfo* streamers) { int rc = 0; AliHLTMessage* tmessage = AliHLTMessage::Stream(object, compression); zmq_msg_t dataMsg; rc = zmq_msg_init_data( &dataMsg, tmessage->Buffer(), tmessage->Length(), alizmq_deleteTObject, tmessage); if (streamers) { alizmq_update_streamerlist(streamers, tmessage->GetStreamerInfos()); } //then send the object topic rc = zmq_send( socket, &topic, sizeof(topic), ZMQ_SNDMORE ); if (rc<0) { zmq_msg_close(&dataMsg); //printf("unable to send topic: %s %s\n", topic.Description().c_str(), zmq_strerror(errno)); return rc; } //send the object itself rc = zmq_msg_send(&dataMsg, socket, flags); if (rc<0) { //printf("unable to send data: %s %s\n", tmessage->GetName(), zmq_strerror(errno)); zmq_msg_close(&dataMsg); return rc; } return rc; } //______________________________________________________________________________ int AliZMQhelpers::alizmq_msg_send(const AliHLTDataTopic& topic, const std::string& data, void* socket, int flags) { int rc = 0; rc = zmq_send( socket, &topic, sizeof(topic), ZMQ_SNDMORE ); if (rc<0) { //printf("unable to send topic: %s %s\n", topic.Description().c_str(), zmq_strerror(errno)); return rc; } zmq_msg_t dataMsg; zmq_msg_init_size(&dataMsg, data.size()); memcpy(zmq_msg_data(&dataMsg), data.data(), zmq_msg_size(&dataMsg)); rc = zmq_msg_send(&dataMsg, socket, flags); if (rc<0) { //printf("unable to send data: %s\n", data.c_str()); zmq_msg_close(&dataMsg); return rc; } return rc; } //______________________________________________________________________________ int AliZMQhelpers::alizmq_msg_add(aliZMQmsg* message, DataTopic* topic, AliRawData* blob) { //add a frame to the mesage int rc = 0; topic->SetSerialization(kSerializationNONE); //prepare topic msg zmq_msg_t* topicMsg = new zmq_msg_t; rc = zmq_msg_init_size( topicMsg, sizeof(*topic)); if (rc<0) { zmq_msg_close(topicMsg); delete topicMsg; return -1; } memcpy(zmq_msg_data(topicMsg), topic, sizeof(*topic)); zmq_msg_t* dataMsg = new zmq_msg_t; rc = zmq_msg_init_data( dataMsg, blob->GetBuffer(), blob->GetSize(), alizmq_deleteTObject, blob); if (rc<0) { zmq_msg_close(topicMsg); zmq_msg_close(dataMsg); delete topicMsg; delete dataMsg; return -1; } //add the frame to the message message->push_back(std::make_pair(topicMsg,dataMsg)); return message->size(); } //______________________________________________________________________________ int AliZMQhelpers::alizmq_file_write(AtomicFile& afile, AliHLTDataTopic topic, TObject* object) { //To avoid problems with resource leaks in the HLT the use of non owning TCollection //is forbidden. //Use AliHLTObjArray/AliHLTList instead. //cannot use AliFatal here, so we throw. TCollection* collection = dynamic_cast<TCollection*>(object); if (collection) { if (!collection->IsOwner() && !(strcmp(collection->ClassName(),"AliHLTObjArray")==0 || strcmp(collection->ClassName(),"AliHLTList")==0)) { afile.Close(); throw std::runtime_error("Cannot use a non-owning TCollection in HLT unless it is a AliHLTList or AliHLTObjArray"); } } topic.SetSerialization(kSerializationROOT); TFile* file = afile.GetFile(); if (!file) { printf("could not get file\n"); return -1; } //TODO: do some sanity checks AliRawData topicBlob; //const_cast is here because AliRawData interface is broken topicBlob.SetBuffer(const_cast<AliHLTDataTopic*>(&topic), sizeof(topic)); file->WriteObject(&topicBlob, "header"); file->WriteObject(object, "payload"); return 0; } //______________________________________________________________________________ int AliZMQhelpers::alizmq_file_write(AtomicFile& afile, const AliHLTDataTopic& topic, const void* buf, Int_t len) { TFile* file = afile.GetFile(); if (!file) { printf("could not get file\n"); return -1; } //TODO: do some sanity checks AliRawData headerBlob; //const_cast is here because AliRawData interface is broken headerBlob.SetBuffer(const_cast<AliHLTDataTopic*>(&topic), sizeof(topic)); file->WriteObject(&headerBlob, "header"); AliRawData payloadBlob; //const_cast is here because AliRawData interface is broken payloadBlob.SetBuffer(const_cast<void*>(buf), len); file->WriteObject(&payloadBlob, "payload"); return 0; } //______________________________________________________________________________ int AliZMQhelpers::alizmq_file_write(AtomicFile& afile, aliZMQmsg* message, bool deserializeROOTobjects) { for (aliZMQmsg::iterator i=message->begin(); i!=message->end(); ++i) { AliHLTDataTopic topic; alizmq_msg_iter_topic(i,topic); if (topic.fDataSerialization==kSerializationROOT && deserializeROOTobjects) { TObject* object = NULL; alizmq_msg_iter_data(i, object); if (!object) { printf("alizmq_file_writ error: root object could not be deserialized from message\n"); return -1; } alizmq_file_write(afile, topic, object); delete object; } else { void* payloadBuf = NULL; size_t payloadSize = 0; alizmq_msg_iter_data(i,payloadBuf, payloadSize); alizmq_file_write(afile, topic, payloadBuf, payloadSize); } } return 0; } //______________________________________________________________________________ int AliZMQhelpers::alizmq_file_read(TFile& file, aliZMQmsg* message) { if (!message) {printf("no message!\n"); return -1;} if (file.GetNkeys()%2) {printf("number of keys in the file not even\n");return 1;} TList* listOfKeys = file.GetListOfKeys(); TIter iter(listOfKeys, kIterBackward); while (TKey* key = static_cast<TKey*>(iter())) { std::string objectName = key->GetName(); if (objectName!="header") continue; Short_t cycle = key->GetCycle(); AliRawData* headerBlob = static_cast<AliRawData*>(key->ReadObj()); if (!headerBlob) {printf("could not read the header blob for cycle %i\n",cycle); continue;} AliHLTDataTopic topic; memcpy(&topic, headerBlob->GetBuffer(), (size_t(headerBlob->GetSize())>sizeof(topic))?sizeof(topic):size_t(headerBlob->GetSize())); delete headerBlob; TKey* payloadKey = file.GetKey("payload",cycle); if (!payloadKey) {printf("no payload found for header %i\n",cycle); continue;} string payloadClassName = payloadKey->GetClassName(); if (payloadClassName.find("AliRawData")!=string::npos) { AliRawData* payloadBlob = static_cast<AliRawData*>(payloadKey->ReadObj()); if (!payloadBlob) {printf("could not read the payload blob for cycle %i\n",cycle); continue;} if (alizmq_msg_add(message, &topic, payloadBlob)<0) {delete payloadBlob;} } else { TObject* object = payloadKey->ReadObj(); if (!object) {printf("could not extract the root object from key %s with cycle %i \n", key->GetName(), cycle); continue;} if (alizmq_msg_add(message, &topic, object)<0) {delete object;} delete object; } } return 0; } //______________________________________________________________________________ AliZMQhelpers::AtomicFile::AtomicFile(const char* name) : targetFileName(name) , tempFile(NULL) { TString tmpname(name); tmpname+="."; if (FILE* fd = gSystem->TempFileName(tmpname,gSystem->DirName(name))) { tempFile = new TFile(tmpname.Data(),"recreate"); fclose(fd); } } //______________________________________________________________________________ AliZMQhelpers::AtomicFile::~AtomicFile() { Close(); } //______________________________________________________________________________ void AliZMQhelpers::AtomicFile::Close() { if (!tempFile) return; TString tempname = tempFile->GetName(); tempFile->Close(); delete tempFile; tempFile=NULL; gSystem->Rename(tempname.Data(),targetFileName.Data()); targetFileName.Clear(); } <commit_msg>Add missing include <stdexcept><commit_after>// a helper library for using ZMQ with ALIROOT, focussed on multipart messaging // this lib implements the HLT specific interface, for general use cases // see AliZMQhelpers.h // blame: Mikolaj Krzewicki, [email protected] // some of it might be inspired by czmq.h (http://czmq.zeromq.org) // // Copyright (C) 2015 Goethe University Frankfurt // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // #include "AliHLTZMQhelpers.h" #include "AliHLTMessage.h" #include "TObjArray.h" #include "TFile.h" #include "TKey.h" #include "zmq.h" #include "AliRawData.h" #include "TSystem.h" #include <exception> #include <stdexcept> using namespace AliZMQhelpers; //_______________________________________________________________________________________ int AliZMQhelpers::alizmq_msg_iter_check_id(aliZMQmsg::iterator it, const AliHLTDataTopic& topic) { AliHLTDataTopic actualTopic; alizmq_msg_iter_topic(it, actualTopic); if (actualTopic.GetID() == topic.GetID()) return 0; return 1; } //_______________________________________________________________________________________ int AliZMQhelpers::alizmq_msg_send(const AliHLTDataTopic& topic, TObject* object, void* socket, int flags, int compression, aliZMQrootStreamerInfo* streamers) { int rc = 0; AliHLTMessage* tmessage = AliHLTMessage::Stream(object, compression); zmq_msg_t dataMsg; rc = zmq_msg_init_data( &dataMsg, tmessage->Buffer(), tmessage->Length(), alizmq_deleteTObject, tmessage); if (streamers) { alizmq_update_streamerlist(streamers, tmessage->GetStreamerInfos()); } //then send the object topic rc = zmq_send( socket, &topic, sizeof(topic), ZMQ_SNDMORE ); if (rc<0) { zmq_msg_close(&dataMsg); //printf("unable to send topic: %s %s\n", topic.Description().c_str(), zmq_strerror(errno)); return rc; } //send the object itself rc = zmq_msg_send(&dataMsg, socket, flags); if (rc<0) { //printf("unable to send data: %s %s\n", tmessage->GetName(), zmq_strerror(errno)); zmq_msg_close(&dataMsg); return rc; } return rc; } //______________________________________________________________________________ int AliZMQhelpers::alizmq_msg_send(const AliHLTDataTopic& topic, const std::string& data, void* socket, int flags) { int rc = 0; rc = zmq_send( socket, &topic, sizeof(topic), ZMQ_SNDMORE ); if (rc<0) { //printf("unable to send topic: %s %s\n", topic.Description().c_str(), zmq_strerror(errno)); return rc; } zmq_msg_t dataMsg; zmq_msg_init_size(&dataMsg, data.size()); memcpy(zmq_msg_data(&dataMsg), data.data(), zmq_msg_size(&dataMsg)); rc = zmq_msg_send(&dataMsg, socket, flags); if (rc<0) { //printf("unable to send data: %s\n", data.c_str()); zmq_msg_close(&dataMsg); return rc; } return rc; } //______________________________________________________________________________ int AliZMQhelpers::alizmq_msg_add(aliZMQmsg* message, DataTopic* topic, AliRawData* blob) { //add a frame to the mesage int rc = 0; topic->SetSerialization(kSerializationNONE); //prepare topic msg zmq_msg_t* topicMsg = new zmq_msg_t; rc = zmq_msg_init_size( topicMsg, sizeof(*topic)); if (rc<0) { zmq_msg_close(topicMsg); delete topicMsg; return -1; } memcpy(zmq_msg_data(topicMsg), topic, sizeof(*topic)); zmq_msg_t* dataMsg = new zmq_msg_t; rc = zmq_msg_init_data( dataMsg, blob->GetBuffer(), blob->GetSize(), alizmq_deleteTObject, blob); if (rc<0) { zmq_msg_close(topicMsg); zmq_msg_close(dataMsg); delete topicMsg; delete dataMsg; return -1; } //add the frame to the message message->push_back(std::make_pair(topicMsg,dataMsg)); return message->size(); } //______________________________________________________________________________ int AliZMQhelpers::alizmq_file_write(AtomicFile& afile, AliHLTDataTopic topic, TObject* object) { //To avoid problems with resource leaks in the HLT the use of non owning TCollection //is forbidden. //Use AliHLTObjArray/AliHLTList instead. //cannot use AliFatal here, so we throw. TCollection* collection = dynamic_cast<TCollection*>(object); if (collection) { if (!collection->IsOwner() && !(strcmp(collection->ClassName(),"AliHLTObjArray")==0 || strcmp(collection->ClassName(),"AliHLTList")==0)) { afile.Close(); throw std::runtime_error("Cannot use a non-owning TCollection in HLT unless it is a AliHLTList or AliHLTObjArray"); } } topic.SetSerialization(kSerializationROOT); TFile* file = afile.GetFile(); if (!file) { printf("could not get file\n"); return -1; } //TODO: do some sanity checks AliRawData topicBlob; //const_cast is here because AliRawData interface is broken topicBlob.SetBuffer(const_cast<AliHLTDataTopic*>(&topic), sizeof(topic)); file->WriteObject(&topicBlob, "header"); file->WriteObject(object, "payload"); return 0; } //______________________________________________________________________________ int AliZMQhelpers::alizmq_file_write(AtomicFile& afile, const AliHLTDataTopic& topic, const void* buf, Int_t len) { TFile* file = afile.GetFile(); if (!file) { printf("could not get file\n"); return -1; } //TODO: do some sanity checks AliRawData headerBlob; //const_cast is here because AliRawData interface is broken headerBlob.SetBuffer(const_cast<AliHLTDataTopic*>(&topic), sizeof(topic)); file->WriteObject(&headerBlob, "header"); AliRawData payloadBlob; //const_cast is here because AliRawData interface is broken payloadBlob.SetBuffer(const_cast<void*>(buf), len); file->WriteObject(&payloadBlob, "payload"); return 0; } //______________________________________________________________________________ int AliZMQhelpers::alizmq_file_write(AtomicFile& afile, aliZMQmsg* message, bool deserializeROOTobjects) { for (aliZMQmsg::iterator i=message->begin(); i!=message->end(); ++i) { AliHLTDataTopic topic; alizmq_msg_iter_topic(i,topic); if (topic.fDataSerialization==kSerializationROOT && deserializeROOTobjects) { TObject* object = NULL; alizmq_msg_iter_data(i, object); if (!object) { printf("alizmq_file_writ error: root object could not be deserialized from message\n"); return -1; } alizmq_file_write(afile, topic, object); delete object; } else { void* payloadBuf = NULL; size_t payloadSize = 0; alizmq_msg_iter_data(i,payloadBuf, payloadSize); alizmq_file_write(afile, topic, payloadBuf, payloadSize); } } return 0; } //______________________________________________________________________________ int AliZMQhelpers::alizmq_file_read(TFile& file, aliZMQmsg* message) { if (!message) {printf("no message!\n"); return -1;} if (file.GetNkeys()%2) {printf("number of keys in the file not even\n");return 1;} TList* listOfKeys = file.GetListOfKeys(); TIter iter(listOfKeys, kIterBackward); while (TKey* key = static_cast<TKey*>(iter())) { std::string objectName = key->GetName(); if (objectName!="header") continue; Short_t cycle = key->GetCycle(); AliRawData* headerBlob = static_cast<AliRawData*>(key->ReadObj()); if (!headerBlob) {printf("could not read the header blob for cycle %i\n",cycle); continue;} AliHLTDataTopic topic; memcpy(&topic, headerBlob->GetBuffer(), (size_t(headerBlob->GetSize())>sizeof(topic))?sizeof(topic):size_t(headerBlob->GetSize())); delete headerBlob; TKey* payloadKey = file.GetKey("payload",cycle); if (!payloadKey) {printf("no payload found for header %i\n",cycle); continue;} string payloadClassName = payloadKey->GetClassName(); if (payloadClassName.find("AliRawData")!=string::npos) { AliRawData* payloadBlob = static_cast<AliRawData*>(payloadKey->ReadObj()); if (!payloadBlob) {printf("could not read the payload blob for cycle %i\n",cycle); continue;} if (alizmq_msg_add(message, &topic, payloadBlob)<0) {delete payloadBlob;} } else { TObject* object = payloadKey->ReadObj(); if (!object) {printf("could not extract the root object from key %s with cycle %i \n", key->GetName(), cycle); continue;} if (alizmq_msg_add(message, &topic, object)<0) {delete object;} delete object; } } return 0; } //______________________________________________________________________________ AliZMQhelpers::AtomicFile::AtomicFile(const char* name) : targetFileName(name) , tempFile(NULL) { TString tmpname(name); tmpname+="."; if (FILE* fd = gSystem->TempFileName(tmpname,gSystem->DirName(name))) { tempFile = new TFile(tmpname.Data(),"recreate"); fclose(fd); } } //______________________________________________________________________________ AliZMQhelpers::AtomicFile::~AtomicFile() { Close(); } //______________________________________________________________________________ void AliZMQhelpers::AtomicFile::Close() { if (!tempFile) return; TString tempname = tempFile->GetName(); tempFile->Close(); delete tempFile; tempFile=NULL; gSystem->Rename(tempname.Data(),targetFileName.Data()); targetFileName.Clear(); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: CustomAnimationPanel.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 06:39:17 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SD_TOOLPANEL_CONTROLS_CUSTOM_ANIMATION_PANEL_HXX #define SD_TOOLPANEL_CONTROLS_CUSTOM_ANIMATION_PANEL_HXX #include "taskpane/SubToolPanel.hxx" namespace sd { class ViewShellBase; } namespace sd { namespace toolpanel { class TreeNode; class ControlFactory; } } namespace sd { namespace toolpanel { namespace controls { class CustomAnimationPanel : public SubToolPanel { public: CustomAnimationPanel ( TreeNode* pParent, ViewShellBase& rBase); virtual ~CustomAnimationPanel (void); static std::auto_ptr<ControlFactory> CreateControlFactory (ViewShellBase& rBase); virtual Size GetPreferredSize (void); virtual sal_Int32 GetPreferredWidth (sal_Int32 nHeigh); virtual sal_Int32 GetPreferredHeight (sal_Int32 nWidth); virtual ::Window* GetWindow (void); virtual bool IsResizable (void); virtual bool IsExpandable (void) const; virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessibleObject ( const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible>& rxParent); private: Size maPreferredSize; ::Window* mpWrappedControl; }; } } } // end of namespace ::sd::toolpanel::controls #endif <commit_msg>INTEGRATION: CWS sdwarningsbegone (1.5.316); FILE MERGED 2006/11/27 13:48:13 cl 1.5.316.1: #i69285# warning free code changes for sd project<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: CustomAnimationPanel.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: kz $ $Date: 2006-12-12 18:47:45 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SD_TOOLPANEL_CONTROLS_CUSTOM_ANIMATION_PANEL_HXX #define SD_TOOLPANEL_CONTROLS_CUSTOM_ANIMATION_PANEL_HXX #include "taskpane/SubToolPanel.hxx" namespace sd { class ViewShellBase; } namespace sd { namespace toolpanel { class TreeNode; class ControlFactory; } } namespace sd { namespace toolpanel { namespace controls { class CustomAnimationPanel : public SubToolPanel { public: CustomAnimationPanel ( TreeNode* pParent, ViewShellBase& rBase); virtual ~CustomAnimationPanel (void); static std::auto_ptr<ControlFactory> CreateControlFactory (ViewShellBase& rBase); virtual Size GetPreferredSize (void); virtual sal_Int32 GetPreferredWidth (sal_Int32 nHeigh); virtual sal_Int32 GetPreferredHeight (sal_Int32 nWidth); virtual ::Window* GetWindow (void); virtual bool IsResizable (void); virtual bool IsExpandable (void) const; virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessibleObject ( const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible>& rxParent); using Window::GetWindow; private: Size maPreferredSize; ::Window* mpWrappedControl; }; } } } // end of namespace ::sd::toolpanel::controls #endif <|endoftext|>
<commit_before><commit_msg>fix variable name conflict<commit_after><|endoftext|>
<commit_before><commit_msg>math->pcl_macros<commit_after><|endoftext|>
<commit_before><commit_msg>INTEGRATION: CWS os20 (1.2.382); FILE MERGED 2003/09/12 12:27:40 fme 1.2.382.1: #111937# Keep attribute, widows and orphans in balanced sections<commit_after><|endoftext|>
<commit_before><commit_msg>OUString: remove temporaries and unneeded conversions<commit_after><|endoftext|>
<commit_before><commit_msg>test-storage-transpose: test more type and more simd structs<commit_after><|endoftext|>
<commit_before>/* Copyright 2016 Anastasiya Kornilova. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "gyroSensor.h" #include <qmath.h> #include <trikKernel/configurer.h> #include <trikKernel/timeVal.h> #include <QsLog.h> #include <cmath> #include "vectorSensorWorker.h" using namespace trikControl; static constexpr int GYRO_ARITHM_PRECISION = 8; static constexpr double GYRO_250DPS = 8.75 / (1 << GYRO_ARITHM_PRECISION) ; static constexpr double pi() { return 3.14159265358979323846;} static constexpr double RAD_TO_MDEG = 1000 * 180 / pi(); GyroSensor::GyroSensor(const QString &deviceName, const trikKernel::Configurer &configurer , const trikHal::HardwareAbstractionInterface &hardwareAbstraction, VectorSensorInterface *accelerometer) : mState(deviceName) , mIsCalibrated(false) , mQ(QQuaternion(1, 0, 0, 0)) , mGyroCounter(0) , mLastUpdate(trikKernel::TimeVal(0, 0)) , mAccelerometer(accelerometer) { mVectorSensorWorker.reset(new VectorSensorWorker(configurer.attributeByDevice(deviceName, "deviceFile"), mState , hardwareAbstraction, mWorkerThread)); mBias.resize(3); mGyroSum.resize(3); mResult.resize(7); mRawData.resize(4); mAccelerometerVector.resize(3); mAccelerometerSum.resize(3); mAccelerometerCounter = 0; qDebug() << "constr"; mCalibrationTimer.moveToThread(&mWorkerThread); mCalibrationTimer.setSingleShot(true); if (!mState.isFailed()) { qRegisterMetaType<trikKernel::TimeVal>("trikKernel::TimeVal"); connect(mVectorSensorWorker.data(), SIGNAL(newData(QVector<int>,trikKernel::TimeVal)) , this, SLOT(countTilt(QVector<int>,trikKernel::TimeVal))); connect(&mCalibrationTimer, SIGNAL(timeout()), this, SLOT(initParams())); QLOG_INFO() << "Starting VectorSensor worker thread" << &mWorkerThread; mState.ready(); } } GyroSensor::~GyroSensor() { if (mWorkerThread.isRunning()) { QMetaObject::invokeMethod(mVectorSensorWorker.data(), "deinitialize"); mWorkerThread.quit(); mWorkerThread.wait(); } } GyroSensor::Status GyroSensor::status() const { return mState.status(); } const QQuaternion &GyroSensor::Q() const { return mQ; } QVector<int> GyroSensor::read() const { return mResult; } QVector<int> GyroSensor::readRawData() const { return mRawData; } void GyroSensor::calibrate(int msec) { qDebug() << "calib"; mCalibrationTimer.start(msec); connect(mVectorSensorWorker.data(), SIGNAL(newData(QVector<int>,trikKernel::TimeVal)) , this, SLOT(sumBias(QVector<int>,trikKernel::TimeVal))); connect(mAccelerometer, SIGNAL(newData(QVector<int>,trikKernel::TimeVal)) , this, SLOT(sumAccelerometer(QVector<int>,trikKernel::TimeVal))); mIsCalibrated = false; } bool GyroSensor::isCalibrated() const { return mIsCalibrated; } void GyroSensor::countTilt(const QVector<int> &gyroData, trikKernel::TimeVal t) { mRawData[0] = -gyroData[1]; mRawData[1] = -gyroData[0]; mRawData[2] = gyroData[2]; mRawData[3] = t.packedUInt32(); static bool timeInited = false; if (!timeInited) { timeInited = true; mLastUpdate = t; } else { const auto r0 = ((gyroData[0]<<GYRO_ARITHM_PRECISION) - mBias[0]) * GYRO_250DPS; const auto r1 = ((gyroData[1]<<GYRO_ARITHM_PRECISION) - mBias[1]) * GYRO_250DPS; const auto r2 = ((gyroData[2]<<GYRO_ARITHM_PRECISION) - mBias[2]) * GYRO_250DPS; mResult[0] = r0; mResult[1] = r1; mResult[2] = r2; mResult[3] = t.packedUInt32(); constexpr auto deltaConst = pi() / 180 / 1000 / 1000000 / 2; const auto dt = (t - mLastUpdate) * deltaConst; const auto x = r0 * dt; const auto y = r1 * dt; const auto z = r2 * dt; const auto c1 = std::cos(z); const auto s1 = std::sin(z); const auto c2 = std::cos(y); const auto s2 = std::sin(y); const auto c3 = std::cos(x); const auto s3 = std::sin(x); QQuaternion deltaQ; deltaQ.setScalar(c1 * c2 * c3 + s1 * s2 * s3); deltaQ.setX(s1 * c2 * c3 - c1 * s2 * s3); deltaQ.setY(c1 * s2 * c3 + s1 * c2 * s3); deltaQ.setZ(c1 * c2 * s3 - s1 * s2 * c3); mQ *= deltaQ; mQ.normalize(); mLastUpdate = t; QVector3D euler = getEulerAngles(); mResult[4] = euler.x(); mResult[5] = euler.y(); mResult[6] = euler.z(); emit newData(mResult, t); } } void GyroSensor::sumBias(const QVector<int> &gyroData, trikKernel::TimeVal) { // qDebug() << "b"; mGyroSum[0] -= gyroData[1]; mGyroSum[1] -= gyroData[0]; mGyroSum[2] += gyroData[2]; mGyroCounter++; } void GyroSensor::initParams() { disconnect(mVectorSensorWorker.data(), SIGNAL(newData(QVector<int>,trikKernel::TimeVal)) , this, SLOT(sumBias(QVector<int>,trikKernel::TimeVal))); disconnect(mAccelerometer, SIGNAL(newData(QVector<int>,trikKernel::TimeVal)) , this, SLOT(sumAccelerometer(QVector<int>,trikKernel::TimeVal))); if (mGyroCounter != 0) { for (int i = 0; i < 3; i++) { mBias[i] = (mGyroSum[i] << GYRO_ARITHM_PRECISION) / mGyroCounter; mGyroSum[i] = 0; } } mGyroCounter = 0; mIsCalibrated = true; mQ = QQuaternion(1, 0, 0, 0); if (mAccelerometerCounter != 0) { for (int i = 0; i < 3; i++) { mAccelerometerVector[i] = mAccelerometerSum[i] / mAccelerometerCounter; qDebug() << mAccelerometerVector[i]; mAccelerometerSum[i] = 0; } } mAccelerometerCounter = 0; QVector3D acc(mAccelerometerVector[0], mAccelerometerVector[1], mAccelerometerVector[2]); acc.normalize(); qDebug() << acc.x() << ";" << acc.y() << ";" << acc.z(); QVector3D gravity(0, 0, 1); float dot = QVector3D::dotProduct(acc, gravity); QVector3D cross = QVector3D::crossProduct(acc, gravity); // qDebug() << cross.x() << ";" << cross.y() << ";" << cross.z(); // qDebug() << dot; double t = sqrt(2) / 2; mQ = QQuaternion(t, 0, -t, 0); // mQ.normalize(); qDebug() << mQ.scalar() << ";" << mQ.x() << ";" << mQ.y() << ";" << mQ.z(); } void GyroSensor::sumAccelerometer(const QVector<int> &accelerometerData, const trikKernel::TimeVal &) { // qDebug() << "a"; mAccelerometerSum[0] += accelerometerData[0]; mAccelerometerSum[1] += accelerometerData[1]; mAccelerometerSum[2] += accelerometerData[2]; mAccelerometerCounter++; } QVector3D GyroSensor::getEulerAngles() { float pitch = 0.0; float roll = 0.0; float yaw = 0.0; float xp = mQ.x(); float yp = mQ.y(); float zp = mQ.z(); float wp = mQ.scalar(); float xx = xp * xp; float xy = xp * yp; float xz = xp * zp; float xw = xp * wp; float yy = yp * yp; float yz = yp * zp; float yw = yp * wp; float zz = zp * zp; float zw = zp * wp; const float lengthSquared = xx + yy + zz + wp * wp; if (!qFuzzyIsNull(lengthSquared - 1.0f) && !qFuzzyIsNull(lengthSquared)) { xx /= lengthSquared; xy /= lengthSquared; // same as (xp / length) * (yp / length) xz /= lengthSquared; xw /= lengthSquared; yy /= lengthSquared; yz /= lengthSquared; yw /= lengthSquared; zz /= lengthSquared; zw /= lengthSquared; } pitch = std::asin(-2.0f * (yz - xw)); if (pitch < M_PI_2) { if (pitch > -M_PI_2) { yaw = std::atan2(2.0f * (xz + yw), 1.0f - 2.0f * (xx + yy)); roll = std::atan2(2.0f * (xy + zw), 1.0f - 2.0f * (xx + zz)); } else { // not a unique solution roll = 0.0f; yaw = -std::atan2(-2.0f * (xy - zw), 1.0f - 2.0f * (yy + zz)); } } else { // not a unique solution roll = 0.0f; yaw = std::atan2(-2.0f * (xy - zw), 1.0f - 2.0f * (yy + zz)); } pitch = pitch * RAD_TO_MDEG; yaw = yaw * RAD_TO_MDEG; roll = roll * RAD_TO_MDEG; return QVector3D(pitch, roll, yaw); } <commit_msg>with rotation<commit_after>/* Copyright 2016 Anastasiya Kornilova. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "gyroSensor.h" #include <qmath.h> #include <trikKernel/configurer.h> #include <trikKernel/timeVal.h> #include <QsLog.h> #include <cmath> #include "vectorSensorWorker.h" using namespace trikControl; static constexpr int GYRO_ARITHM_PRECISION = 8; static constexpr double GYRO_250DPS = 8.75 / (1 << GYRO_ARITHM_PRECISION) ; static constexpr double pi() { return 3.14159265358979323846;} static constexpr double RAD_TO_MDEG = 1000 * 180 / pi(); GyroSensor::GyroSensor(const QString &deviceName, const trikKernel::Configurer &configurer , const trikHal::HardwareAbstractionInterface &hardwareAbstraction, VectorSensorInterface *accelerometer) : mState(deviceName) , mIsCalibrated(false) , mQ(QQuaternion(1, 0, 0, 0)) , mGyroCounter(0) , mLastUpdate(trikKernel::TimeVal(0, 0)) , mAccelerometer(accelerometer) { mVectorSensorWorker.reset(new VectorSensorWorker(configurer.attributeByDevice(deviceName, "deviceFile"), mState , hardwareAbstraction, mWorkerThread)); mBias.resize(3); mGyroSum.resize(3); mResult.resize(7); mRawData.resize(4); mAccelerometerVector.resize(3); mAccelerometerSum.resize(3); mAccelerometerCounter = 0; qDebug() << "constr"; mCalibrationTimer.moveToThread(&mWorkerThread); mCalibrationTimer.setSingleShot(true); if (!mState.isFailed()) { qRegisterMetaType<trikKernel::TimeVal>("trikKernel::TimeVal"); connect(mVectorSensorWorker.data(), SIGNAL(newData(QVector<int>,trikKernel::TimeVal)) , this, SLOT(countTilt(QVector<int>,trikKernel::TimeVal))); connect(&mCalibrationTimer, SIGNAL(timeout()), this, SLOT(initParams())); QLOG_INFO() << "Starting VectorSensor worker thread" << &mWorkerThread; mState.ready(); } } GyroSensor::~GyroSensor() { if (mWorkerThread.isRunning()) { QMetaObject::invokeMethod(mVectorSensorWorker.data(), "deinitialize"); mWorkerThread.quit(); mWorkerThread.wait(); } } GyroSensor::Status GyroSensor::status() const { return mState.status(); } const QQuaternion &GyroSensor::Q() const { return mQ; } QVector<int> GyroSensor::read() const { return mResult; } QVector<int> GyroSensor::readRawData() const { return mRawData; } void GyroSensor::calibrate(int msec) { qDebug() << "calib"; mCalibrationTimer.start(msec); connect(mVectorSensorWorker.data(), SIGNAL(newData(QVector<int>,trikKernel::TimeVal)) , this, SLOT(sumBias(QVector<int>,trikKernel::TimeVal))); connect(mAccelerometer, SIGNAL(newData(QVector<int>,trikKernel::TimeVal)) , this, SLOT(sumAccelerometer(QVector<int>,trikKernel::TimeVal))); mIsCalibrated = false; } bool GyroSensor::isCalibrated() const { return mIsCalibrated; } void GyroSensor::countTilt(const QVector<int> &gyroData, trikKernel::TimeVal t) { mRawData[0] = -gyroData[1]; mRawData[1] = -gyroData[0]; mRawData[2] = gyroData[2]; mRawData[3] = t.packedUInt32(); static bool timeInited = false; if (!timeInited) { timeInited = true; mLastUpdate = t; } else { const auto r0 = ((gyroData[0]<<GYRO_ARITHM_PRECISION) - mBias[0]) * GYRO_250DPS; const auto r1 = ((gyroData[1]<<GYRO_ARITHM_PRECISION) - mBias[1]) * GYRO_250DPS; const auto r2 = ((gyroData[2]<<GYRO_ARITHM_PRECISION) - mBias[2]) * GYRO_250DPS; mResult[0] = r0; mResult[1] = r1; mResult[2] = r2; mResult[3] = t.packedUInt32(); constexpr auto deltaConst = pi() / 180 / 1000 / 1000000 / 2; const auto dt = (t - mLastUpdate) * deltaConst; const auto x = r0 * dt; const auto y = r1 * dt; const auto z = r2 * dt; const auto c1 = std::cos(z); const auto s1 = std::sin(z); const auto c2 = std::cos(y); const auto s2 = std::sin(y); const auto c3 = std::cos(x); const auto s3 = std::sin(x); QQuaternion deltaQ; deltaQ.setScalar(c1 * c2 * c3 + s1 * s2 * s3); deltaQ.setX(s1 * c2 * c3 - c1 * s2 * s3); deltaQ.setY(c1 * s2 * c3 + s1 * c2 * s3); deltaQ.setZ(c1 * c2 * s3 - s1 * s2 * c3); mQ *= deltaQ; mQ.normalize(); mLastUpdate = t; QVector3D euler = getEulerAngles(); mResult[4] = euler.x(); mResult[5] = euler.y(); mResult[6] = euler.z(); emit newData(mResult, t); } } void GyroSensor::sumBias(const QVector<int> &gyroData, trikKernel::TimeVal) { // qDebug() << "b"; mGyroSum[0] -= gyroData[1]; mGyroSum[1] -= gyroData[0]; mGyroSum[2] += gyroData[2]; mGyroCounter++; } void GyroSensor::initParams() { disconnect(mVectorSensorWorker.data(), SIGNAL(newData(QVector<int>,trikKernel::TimeVal)) , this, SLOT(sumBias(QVector<int>,trikKernel::TimeVal))); disconnect(mAccelerometer, SIGNAL(newData(QVector<int>,trikKernel::TimeVal)) , this, SLOT(sumAccelerometer(QVector<int>,trikKernel::TimeVal))); if (mGyroCounter != 0) { for (int i = 0; i < 3; i++) { mBias[i] = (mGyroSum[i] << GYRO_ARITHM_PRECISION) / mGyroCounter; mGyroSum[i] = 0; } } mGyroCounter = 0; mIsCalibrated = true; mQ = QQuaternion(1, 0, 0, 0); if (mAccelerometerCounter != 0) { for (int i = 0; i < 3; i++) { mAccelerometerVector[i] = mAccelerometerSum[i] / mAccelerometerCounter; qDebug() << mAccelerometerVector[i]; mAccelerometerSum[i] = 0; } } mAccelerometerCounter = 0; QVector3D acc(mAccelerometerVector[0], mAccelerometerVector[1], mAccelerometerVector[2]); acc.normalize(); qDebug() << acc.x() << ";" << acc.y() << ";" << acc.z(); QVector3D gravity(0, 0, 1); float dot = QVector3D::dotProduct(acc, gravity); QVector3D cross = QVector3D::crossProduct(acc, gravity); // qDebug() << cross.x() << ";" << cross.y() << ";" << cross.z(); // qDebug() << dot; double t = sqrt(2) / 2; // mQ = QQuaternion(t, 0, -t, 0); // mQ.normalize(); qDebug() << mQ.scalar() << ";" << mQ.x() << ";" << mQ.y() << ";" << mQ.z(); } void GyroSensor::sumAccelerometer(const QVector<int> &accelerometerData, const trikKernel::TimeVal &) { // qDebug() << "a"; mAccelerometerSum[0] += accelerometerData[0]; mAccelerometerSum[1] += accelerometerData[1]; mAccelerometerSum[2] += accelerometerData[2]; mAccelerometerCounter++; } QVector3D GyroSensor::getEulerAngles() { float pitch = 0.0; float roll = 0.0; float yaw = 0.0; float xp = mQ.x(); float yp = mQ.y(); float zp = mQ.z(); float wp = mQ.scalar(); float xx = xp * xp; float xy = xp * yp; float xz = xp * zp; float xw = xp * wp; float yy = yp * yp; float yz = yp * zp; float yw = yp * wp; float zz = zp * zp; float zw = zp * wp; const float lengthSquared = xx + yy + zz + wp * wp; if (!qFuzzyIsNull(lengthSquared - 1.0f) && !qFuzzyIsNull(lengthSquared)) { xx /= lengthSquared; xy /= lengthSquared; // same as (xp / length) * (yp / length) xz /= lengthSquared; xw /= lengthSquared; yy /= lengthSquared; yz /= lengthSquared; yw /= lengthSquared; zz /= lengthSquared; zw /= lengthSquared; } pitch = std::asin(-2.0f * (yz - xw)); if (pitch < M_PI_2) { if (pitch > -M_PI_2) { yaw = std::atan2(2.0f * (xz + yw), 1.0f - 2.0f * (xx + yy)); roll = std::atan2(2.0f * (xy + zw), 1.0f - 2.0f * (xx + zz)); } else { // not a unique solution roll = 0.0f; yaw = -std::atan2(-2.0f * (xy - zw), 1.0f - 2.0f * (yy + zz)); } } else { // not a unique solution roll = 0.0f; yaw = std::atan2(-2.0f * (xy - zw), 1.0f - 2.0f * (yy + zz)); } pitch = pitch * RAD_TO_MDEG; yaw = yaw * RAD_TO_MDEG; roll = roll * RAD_TO_MDEG; return QVector3D(pitch, roll, yaw); } <|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2013 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following ** disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ***********************************************************************************************************************/ #include "AutoTypeExpression.h" #include "../../declarations/VariableDeclaration.h" #include "../../types/ErrorType.h" #include "../../types/PointerType.h" #include "../../types/ReferenceType.h" #include "PointerTypeExpression.h" #include "ReferenceTypeExpression.h" #include "ModelBase/src/nodes/TypedListDefinition.h" DEFINE_TYPED_LIST(OOModel::AutoTypeExpression) namespace OOModel { COMPOSITENODE_DEFINE_EMPTY_CONSTRUCTORS(AutoTypeExpression) COMPOSITENODE_DEFINE_TYPE_REGISTRATION_METHODS(AutoTypeExpression) Type* AutoTypeExpression::type() { auto p = parent(); VariableDeclaration* varDecl = nullptr; if(!(varDecl = dynamic_cast<VariableDeclaration*>(p))) varDecl = dynamic_cast<VariableDeclaration*>(p->parent()); Q_ASSERT(varDecl); if(!varDecl->initialValue()) return new ErrorType("No initial value in auto type"); auto initType = varDecl->initialValue()->type(); if(varDecl == p) return initType; if(dynamic_cast<ReferenceTypeExpression*>(p)) return new ReferenceType(initType, initType->isValueType()); if(dynamic_cast<PointerTypeExpression*>(p)) return new PointerType(initType, initType->isValueType()); return new ErrorType("Could not find type of auto expression"); } } <commit_msg>Add support for const / volatile auto type<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2013 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following ** disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ***********************************************************************************************************************/ #include "AutoTypeExpression.h" #include "../../declarations/VariableDeclaration.h" #include "../../types/ErrorType.h" #include "../../types/PointerType.h" #include "../../types/ReferenceType.h" #include "PointerTypeExpression.h" #include "ReferenceTypeExpression.h" #include "ModelBase/src/nodes/TypedListDefinition.h" DEFINE_TYPED_LIST(OOModel::AutoTypeExpression) namespace OOModel { COMPOSITENODE_DEFINE_EMPTY_CONSTRUCTORS(AutoTypeExpression) COMPOSITENODE_DEFINE_TYPE_REGISTRATION_METHODS(AutoTypeExpression) Type* AutoTypeExpression::type() { /** * TODO: like this we return the wrong type for auto && * note however that const and volatile are supported as TypeQualifierExpression * adds the qualifier when calling the type() method **/ auto p = parent(); Model::Node* current = this; VariableDeclaration* varDecl = nullptr; while(!(varDecl = dynamic_cast<VariableDeclaration*>(p))) { current = p; p = p->parent(); Q_ASSERT(p); } if(!varDecl->initialValue()) return new ErrorType("No initial value in auto type"); auto initType = varDecl->initialValue()->type(); if(varDecl == p) return initType; if(dynamic_cast<ReferenceTypeExpression*>(current)) return new ReferenceType(initType, initType->isValueType()); if(dynamic_cast<PointerTypeExpression*>(current)) return new PointerType(initType, initType->isValueType()); return new ErrorType("Could not find type of auto expression"); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: process_impl.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2003-03-26 16:46:05 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _STRINGS_H #include <strings.h> #endif #ifndef _STDLIB_H #include <stdlib.h> #endif #ifndef _OSL_PROCESS_H_ #include <osl/process.h> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _OSL_THREAD_H_ #include <osl/thread.h> #endif #ifndef _OSL_FILE_HXX_ #include <osl/file.hxx> #endif #ifndef _OSL_UUNXAPI_HXX_ #include "uunxapi.hxx" #endif #ifndef _OSL_FILE_PATH_HELPER_HXX_ #include "file_path_helper.hxx" #endif #include <string.h> //------------------------------------ // forward //------------------------------------ extern "C" sal_Char *getCmdLine(); extern "C" char* osl_impl_getExecutableName(char * buffer, size_t n); //------------------------------------ // private stuff //------------------------------------ namespace /* private */ { const rtl::OUString UNICHAR_SLASH = rtl::OUString::createFromAscii("/"); //------------------------------------------------------- // if the command line arg 0 contains a '/' somewhere it // has been probably invoked relatively to the current // working dir //------------------------------------------------------- inline bool is_relative_to_cwd(const rtl::OUString& path) { return (path.indexOf(UNICHAR_SLASH) > -1); } //--------------------------------------------------------- // make a relative path absolute using the current working // directory // no return value because osl_getExecutableFile either // returns osl_Process_E_None or osl_Process_E_Unknown //--------------------------------------------------------- void make_absolute_to_cwd(const rtl::OUString& relative_path, rtl::OUString& absolute_path) { rtl::OUString cwd_url; if (osl_Process_E_None == osl_getProcessWorkingDir(&cwd_url.pData)) { rtl::OUString cwd; osl::FileBase::RC rc = osl::FileBase::getSystemPathFromFileURL(cwd_url, cwd); OSL_ASSERT(osl::FileBase::E_None == rc); osl::systemPathMakeAbsolutePath(cwd, relative_path, absolute_path); } } //--------------------------------------------------------- // search for the file using the PATH environment variable // no return value because osl_getExecutableFile either // returns osl_Process_E_None or osl_Process_E_Unknown //--------------------------------------------------------- void find_in_PATH(const rtl::OUString& file_path, rtl::OUString& path_found) { rtl::OUString PATH = rtl::OUString::createFromAscii("PATH"); rtl::OUString env_path; if (osl_getEnvironment(PATH.pData, &env_path.pData) == osl_Process_E_None) osl::searchPath(file_path, env_path, path_found); } } // namespace /private */ /*************************************** osl_getExecutableFile **************************************/ oslProcessError SAL_CALL osl_getExecutableFile(rtl_uString** ppustrFile) { sal_Char* p_cmdline = getCmdLine(); rtl::OUString cmdline(p_cmdline, strlen(p_cmdline), osl_getThreadTextEncoding()); free(p_cmdline); rtl::OUString abs_path; if (osl::systemPathIsRelativePath(cmdline)) { if (is_relative_to_cwd(cmdline)) make_absolute_to_cwd(cmdline, abs_path); else find_in_PATH(cmdline, abs_path); } else { abs_path = cmdline; } rtl::OUString path_resolved; oslProcessError osl_error = osl_Process_E_Unknown; if ((abs_path.getLength() > 0) && osl::realpath(abs_path, path_resolved)) { rtl::OUString furl; osl::FileBase::RC rc = osl::FileBase::getFileURLFromSystemPath(path_resolved.pData, furl); OSL_ASSERT(osl::FileBase::E_None == rc); rtl_uString_assign(ppustrFile, furl.pData); osl_error = osl_Process_E_None; } return osl_error; } /*************************************** Necessary for signal.c **************************************/ char* osl_impl_getExecutableName(char * buffer, size_t n) { sal_Char* p_cmdline = getCmdLine(); rtl::OUString cmdline(p_cmdline, strlen(p_cmdline), osl_getThreadTextEncoding()); free(p_cmdline); rtl::OUString exename_u; osl::systemPathGetFileNameOrLastDirectoryPart(cmdline, exename_u); rtl::OString exename_a = rtl::OUStringToOString(exename_u, osl_getThreadTextEncoding()); char* pChrRet = NULL; if (exename_a.getLength() < n) { strcpy(buffer, exename_a.getStr()); pChrRet = buffer; } return pChrRet; } <commit_msg>INTEGRATION: CWS ooo11rc (1.2.52); FILE MERGED 2003/06/27 15:18:29 haggai 1.2.52.1: #i12645# handle NULL return from getCmdLine() safely<commit_after>/************************************************************************* * * $RCSfile: process_impl.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2003-07-02 13:34:30 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _STRINGS_H #include <strings.h> #endif #ifndef _STDLIB_H #include <stdlib.h> #endif #ifndef _OSL_PROCESS_H_ #include <osl/process.h> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _OSL_THREAD_H_ #include <osl/thread.h> #endif #ifndef _OSL_FILE_HXX_ #include <osl/file.hxx> #endif #ifndef _OSL_UUNXAPI_HXX_ #include "uunxapi.hxx" #endif #ifndef _OSL_FILE_PATH_HELPER_HXX_ #include "file_path_helper.hxx" #endif #include <string.h> //------------------------------------ // forward //------------------------------------ extern "C" sal_Char *getCmdLine(); extern "C" char* osl_impl_getExecutableName(char * buffer, size_t n); //------------------------------------ // private stuff //------------------------------------ namespace /* private */ { const rtl::OUString UNICHAR_SLASH = rtl::OUString::createFromAscii("/"); //------------------------------------------------------- // if the command line arg 0 contains a '/' somewhere it // has been probably invoked relatively to the current // working dir //------------------------------------------------------- inline bool is_relative_to_cwd(const rtl::OUString& path) { return (path.indexOf(UNICHAR_SLASH) > -1); } //--------------------------------------------------------- // make a relative path absolute using the current working // directory // no return value because osl_getExecutableFile either // returns osl_Process_E_None or osl_Process_E_Unknown //--------------------------------------------------------- void make_absolute_to_cwd(const rtl::OUString& relative_path, rtl::OUString& absolute_path) { rtl::OUString cwd_url; if (osl_Process_E_None == osl_getProcessWorkingDir(&cwd_url.pData)) { rtl::OUString cwd; osl::FileBase::RC rc = osl::FileBase::getSystemPathFromFileURL(cwd_url, cwd); OSL_ASSERT(osl::FileBase::E_None == rc); osl::systemPathMakeAbsolutePath(cwd, relative_path, absolute_path); } } //--------------------------------------------------------- // search for the file using the PATH environment variable // no return value because osl_getExecutableFile either // returns osl_Process_E_None or osl_Process_E_Unknown //--------------------------------------------------------- void find_in_PATH(const rtl::OUString& file_path, rtl::OUString& path_found) { rtl::OUString PATH = rtl::OUString::createFromAscii("PATH"); rtl::OUString env_path; if (osl_getEnvironment(PATH.pData, &env_path.pData) == osl_Process_E_None) osl::searchPath(file_path, env_path, path_found); } } // namespace /private */ /*************************************** osl_getExecutableFile **************************************/ oslProcessError SAL_CALL osl_getExecutableFile(rtl_uString** ppustrFile) { sal_Char* p_cmdline = getCmdLine(); oslProcessError osl_error = osl_Process_E_Unknown; if (p_cmdline != 0) { rtl::OUString cmdline(p_cmdline, strlen(p_cmdline), osl_getThreadTextEncoding()); free(p_cmdline); rtl::OUString abs_path; if (osl::systemPathIsRelativePath(cmdline)) { if (is_relative_to_cwd(cmdline)) make_absolute_to_cwd(cmdline, abs_path); else find_in_PATH(cmdline, abs_path); } else { abs_path = cmdline; } rtl::OUString path_resolved; if ((abs_path.getLength() > 0) && osl::realpath(abs_path, path_resolved)) { rtl::OUString furl; osl::FileBase::RC rc = osl::FileBase::getFileURLFromSystemPath(path_resolved.pData, furl); OSL_ASSERT(osl::FileBase::E_None == rc); rtl_uString_assign(ppustrFile, furl.pData); osl_error = osl_Process_E_None; } } return osl_error; } /*************************************** Necessary for signal.c **************************************/ char* osl_impl_getExecutableName(char * buffer, size_t n) { sal_Char* p_cmdline = getCmdLine(); char* pChrRet = NULL; if (p_cmdline != 0) { rtl::OUString cmdline(p_cmdline, strlen(p_cmdline), osl_getThreadTextEncoding()); free(p_cmdline); rtl::OUString exename_u; osl::systemPathGetFileNameOrLastDirectoryPart(cmdline, exename_u); rtl::OString exename_a = rtl::OUStringToOString(exename_u, osl_getThreadTextEncoding()); if (exename_a.getLength() < n) { strcpy(buffer, exename_a.getStr()); pChrRet = buffer; } } return pChrRet; } <|endoftext|>
<commit_before>// // Copyright (c) 2008 Advanced Micro Devices, Inc. All rights reserved. // #include "device/gpu/gpudefs.hpp" #include "device/gpu/gpuprogram.hpp" #include "device/gpu/gpukernel.hpp" #include "acl.h" #include "SCShadersSi.h" #include "si_ci_merged_offset.h" #include <string> #include <fstream> #include <sstream> #include <iostream> #include <ctime> namespace gpu { bool NullKernel::siCreateHwInfo(const void* shader, AMUabiAddEncoding& encoding) { static const uint NumSiCsInfos = (70 + 5 + 1 + 32 + 6); CALProgramInfoEntry* newInfos; uint i = 0; uint infoCount = NumSiCsInfos; const SC_SI_HWSHADER_CS* cShader = reinterpret_cast<const SC_SI_HWSHADER_CS*>(shader); newInfos = new CALProgramInfoEntry[infoCount]; encoding.progInfos = newInfos; if (encoding.progInfos == 0) { infoCount = 0; return false; } newInfos[i].address = AMU_ABI_USER_ELEMENT_COUNT; newInfos[i].value = cShader->common.userElementCount; i++; for (unsigned int j = 0; j < cShader->common.userElementCount; j++) { newInfos[i].address = AMU_ABI_USER_ELEMENTS_0_DWORD0 + 4*j; newInfos[i].value = HWSHADER_Get(cShader, common.pUserElements)[j].dataClass; i++; newInfos[i].address = AMU_ABI_USER_ELEMENTS_0_DWORD1 + 4*j; newInfos[i].value = HWSHADER_Get(cShader, common.pUserElements)[j].apiSlot; i++; newInfos[i].address = AMU_ABI_USER_ELEMENTS_0_DWORD2 + 4*j; newInfos[i].value = HWSHADER_Get(cShader, common.pUserElements)[j].startUserReg; i++; newInfos[i].address = AMU_ABI_USER_ELEMENTS_0_DWORD3 + 4*j; newInfos[i].value = HWSHADER_Get(cShader, common.pUserElements)[j].userRegCount; i++; } newInfos[i].address = AMU_ABI_SI_NUM_VGPRS; newInfos[i].value = cShader->common.numVgprs; i++; newInfos[i].address = AMU_ABI_SI_NUM_SGPRS; newInfos[i].value = cShader->common.numSgprs; i++; newInfos[i].address = AMU_ABI_SI_NUM_SGPRS_AVAIL; newInfos[i].value = 104-2; //512;//options.NumSGPRsAvailable; i++; newInfos[i].address = AMU_ABI_SI_NUM_VGPRS_AVAIL; newInfos[i].value = 256;//options.NumVGPRsAvailable; i++; newInfos[i].address = AMU_ABI_SI_FLOAT_MODE; newInfos[i].value = cShader->common.floatMode; i++; newInfos[i].address = AMU_ABI_SI_IEEE_MODE; newInfos[i].value = cShader->common.bIeeeMode; i++; newInfos[i].address = AMU_ABI_SI_SCRATCH_SIZE; newInfos[i].value = cShader->common.scratchSize;; i++; newInfos[i].address = mmCOMPUTE_PGM_RSRC2; newInfos[i].value = cShader->computePgmRsrc2.u32All; i++; newInfos[i].address = AMU_ABI_NUM_THREAD_PER_GROUP_X; newInfos[i].value = cShader->numThreadX; i++; newInfos[i].address = AMU_ABI_NUM_THREAD_PER_GROUP_Y; newInfos[i].value = cShader->numThreadY; i++; newInfos[i].address = AMU_ABI_NUM_THREAD_PER_GROUP_Z; newInfos[i].value = cShader->numThreadZ; i++; newInfos[i].address = AMU_ABI_ORDERED_APPEND_ENABLE; newInfos[i].value = cShader->bOrderedAppendEnable; i++; newInfos[i].address = AMU_ABI_RAT_OP_IS_USED; newInfos[i].value = cShader->common.uavResourceUsage[0]; i++; for (unsigned int j = 0; j < ((SC_MAX_UAV + 31) / 32); j++) { newInfos[i].address = AMU_ABI_UAV_RESOURCE_MASK_0 + j; newInfos[i].value = cShader->common.uavResourceUsage[j]; i++; } newInfos[i].address = AMU_ABI_NUM_WAVEFRONT_PER_SIMD; // Setting the same as for scWrapR800Info newInfos[i].value = 1; i++; newInfos[i].address = AMU_ABI_WAVEFRONT_SIZE; newInfos[i].value = nullDev().hwInfo()->simdWidth_ * 4; //options.WavefrontSize; i++; newInfos[i].address = AMU_ABI_LDS_SIZE_AVAIL; newInfos[i].value = 32*1024; //options.LDSSize; i++; newInfos[i].address = AMU_ABI_LDS_SIZE_USED; newInfos[i].value = 64 * 4 * cShader->computePgmRsrc2.bits.LDS_SIZE; i++; infoCount = i; assert((i + 4 * (16 - cShader->common.userElementCount)) == NumSiCsInfos); encoding.progInfosCount = infoCount; CALUavMask uavMask; memcpy(uavMask.mask, cShader->common.uavResourceUsage, sizeof(CALUavMask)); encoding.uavMask = uavMask; encoding.textData = HWSHADER_Get(cShader, common.hShaderMemHandle); encoding.textSize = cShader->common.codeLenInByte; instructionCnt_ = encoding.textSize / sizeof(uint32_t); encoding.scratchRegisterCount = cShader->common.scratchSize; encoding.UAVReturnBufferTotalSize = 0; return true; } bool HSAILKernel::aqlCreateHWInfo(const void* shader, size_t shaderSize) { // Copy the shader_isa into a buffer hwMetaData_ = new char[shaderSize]; if (hwMetaData_ == NULL) { return false; } memcpy(hwMetaData_, shader, shaderSize); SC_SI_HWSHADER_CS* siMetaData = reinterpret_cast<SC_SI_HWSHADER_CS*>(hwMetaData_); // Code to patch the pointers in the shader object. // Must be preferably done in the compiler library size_t offset = siMetaData->common.uSizeInBytes; if (siMetaData->common.u32PvtDataSizeInBytes > 0) { siMetaData->common.pPvtData = reinterpret_cast<SC_BYTE *>( reinterpret_cast<char *>(siMetaData) + offset); offset += siMetaData->common.u32PvtDataSizeInBytes; } if (siMetaData->common.codeLenInByte > 0) { siMetaData->common.hShaderMemHandle = reinterpret_cast<char *>(siMetaData) + offset; offset += siMetaData->common.codeLenInByte; } char* headerBaseAddress = reinterpret_cast<char*>(siMetaData->common.hShaderMemHandle); hsa_ext_code_descriptor_t* hcd = reinterpret_cast<hsa_ext_code_descriptor_t*>(headerBaseAddress); amd_kernel_code_t* akc = reinterpret_cast<amd_kernel_code_t*>( headerBaseAddress + hcd->code.handle); address codeStartAddress = reinterpret_cast<address>(akc); address codeEndAddress = reinterpret_cast<address>(hcd) + siMetaData->common.codeLenInByte; uint64_t codeSize = codeEndAddress - codeStartAddress; code_ = new gpu::Memory(dev(), amd::alignUp(codeSize, gpu::ConstBuffer::VectorSize)); // Initialize kernel ISA code if ((code_ != NULL) && code_->create(Resource::Local)) { address cpuCodePtr = static_cast<address>(code_->map(NULL, Resource::WriteOnly)); // Copy only amd_kernel_code_t memcpy(cpuCodePtr, codeStartAddress, codeSize); code_->unmap(NULL); } else { LogError("Failed to allocate ISA code!"); return false; } cpuAqlCode_ = akc; assert((akc->workitem_private_segment_byte_size & 3) == 0 && "Scratch must be DWORD aligned"); workGroupInfo_.scratchRegs_ = amd::alignUp(akc->workitem_private_segment_byte_size, 16) / sizeof(uint); workGroupInfo_.availableSGPRs_ = dev().gslCtx()->getNumSGPRsAvailable(); workGroupInfo_.availableVGPRs_ = dev().gslCtx()->getNumVGPRsAvailable(); workGroupInfo_.preferredSizeMultiple_ = dev().getAttribs().wavefrontSize; workGroupInfo_.privateMemSize_ = akc->workitem_private_segment_byte_size; workGroupInfo_.localMemSize_ = workGroupInfo_.usedLDSSize_ = akc->workgroup_group_segment_byte_size; workGroupInfo_.usedSGPRs_ = akc->wavefront_sgpr_count; workGroupInfo_.usedStackSize_ = 0; workGroupInfo_.usedVGPRs_ = akc->workitem_vgpr_count; workGroupInfo_.wavefrontPerSIMD_ = dev().getAttribs().wavefrontSize; return true; } } // namespace gpu <commit_msg>P4 to Git Change 1084700 by ericz@fl_ericz3 on 2014/10/06 18:17:12<commit_after>// // Copyright (c) 2008 Advanced Micro Devices, Inc. All rights reserved. // #include "device/gpu/gpudefs.hpp" #include "device/gpu/gpuprogram.hpp" #include "device/gpu/gpukernel.hpp" #include "acl.h" #include "SCShadersSi.h" #include "si_ci_vi_merged_offset.h" #include <string> #include <fstream> #include <sstream> #include <iostream> #include <ctime> namespace gpu { bool NullKernel::siCreateHwInfo(const void* shader, AMUabiAddEncoding& encoding) { static const uint NumSiCsInfos = (70 + 5 + 1 + 32 + 6); CALProgramInfoEntry* newInfos; uint i = 0; uint infoCount = NumSiCsInfos; const SC_SI_HWSHADER_CS* cShader = reinterpret_cast<const SC_SI_HWSHADER_CS*>(shader); newInfos = new CALProgramInfoEntry[infoCount]; encoding.progInfos = newInfos; if (encoding.progInfos == 0) { infoCount = 0; return false; } newInfos[i].address = AMU_ABI_USER_ELEMENT_COUNT; newInfos[i].value = cShader->common.userElementCount; i++; for (unsigned int j = 0; j < cShader->common.userElementCount; j++) { newInfos[i].address = AMU_ABI_USER_ELEMENTS_0_DWORD0 + 4*j; newInfos[i].value = HWSHADER_Get(cShader, common.pUserElements)[j].dataClass; i++; newInfos[i].address = AMU_ABI_USER_ELEMENTS_0_DWORD1 + 4*j; newInfos[i].value = HWSHADER_Get(cShader, common.pUserElements)[j].apiSlot; i++; newInfos[i].address = AMU_ABI_USER_ELEMENTS_0_DWORD2 + 4*j; newInfos[i].value = HWSHADER_Get(cShader, common.pUserElements)[j].startUserReg; i++; newInfos[i].address = AMU_ABI_USER_ELEMENTS_0_DWORD3 + 4*j; newInfos[i].value = HWSHADER_Get(cShader, common.pUserElements)[j].userRegCount; i++; } newInfos[i].address = AMU_ABI_SI_NUM_VGPRS; newInfos[i].value = cShader->common.numVgprs; i++; newInfos[i].address = AMU_ABI_SI_NUM_SGPRS; newInfos[i].value = cShader->common.numSgprs; i++; newInfos[i].address = AMU_ABI_SI_NUM_SGPRS_AVAIL; newInfos[i].value = 104-2; //512;//options.NumSGPRsAvailable; i++; newInfos[i].address = AMU_ABI_SI_NUM_VGPRS_AVAIL; newInfos[i].value = 256;//options.NumVGPRsAvailable; i++; newInfos[i].address = AMU_ABI_SI_FLOAT_MODE; newInfos[i].value = cShader->common.floatMode; i++; newInfos[i].address = AMU_ABI_SI_IEEE_MODE; newInfos[i].value = cShader->common.bIeeeMode; i++; newInfos[i].address = AMU_ABI_SI_SCRATCH_SIZE; newInfos[i].value = cShader->common.scratchSize;; i++; newInfos[i].address = mmCOMPUTE_PGM_RSRC2; newInfos[i].value = cShader->computePgmRsrc2.u32All; i++; newInfos[i].address = AMU_ABI_NUM_THREAD_PER_GROUP_X; newInfos[i].value = cShader->numThreadX; i++; newInfos[i].address = AMU_ABI_NUM_THREAD_PER_GROUP_Y; newInfos[i].value = cShader->numThreadY; i++; newInfos[i].address = AMU_ABI_NUM_THREAD_PER_GROUP_Z; newInfos[i].value = cShader->numThreadZ; i++; newInfos[i].address = AMU_ABI_ORDERED_APPEND_ENABLE; newInfos[i].value = cShader->bOrderedAppendEnable; i++; newInfos[i].address = AMU_ABI_RAT_OP_IS_USED; newInfos[i].value = cShader->common.uavResourceUsage[0]; i++; for (unsigned int j = 0; j < ((SC_MAX_UAV + 31) / 32); j++) { newInfos[i].address = AMU_ABI_UAV_RESOURCE_MASK_0 + j; newInfos[i].value = cShader->common.uavResourceUsage[j]; i++; } newInfos[i].address = AMU_ABI_NUM_WAVEFRONT_PER_SIMD; // Setting the same as for scWrapR800Info newInfos[i].value = 1; i++; newInfos[i].address = AMU_ABI_WAVEFRONT_SIZE; newInfos[i].value = nullDev().hwInfo()->simdWidth_ * 4; //options.WavefrontSize; i++; newInfos[i].address = AMU_ABI_LDS_SIZE_AVAIL; newInfos[i].value = 32*1024; //options.LDSSize; i++; newInfos[i].address = AMU_ABI_LDS_SIZE_USED; newInfos[i].value = 64 * 4 * cShader->computePgmRsrc2.bits.LDS_SIZE; i++; infoCount = i; assert((i + 4 * (16 - cShader->common.userElementCount)) == NumSiCsInfos); encoding.progInfosCount = infoCount; CALUavMask uavMask; memcpy(uavMask.mask, cShader->common.uavResourceUsage, sizeof(CALUavMask)); encoding.uavMask = uavMask; encoding.textData = HWSHADER_Get(cShader, common.hShaderMemHandle); encoding.textSize = cShader->common.codeLenInByte; instructionCnt_ = encoding.textSize / sizeof(uint32_t); encoding.scratchRegisterCount = cShader->common.scratchSize; encoding.UAVReturnBufferTotalSize = 0; return true; } bool HSAILKernel::aqlCreateHWInfo(const void* shader, size_t shaderSize) { // Copy the shader_isa into a buffer hwMetaData_ = new char[shaderSize]; if (hwMetaData_ == NULL) { return false; } memcpy(hwMetaData_, shader, shaderSize); SC_SI_HWSHADER_CS* siMetaData = reinterpret_cast<SC_SI_HWSHADER_CS*>(hwMetaData_); // Code to patch the pointers in the shader object. // Must be preferably done in the compiler library size_t offset = siMetaData->common.uSizeInBytes; if (siMetaData->common.u32PvtDataSizeInBytes > 0) { siMetaData->common.pPvtData = reinterpret_cast<SC_BYTE *>( reinterpret_cast<char *>(siMetaData) + offset); offset += siMetaData->common.u32PvtDataSizeInBytes; } if (siMetaData->common.codeLenInByte > 0) { siMetaData->common.hShaderMemHandle = reinterpret_cast<char *>(siMetaData) + offset; offset += siMetaData->common.codeLenInByte; } char* headerBaseAddress = reinterpret_cast<char*>(siMetaData->common.hShaderMemHandle); hsa_ext_code_descriptor_t* hcd = reinterpret_cast<hsa_ext_code_descriptor_t*>(headerBaseAddress); amd_kernel_code_t* akc = reinterpret_cast<amd_kernel_code_t*>( headerBaseAddress + hcd->code.handle); address codeStartAddress = reinterpret_cast<address>(akc); address codeEndAddress = reinterpret_cast<address>(hcd) + siMetaData->common.codeLenInByte; uint64_t codeSize = codeEndAddress - codeStartAddress; code_ = new gpu::Memory(dev(), amd::alignUp(codeSize, gpu::ConstBuffer::VectorSize)); // Initialize kernel ISA code if ((code_ != NULL) && code_->create(Resource::Local)) { address cpuCodePtr = static_cast<address>(code_->map(NULL, Resource::WriteOnly)); // Copy only amd_kernel_code_t memcpy(cpuCodePtr, codeStartAddress, codeSize); code_->unmap(NULL); } else { LogError("Failed to allocate ISA code!"); return false; } cpuAqlCode_ = akc; assert((akc->workitem_private_segment_byte_size & 3) == 0 && "Scratch must be DWORD aligned"); workGroupInfo_.scratchRegs_ = amd::alignUp(akc->workitem_private_segment_byte_size, 16) / sizeof(uint); workGroupInfo_.availableSGPRs_ = dev().gslCtx()->getNumSGPRsAvailable(); workGroupInfo_.availableVGPRs_ = dev().gslCtx()->getNumVGPRsAvailable(); workGroupInfo_.preferredSizeMultiple_ = dev().getAttribs().wavefrontSize; workGroupInfo_.privateMemSize_ = akc->workitem_private_segment_byte_size; workGroupInfo_.localMemSize_ = workGroupInfo_.usedLDSSize_ = akc->workgroup_group_segment_byte_size; workGroupInfo_.usedSGPRs_ = akc->wavefront_sgpr_count; workGroupInfo_.usedStackSize_ = 0; workGroupInfo_.usedVGPRs_ = akc->workitem_vgpr_count; workGroupInfo_.wavefrontPerSIMD_ = dev().getAttribs().wavefrontSize; return true; } } // namespace gpu <|endoftext|>
<commit_before>/*============================================================================= This file is part of FLINT. FLINT is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. FLINT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with FLINT; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =============================================================================*/ /****************************************************************************** Copyright (C) 2013 Mike Hansen ******************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <gmp.h> #include <float.h> #include "flint.h" #include "fmpz.h" #include "fmpz_poly.h" #include "ulong_extras.h" #include "profiler.h" #include "NTL-interface.h" #include <NTL/ZZ_pEXFactoring.h> #define nalgs 2 #define ncases 1 #define cpumin 10 int main(int argc, char** argv) { slong s[nalgs]; int c, n, len, ext, reps = 0; fmpz_t p, temp; ZZ prime; ZZ_pX mod; fq_poly_t f; fq_ctx_t ctx; fmpz_mod_poly_t fmod; flint_rand_t state; flint_randinit(state); fmpz_init(p); fmpz_set_str(p, argv[1], 10); fmpz_init(temp); fmpz_set_str(temp, argv[2], 10); ext = fmpz_get_si(temp); fmpz_set_str(temp, argv[3], 10); len = fmpz_get_si(temp); // Set the prime fmpz_get_ZZ(prime, p); ZZ_p::init(prime); // Set the modulus BuildIrred(mod, ext + 1); fmpz_mod_poly_init(fmod, p); //fmpz_mod_poly_randtest_not_zero(fmod, state, ext + 1); //fmpz_mod_poly_set_coeff_ui(fmod, ext, 1); fmpz_mod_poly_set_ZZ_pX(fmod, mod); ZZ_pE::init(mod); fq_ctx_init_modulus(ctx, p, ext, fmod, "a"); fq_poly_init(f); for (c = 0; c < nalgs; c++) { s[c] = 0L; } for (n = 0; n < ncases; n++) { timeit_t t[nalgs]; int l, loops = 1; ZZ_pEX nf; vec_pair_ZZ_pEX_long v; fq_poly_factor_t res; /* Construct random elements of fq */ { fq_poly_randtest(f, state, len, ctx); fq_poly_make_monic(f, f, ctx); fq_poly_get_ZZ_pEX(nf, f); } loop: fflush(stdout); timeit_start(t[0]); for (l = 0; l < loops; l++) fq_poly_factor_init(res, ctx); fq_poly_factor_kaltofen_shoup(res, f, ctx); fq_poly_factor_clear(res); timeit_stop(t[0]); timeit_start(t[1]); for (l = 0; l < loops; l++) v = CanZass(nf); timeit_stop(t[1]); for (c = 0; c < nalgs; c++) if (t[c]->cpu <= cpumin) { flint_printf("%d ", t[c]->cpu); loops *= 2; goto loop; } for (c = 0; c < nalgs; c++) s[c] += t[c]->cpu; reps += loops; } for (c = 0; c < nalgs; c++) { flint_printf("%20f ", s[c] / (double) reps); fflush(stdout); } printf("\n"); fq_poly_clear(f); fmpz_mod_poly_clear(fmod); fq_ctx_clear(ctx); fmpz_clear(p); fmpz_clear(temp); flint_randclear(state); } <commit_msg>Remove extra printing from p-factor_kaltofen_shoup_vs_ntl.cpp<commit_after>/*============================================================================= This file is part of FLINT. FLINT is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. FLINT is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with FLINT; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA =============================================================================*/ /****************************************************************************** Copyright (C) 2013 Mike Hansen ******************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <gmp.h> #include <float.h> #include "flint.h" #include "fmpz.h" #include "fmpz_poly.h" #include "ulong_extras.h" #include "profiler.h" #include "NTL-interface.h" #include <NTL/ZZ_pEXFactoring.h> #define nalgs 2 #define ncases 1 #define cpumin 10 int main(int argc, char** argv) { slong s[nalgs]; int c, n, len, ext, reps = 0; fmpz_t p, temp; ZZ prime; ZZ_pX mod; fq_poly_t f; fq_ctx_t ctx; fmpz_mod_poly_t fmod; flint_rand_t state; flint_randinit(state); fmpz_init(p); fmpz_set_str(p, argv[1], 10); fmpz_init(temp); fmpz_set_str(temp, argv[2], 10); ext = fmpz_get_si(temp); fmpz_set_str(temp, argv[3], 10); len = fmpz_get_si(temp); // Set the prime fmpz_get_ZZ(prime, p); ZZ_p::init(prime); // Set the modulus BuildIrred(mod, ext + 1); fmpz_mod_poly_init(fmod, p); //fmpz_mod_poly_randtest_not_zero(fmod, state, ext + 1); //fmpz_mod_poly_set_coeff_ui(fmod, ext, 1); fmpz_mod_poly_set_ZZ_pX(fmod, mod); ZZ_pE::init(mod); fq_ctx_init_modulus(ctx, p, ext, fmod, "a"); fq_poly_init(f); for (c = 0; c < nalgs; c++) { s[c] = 0L; } for (n = 0; n < ncases; n++) { timeit_t t[nalgs]; int l, loops = 1; ZZ_pEX nf; vec_pair_ZZ_pEX_long v; fq_poly_factor_t res; /* Construct random elements of fq */ { fq_poly_randtest(f, state, len, ctx); fq_poly_make_monic(f, f, ctx); fq_poly_get_ZZ_pEX(nf, f); } loop: fflush(stdout); timeit_start(t[0]); for (l = 0; l < loops; l++) fq_poly_factor_init(res, ctx); fq_poly_factor_kaltofen_shoup(res, f, ctx); fq_poly_factor_clear(res); timeit_stop(t[0]); timeit_start(t[1]); for (l = 0; l < loops; l++) v = CanZass(nf); timeit_stop(t[1]); for (c = 0; c < nalgs; c++) if (t[c]->cpu <= cpumin) { loops *= 2; goto loop; } for (c = 0; c < nalgs; c++) s[c] += t[c]->cpu; reps += loops; } for (c = 0; c < nalgs; c++) { flint_printf("%20f ", s[c] / (double) reps); fflush(stdout); } printf("\n"); fq_poly_clear(f); fmpz_mod_poly_clear(fmod); fq_ctx_clear(ctx); fmpz_clear(p); fmpz_clear(temp); flint_randclear(state); } <|endoftext|>
<commit_before> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2011 Francois Beaune // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "progressiveframerenderer.h" // appleseed.renderer headers. #include "renderer/kernel/rendering/progressive/samplecounter.h" #include "renderer/kernel/rendering/progressive/samplegeneratorjob.h" #include "renderer/kernel/rendering/accumulationframebuffer.h" #include "renderer/kernel/rendering/framerendererbase.h" #include "renderer/kernel/rendering/isamplegenerator.h" #include "renderer/kernel/rendering/itilecallback.h" #include "renderer/modeling/frame/frame.h" #include "renderer/modeling/project/project.h" // appleseed.foundation headers. #include "foundation/image/analysis.h" #include "foundation/image/canvasproperties.h" #include "foundation/image/genericimagefilereader.h" #include "foundation/image/image.h" #include "foundation/math/fixedsizehistory.h" #include "foundation/platform/thread.h" #include "foundation/platform/timer.h" #include "foundation/utility/foreach.h" #include "foundation/utility/job.h" #include "foundation/utility/maplefile.h" #include "foundation/utility/searchpaths.h" #include "foundation/utility/string.h" // Standard headers. #include <vector> using namespace boost; using namespace foundation; using namespace std; namespace renderer { namespace { typedef vector<ISampleGenerator*> SampleGeneratorVector; typedef vector<ITileCallback*> TileCallbackVector; // // Progressive frame renderer. // class ProgressiveFrameRenderer : public FrameRendererBase { public: ProgressiveFrameRenderer( const Project& project, ISampleGeneratorFactory* generator_factory, ITileCallbackFactory* callback_factory, const ParamArray& params) : m_frame(*project.get_frame()) , m_params(params) , m_sample_counter(m_params.m_max_sample_count) , m_ref_image_avg_lum(0.0) { // We must have a generator factory, but it's OK not to have a callback factory. assert(generator_factory); // Create an accumulation framebuffer. const CanvasProperties& props = m_frame.image().properties(); m_framebuffer.reset( generator_factory->create_accumulation_framebuffer( props.m_canvas_width, props.m_canvas_height)); // Create and initialize the job manager. m_job_manager.reset( new JobManager( global_logger(), m_job_queue, m_params.m_thread_count, true)); // keep threads alive, even if there's no more jobs // Instantiate sample generators, one per rendering thread. for (size_t i = 0; i < m_params.m_thread_count; ++i) { m_sample_generators.push_back( generator_factory->create(i, m_params.m_thread_count)); } // Instantiate tile callbacks, one per rendering thread. if (callback_factory) { for (size_t i = 0; i < m_params.m_thread_count; ++i) m_tile_callbacks.push_back(callback_factory->create()); } // Load the reference image if one is specified. if (!m_params.m_ref_image_path.empty()) { const string ref_image_path = project.get_search_paths().qualify(m_params.m_ref_image_path); RENDERER_LOG_DEBUG("loading reference image %s...", ref_image_path.c_str()); GenericImageFileReader reader; m_ref_image.reset(reader.read(ref_image_path.c_str())); m_ref_image_avg_lum = compute_average_luminance(*m_ref_image.get()); RENDERER_LOG_DEBUG( "reference image average luminance %s", pretty_scalar(m_ref_image_avg_lum, 6).c_str()); } print_rendering_thread_count(m_params.m_thread_count); } virtual ~ProgressiveFrameRenderer() { // Delete tile callbacks. for (const_each<TileCallbackVector> i = m_tile_callbacks; i; ++i) (*i)->release(); // Delete sample generators. for (const_each<SampleGeneratorVector> i = m_sample_generators; i; ++i) (*i)->release(); } virtual void release() { delete this; } virtual void render() { start_rendering(); m_job_queue.wait_until_completion(); } virtual void start_rendering() { assert(!is_rendering()); assert(!m_job_queue.has_scheduled_or_running_jobs()); m_abort_switch.clear(); m_framebuffer->clear(); m_sample_counter.clear(); // Reset sample generators. for (size_t i = 0; i < m_params.m_thread_count; ++i) m_sample_generators[i]->reset(); // Schedule the first batch of jobs. for (size_t i = 0; i < m_params.m_thread_count; ++i) { m_job_queue.schedule( new SampleGeneratorJob( m_frame, *m_framebuffer.get(), m_sample_generators[i], m_sample_counter, m_tile_callbacks[i], m_job_queue, i, // job index m_params.m_thread_count, // job count 0, // pass number m_abort_switch)); } // Start job execution. m_job_manager->start(); // Create and start the statistics printing thread. m_statistics_func.reset( new StatisticsFunc( m_frame, *m_framebuffer.get(), m_params.m_print_luminance_stats, m_ref_image.get(), m_ref_image_avg_lum, m_abort_switch)); ThreadFunctionWrapper<StatisticsFunc> wrapper(m_statistics_func.get()); m_statistics_thread.reset(new thread(wrapper)); } virtual void stop_rendering() { // Tell rendering jobs and the statistics printing thread to stop. m_abort_switch.abort(); // Stop job execution. m_job_manager->stop(); // Delete all non-executed jobs. m_job_queue.clear_scheduled_jobs(); // Wait until the statistics printing thread is terminated. m_statistics_thread->join(); } virtual void terminate_rendering() { stop_rendering(); m_statistics_func->write_rms_deviation_file(); } virtual bool is_rendering() const { return m_job_queue.has_scheduled_or_running_jobs(); } private: struct Parameters { const size_t m_thread_count; // number of rendering threads const uint64 m_max_sample_count; // maximum total number of samples to store in the framebuffer const bool m_print_luminance_stats; // compute and print luminance statistics? const string m_ref_image_path; // path to the reference image // Constructor, extract parameters. explicit Parameters(const ParamArray& params) : m_thread_count(FrameRendererBase::get_rendering_thread_count(params)) , m_max_sample_count(params.get_optional<uint64>("max_samples", numeric_limits<uint64>::max())) , m_print_luminance_stats(params.get_optional<bool>("print_luminance_statistics", false)) , m_ref_image_path(params.get_optional<string>("reference_image", "")) { } }; Frame& m_frame; const Parameters m_params; SampleCounter m_sample_counter; auto_ptr<AccumulationFramebuffer> m_framebuffer; JobQueue m_job_queue; auto_ptr<JobManager> m_job_manager; AbortSwitch m_abort_switch; SampleGeneratorVector m_sample_generators; TileCallbackVector m_tile_callbacks; auto_ptr<Image> m_ref_image; double m_ref_image_avg_lum; class StatisticsFunc : public NonCopyable { public: StatisticsFunc( Frame& frame, AccumulationFramebuffer& framebuffer, const bool print_luminance_stats, const Image* ref_image, const double ref_image_avg_lum, AbortSwitch& abort_switch) : m_frame(frame) , m_framebuffer(framebuffer) , m_print_luminance_stats(print_luminance_stats) , m_ref_image(ref_image) , m_ref_image_avg_lum(ref_image_avg_lum) , m_abort_switch(abort_switch) , m_timer_frequency(m_timer.frequency()) , m_last_time(m_timer.read()) , m_last_sample_count(0) { } void operator()() { while (!m_abort_switch.is_aborted()) { const uint64 time = m_timer.read(); const uint64 elapsed_ticks = time - m_last_time; const double elapsed_seconds = static_cast<double>(elapsed_ticks) / m_timer_frequency; if (elapsed_seconds >= 1.0) { print_and_record_statistics(elapsed_seconds); m_last_time = time; } foundation::sleep(5); // needs full qualification } } void write_rms_deviation_file() const { if (!m_spp_count_history.empty()) { MapleFile file("RMS Deviation.mpl"); file.define("rmsd", m_spp_count_history, m_rmsd_history); file.plot("rmsd", "RMS Deviation"); } } private: Frame& m_frame; AccumulationFramebuffer& m_framebuffer; const bool m_print_luminance_stats; const Image* m_ref_image; const double m_ref_image_avg_lum; AbortSwitch& m_abort_switch; DefaultWallclockTimer m_timer; uint64 m_timer_frequency; uint64 m_last_time; uint64 m_last_sample_count; FixedSizeHistory<double, 16> m_sps_count_history; // samples per second history vector<double> m_spp_count_history; // samples per pixel history vector<double> m_rmsd_history; // RMS deviation history void print_and_record_statistics(const double elapsed_seconds) { print_performance_statistics(elapsed_seconds); if (m_print_luminance_stats || m_ref_image) print_and_record_convergence_statistics(); } void print_performance_statistics(const double elapsed_seconds) { const uint64 new_sample_count = m_framebuffer.get_sample_count(); const uint64 pixel_count = static_cast<uint64>(m_frame.image().properties().m_pixel_count); const double spp_count = static_cast<double>(new_sample_count) / pixel_count; const double sps_count = static_cast<double>(new_sample_count - m_last_sample_count) / elapsed_seconds; m_sps_count_history.insert(sps_count); RENDERER_LOG_INFO( "%s samples, %s samples/pixel, %s samples/second", pretty_uint(new_sample_count).c_str(), pretty_scalar(spp_count).c_str(), pretty_scalar(m_sps_count_history.compute_average()).c_str()); m_last_sample_count = new_sample_count; } void print_and_record_convergence_statistics() { assert(m_print_luminance_stats || m_ref_image); string output; Image current_image(m_frame.image()); m_frame.transform_to_output_color_space(current_image); if (m_print_luminance_stats) { const double avg_lum = compute_average_luminance(current_image); output += "average luminance " + pretty_scalar(avg_lum, 6); if (m_ref_image) { const double avg_lum_delta = abs(m_ref_image_avg_lum - avg_lum); output += " ("; output += pretty_percent(avg_lum_delta, m_ref_image_avg_lum, 3); output += " error)"; } } if (m_ref_image) { if (m_print_luminance_stats) output += ", "; const double spp_count = static_cast<double>(m_framebuffer.get_sample_count()) / m_frame.image().properties().m_pixel_count; const double rmsd = compute_rms_deviation(current_image, *m_ref_image); output += "rms deviation " + pretty_scalar(rmsd, 6); m_spp_count_history.push_back(spp_count); m_rmsd_history.push_back(rmsd); } RENDERER_LOG_DEBUG("%s", output.c_str()); } }; auto_ptr<StatisticsFunc> m_statistics_func; auto_ptr<thread> m_statistics_thread; }; } // // ProgressiveFrameRendererFactory class implementation. // ProgressiveFrameRendererFactory::ProgressiveFrameRendererFactory( const Project& project, ISampleGeneratorFactory* generator_factory, ITileCallbackFactory* callback_factory, const ParamArray& params) : m_project(project) , m_generator_factory(generator_factory) , m_callback_factory(callback_factory) , m_params(params) { } void ProgressiveFrameRendererFactory::release() { delete this; } IFrameRenderer* ProgressiveFrameRendererFactory::create() { return new ProgressiveFrameRenderer( m_project, m_generator_factory, m_callback_factory, m_params); } IFrameRenderer* ProgressiveFrameRendererFactory::create( const Project& project, ISampleGeneratorFactory* generator_factory, ITileCallbackFactory* callback_factory, const ParamArray& params) { return new ProgressiveFrameRenderer( project, generator_factory, callback_factory, params); } } // namespace renderer <commit_msg>the average number of samples/second is now displayed as an integer with digit grouping.<commit_after> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2011 Francois Beaune // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "progressiveframerenderer.h" // appleseed.renderer headers. #include "renderer/kernel/rendering/progressive/samplecounter.h" #include "renderer/kernel/rendering/progressive/samplegeneratorjob.h" #include "renderer/kernel/rendering/accumulationframebuffer.h" #include "renderer/kernel/rendering/framerendererbase.h" #include "renderer/kernel/rendering/isamplegenerator.h" #include "renderer/kernel/rendering/itilecallback.h" #include "renderer/modeling/frame/frame.h" #include "renderer/modeling/project/project.h" // appleseed.foundation headers. #include "foundation/image/analysis.h" #include "foundation/image/canvasproperties.h" #include "foundation/image/genericimagefilereader.h" #include "foundation/image/image.h" #include "foundation/math/fixedsizehistory.h" #include "foundation/platform/thread.h" #include "foundation/platform/timer.h" #include "foundation/utility/foreach.h" #include "foundation/utility/job.h" #include "foundation/utility/maplefile.h" #include "foundation/utility/searchpaths.h" #include "foundation/utility/string.h" // Standard headers. #include <vector> using namespace boost; using namespace foundation; using namespace std; namespace renderer { namespace { typedef vector<ISampleGenerator*> SampleGeneratorVector; typedef vector<ITileCallback*> TileCallbackVector; // // Progressive frame renderer. // class ProgressiveFrameRenderer : public FrameRendererBase { public: ProgressiveFrameRenderer( const Project& project, ISampleGeneratorFactory* generator_factory, ITileCallbackFactory* callback_factory, const ParamArray& params) : m_frame(*project.get_frame()) , m_params(params) , m_sample_counter(m_params.m_max_sample_count) , m_ref_image_avg_lum(0.0) { // We must have a generator factory, but it's OK not to have a callback factory. assert(generator_factory); // Create an accumulation framebuffer. const CanvasProperties& props = m_frame.image().properties(); m_framebuffer.reset( generator_factory->create_accumulation_framebuffer( props.m_canvas_width, props.m_canvas_height)); // Create and initialize the job manager. m_job_manager.reset( new JobManager( global_logger(), m_job_queue, m_params.m_thread_count, true)); // keep threads alive, even if there's no more jobs // Instantiate sample generators, one per rendering thread. for (size_t i = 0; i < m_params.m_thread_count; ++i) { m_sample_generators.push_back( generator_factory->create(i, m_params.m_thread_count)); } // Instantiate tile callbacks, one per rendering thread. if (callback_factory) { for (size_t i = 0; i < m_params.m_thread_count; ++i) m_tile_callbacks.push_back(callback_factory->create()); } // Load the reference image if one is specified. if (!m_params.m_ref_image_path.empty()) { const string ref_image_path = project.get_search_paths().qualify(m_params.m_ref_image_path); RENDERER_LOG_DEBUG("loading reference image %s...", ref_image_path.c_str()); GenericImageFileReader reader; m_ref_image.reset(reader.read(ref_image_path.c_str())); m_ref_image_avg_lum = compute_average_luminance(*m_ref_image.get()); RENDERER_LOG_DEBUG( "reference image average luminance %s", pretty_scalar(m_ref_image_avg_lum, 6).c_str()); } print_rendering_thread_count(m_params.m_thread_count); } virtual ~ProgressiveFrameRenderer() { // Delete tile callbacks. for (const_each<TileCallbackVector> i = m_tile_callbacks; i; ++i) (*i)->release(); // Delete sample generators. for (const_each<SampleGeneratorVector> i = m_sample_generators; i; ++i) (*i)->release(); } virtual void release() { delete this; } virtual void render() { start_rendering(); m_job_queue.wait_until_completion(); } virtual void start_rendering() { assert(!is_rendering()); assert(!m_job_queue.has_scheduled_or_running_jobs()); m_abort_switch.clear(); m_framebuffer->clear(); m_sample_counter.clear(); // Reset sample generators. for (size_t i = 0; i < m_params.m_thread_count; ++i) m_sample_generators[i]->reset(); // Schedule the first batch of jobs. for (size_t i = 0; i < m_params.m_thread_count; ++i) { m_job_queue.schedule( new SampleGeneratorJob( m_frame, *m_framebuffer.get(), m_sample_generators[i], m_sample_counter, m_tile_callbacks[i], m_job_queue, i, // job index m_params.m_thread_count, // job count 0, // pass number m_abort_switch)); } // Start job execution. m_job_manager->start(); // Create and start the statistics printing thread. m_statistics_func.reset( new StatisticsFunc( m_frame, *m_framebuffer.get(), m_params.m_print_luminance_stats, m_ref_image.get(), m_ref_image_avg_lum, m_abort_switch)); ThreadFunctionWrapper<StatisticsFunc> wrapper(m_statistics_func.get()); m_statistics_thread.reset(new thread(wrapper)); } virtual void stop_rendering() { // Tell rendering jobs and the statistics printing thread to stop. m_abort_switch.abort(); // Stop job execution. m_job_manager->stop(); // Delete all non-executed jobs. m_job_queue.clear_scheduled_jobs(); // Wait until the statistics printing thread is terminated. m_statistics_thread->join(); } virtual void terminate_rendering() { stop_rendering(); m_statistics_func->write_rms_deviation_file(); } virtual bool is_rendering() const { return m_job_queue.has_scheduled_or_running_jobs(); } private: struct Parameters { const size_t m_thread_count; // number of rendering threads const uint64 m_max_sample_count; // maximum total number of samples to store in the framebuffer const bool m_print_luminance_stats; // compute and print luminance statistics? const string m_ref_image_path; // path to the reference image // Constructor, extract parameters. explicit Parameters(const ParamArray& params) : m_thread_count(FrameRendererBase::get_rendering_thread_count(params)) , m_max_sample_count(params.get_optional<uint64>("max_samples", numeric_limits<uint64>::max())) , m_print_luminance_stats(params.get_optional<bool>("print_luminance_statistics", false)) , m_ref_image_path(params.get_optional<string>("reference_image", "")) { } }; Frame& m_frame; const Parameters m_params; SampleCounter m_sample_counter; auto_ptr<AccumulationFramebuffer> m_framebuffer; JobQueue m_job_queue; auto_ptr<JobManager> m_job_manager; AbortSwitch m_abort_switch; SampleGeneratorVector m_sample_generators; TileCallbackVector m_tile_callbacks; auto_ptr<Image> m_ref_image; double m_ref_image_avg_lum; class StatisticsFunc : public NonCopyable { public: StatisticsFunc( Frame& frame, AccumulationFramebuffer& framebuffer, const bool print_luminance_stats, const Image* ref_image, const double ref_image_avg_lum, AbortSwitch& abort_switch) : m_frame(frame) , m_framebuffer(framebuffer) , m_print_luminance_stats(print_luminance_stats) , m_ref_image(ref_image) , m_ref_image_avg_lum(ref_image_avg_lum) , m_abort_switch(abort_switch) , m_timer_frequency(m_timer.frequency()) , m_last_time(m_timer.read()) , m_last_sample_count(0) { } void operator()() { while (!m_abort_switch.is_aborted()) { const uint64 time = m_timer.read(); const uint64 elapsed_ticks = time - m_last_time; const double elapsed_seconds = static_cast<double>(elapsed_ticks) / m_timer_frequency; if (elapsed_seconds >= 1.0) { print_and_record_statistics(elapsed_seconds); m_last_time = time; } foundation::sleep(5); // needs full qualification } } void write_rms_deviation_file() const { if (!m_spp_count_history.empty()) { MapleFile file("RMS Deviation.mpl"); file.define("rmsd", m_spp_count_history, m_rmsd_history); file.plot("rmsd", "RMS Deviation"); } } private: Frame& m_frame; AccumulationFramebuffer& m_framebuffer; const bool m_print_luminance_stats; const Image* m_ref_image; const double m_ref_image_avg_lum; AbortSwitch& m_abort_switch; DefaultWallclockTimer m_timer; uint64 m_timer_frequency; uint64 m_last_time; uint64 m_last_sample_count; FixedSizeHistory<double, 16> m_sps_count_history; // samples per second history vector<double> m_spp_count_history; // samples per pixel history vector<double> m_rmsd_history; // RMS deviation history void print_and_record_statistics(const double elapsed_seconds) { print_performance_statistics(elapsed_seconds); if (m_print_luminance_stats || m_ref_image) print_and_record_convergence_statistics(); } void print_performance_statistics(const double elapsed_seconds) { const uint64 new_sample_count = m_framebuffer.get_sample_count(); const uint64 pixel_count = static_cast<uint64>(m_frame.image().properties().m_pixel_count); const double spp_count = static_cast<double>(new_sample_count) / pixel_count; const double sps_count = static_cast<double>(new_sample_count - m_last_sample_count) / elapsed_seconds; m_sps_count_history.insert(sps_count); const uint64 avg_sps_count = truncate<uint64>(m_sps_count_history.compute_average()); RENDERER_LOG_INFO( "%s samples, %s samples/pixel, %s samples/second", pretty_uint(new_sample_count).c_str(), pretty_scalar(spp_count).c_str(), pretty_uint(avg_sps_count).c_str()); m_last_sample_count = new_sample_count; } void print_and_record_convergence_statistics() { assert(m_print_luminance_stats || m_ref_image); string output; Image current_image(m_frame.image()); m_frame.transform_to_output_color_space(current_image); if (m_print_luminance_stats) { const double avg_lum = compute_average_luminance(current_image); output += "average luminance " + pretty_scalar(avg_lum, 6); if (m_ref_image) { const double avg_lum_delta = abs(m_ref_image_avg_lum - avg_lum); output += " ("; output += pretty_percent(avg_lum_delta, m_ref_image_avg_lum, 3); output += " error)"; } } if (m_ref_image) { if (m_print_luminance_stats) output += ", "; const double spp_count = static_cast<double>(m_framebuffer.get_sample_count()) / m_frame.image().properties().m_pixel_count; const double rmsd = compute_rms_deviation(current_image, *m_ref_image); output += "rms deviation " + pretty_scalar(rmsd, 6); m_spp_count_history.push_back(spp_count); m_rmsd_history.push_back(rmsd); } RENDERER_LOG_DEBUG("%s", output.c_str()); } }; auto_ptr<StatisticsFunc> m_statistics_func; auto_ptr<thread> m_statistics_thread; }; } // // ProgressiveFrameRendererFactory class implementation. // ProgressiveFrameRendererFactory::ProgressiveFrameRendererFactory( const Project& project, ISampleGeneratorFactory* generator_factory, ITileCallbackFactory* callback_factory, const ParamArray& params) : m_project(project) , m_generator_factory(generator_factory) , m_callback_factory(callback_factory) , m_params(params) { } void ProgressiveFrameRendererFactory::release() { delete this; } IFrameRenderer* ProgressiveFrameRendererFactory::create() { return new ProgressiveFrameRenderer( m_project, m_generator_factory, m_callback_factory, m_params); } IFrameRenderer* ProgressiveFrameRendererFactory::create( const Project& project, ISampleGeneratorFactory* generator_factory, ITileCallbackFactory* callback_factory, const ParamArray& params) { return new ProgressiveFrameRenderer( project, generator_factory, callback_factory, params); } } // namespace renderer <|endoftext|>
<commit_before>#include <iostream> #include "opencv2/opencv_modules.hpp" #if defined(HAVE_OPENCV_CUDACODEC) && defined(WIN32) #include <vector> #include <numeric> #include "opencv2/core.hpp" #include "opencv2/cudacodec.hpp" #include "opencv2/highgui.hpp" #include "opencv2/contrib.hpp" int main(int argc, const char* argv[]) { if (argc != 2) { std::cerr << "Usage : video_writer <input video file>" << std::endl; return -1; } const double FPS = 25.0; cv::VideoCapture reader(argv[1]); if (!reader.isOpened()) { std::cerr << "Can't open input video file" << std::endl; return -1; } cv::gpu::printShortCudaDeviceInfo(cv::gpu::getDevice()); cv::VideoWriter writer; cv::Ptr<cv::cudacodec::VideoWriter> d_writer; cv::Mat frame; cv::gpu::GpuMat d_frame; std::vector<double> cpu_times; std::vector<double> gpu_times; cv::TickMeter tm; for (int i = 1;; ++i) { std::cout << "Read " << i << " frame" << std::endl; reader >> frame; if (frame.empty()) { std::cout << "Stop" << std::endl; break; } if (!writer.isOpened()) { std::cout << "Frame Size : " << frame.cols << "x" << frame.rows << std::endl; std::cout << "Open CPU Writer" << std::endl; if (!writer.open("output_cpu.avi", cv::VideoWriter::fourcc('X', 'V', 'I', 'D'), FPS, frame.size())) return -1; } if (d_writer.empty()) { std::cout << "Open CUDA Writer" << std::endl; d_writer = cv::cudacodec::createVideoWriter("output_gpu.avi", frame.size(), FPS); } d_frame.upload(frame); std::cout << "Write " << i << " frame" << std::endl; tm.reset(); tm.start(); writer.write(frame); tm.stop(); cpu_times.push_back(tm.getTimeMilli()); tm.reset(); tm.start(); d_writer->write(d_frame); tm.stop(); gpu_times.push_back(tm.getTimeMilli()); } std::cout << std::endl << "Results:" << std::endl; std::sort(cpu_times.begin(), cpu_times.end()); std::sort(gpu_times.begin(), gpu_times.end()); double cpu_avg = std::accumulate(cpu_times.begin(), cpu_times.end(), 0.0) / cpu_times.size(); double gpu_avg = std::accumulate(gpu_times.begin(), gpu_times.end(), 0.0) / gpu_times.size(); std::cout << "CPU [XVID] : Avg : " << cpu_avg << " ms FPS : " << 1000.0 / cpu_avg << std::endl; std::cout << "GPU [H264] : Avg : " << gpu_avg << " ms FPS : " << 1000.0 / gpu_avg << std::endl; return 0; } #else int main() { std::cout << "OpenCV was built without CUDA Video encoding support\n" << std::endl; return 0; } #endif <commit_msg>fixed video_writer sample<commit_after>#include <iostream> #include "opencv2/opencv_modules.hpp" #if defined(HAVE_OPENCV_CUDACODEC) && defined(WIN32) #include <vector> #include <numeric> #include "opencv2/core.hpp" #include "opencv2/cudacodec.hpp" #include "opencv2/highgui.hpp" #include "opencv2/contrib.hpp" int main(int argc, const char* argv[]) { if (argc != 2) { std::cerr << "Usage : video_writer <input video file>" << std::endl; return -1; } const double FPS = 25.0; cv::VideoCapture reader(argv[1]); if (!reader.isOpened()) { std::cerr << "Can't open input video file" << std::endl; return -1; } cv::cuda::printShortCudaDeviceInfo(cv::cuda::getDevice()); cv::VideoWriter writer; cv::Ptr<cv::cudacodec::VideoWriter> d_writer; cv::Mat frame; cv::cuda::GpuMat d_frame; std::vector<double> cpu_times; std::vector<double> gpu_times; cv::TickMeter tm; for (int i = 1;; ++i) { std::cout << "Read " << i << " frame" << std::endl; reader >> frame; if (frame.empty()) { std::cout << "Stop" << std::endl; break; } if (!writer.isOpened()) { std::cout << "Frame Size : " << frame.cols << "x" << frame.rows << std::endl; std::cout << "Open CPU Writer" << std::endl; if (!writer.open("output_cpu.avi", cv::VideoWriter::fourcc('X', 'V', 'I', 'D'), FPS, frame.size())) return -1; } if (d_writer.empty()) { std::cout << "Open CUDA Writer" << std::endl; d_writer = cv::cudacodec::createVideoWriter("output_gpu.avi", frame.size(), FPS); } d_frame.upload(frame); std::cout << "Write " << i << " frame" << std::endl; tm.reset(); tm.start(); writer.write(frame); tm.stop(); cpu_times.push_back(tm.getTimeMilli()); tm.reset(); tm.start(); d_writer->write(d_frame); tm.stop(); gpu_times.push_back(tm.getTimeMilli()); } std::cout << std::endl << "Results:" << std::endl; std::sort(cpu_times.begin(), cpu_times.end()); std::sort(gpu_times.begin(), gpu_times.end()); double cpu_avg = std::accumulate(cpu_times.begin(), cpu_times.end(), 0.0) / cpu_times.size(); double gpu_avg = std::accumulate(gpu_times.begin(), gpu_times.end(), 0.0) / gpu_times.size(); std::cout << "CPU [XVID] : Avg : " << cpu_avg << " ms FPS : " << 1000.0 / cpu_avg << std::endl; std::cout << "GPU [H264] : Avg : " << gpu_avg << " ms FPS : " << 1000.0 / gpu_avg << std::endl; return 0; } #else int main() { std::cout << "OpenCV was built without CUDA Video encoding support\n" << std::endl; return 0; } #endif <|endoftext|>
<commit_before>// @(#)root/rint:$Name: $:$Id: TRint.cxx,v 1.33 2004/05/11 00:19:59 rdm Exp $ // Author: Rene Brun 17/02/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // Rint // // // // Rint is the ROOT Interactive Interface. It allows interactive access // // to the ROOT system via the CINT C/C++ interpreter. // // // ////////////////////////////////////////////////////////////////////////// #include "TROOT.h" #include "TClass.h" #include "TVirtualX.h" #include "Getline.h" #include "TStyle.h" #include "TObjectTable.h" #include "TClassTable.h" #include "TStopwatch.h" #include "TBenchmark.h" #include "TRint.h" #include "TSystem.h" #include "TEnv.h" #include "TSysEvtHandler.h" #include "TError.h" #include "TException.h" #include "TInterpreter.h" #include "TObjArray.h" #include "TObjString.h" #include "TFile.h" #include "TMapFile.h" #include "TTabCom.h" #include "TError.h" #ifdef R__UNIX #include <signal.h> extern "C" { extern int G__get_security_error(); extern int G__genericerror(const char* msg); } #endif static Int_t key_pressed(Int_t key) { gApplication->KeyPressed(key); return 0; } //----- Interrupt signal handler ----------------------------------------------- //______________________________________________________________________________ class TInterruptHandler : public TSignalHandler { public: TInterruptHandler() : TSignalHandler(kSigInterrupt, kFALSE) { } Bool_t Notify(); }; //______________________________________________________________________________ Bool_t TInterruptHandler::Notify() { // TRint interrupt handler. if (fDelay) { fDelay++; return kTRUE; } // make sure we use the sbrk heap (in case of mapped files) gMmallocDesc = 0; if (!G__get_security_error()) G__genericerror("\n *** Break *** keyboard interrupt"); else { Break("TInterruptHandler::Notify", "keyboard interrupt"); if (TROOT::Initialized()) { Getlinem(kInit, "Root > "); gInterpreter->RewindDictionary(); Throw(GetSignal()); } } return kTRUE; } //----- Terminal Input file handler -------------------------------------------- //______________________________________________________________________________ class TTermInputHandler : public TFileHandler { public: TTermInputHandler(Int_t fd) : TFileHandler(fd, 1) { } Bool_t Notify(); Bool_t ReadNotify() { return Notify(); } }; //______________________________________________________________________________ Bool_t TTermInputHandler::Notify() { return gApplication->HandleTermInput(); } ClassImp(TRint) //______________________________________________________________________________ TRint::TRint(const char *appClassName, Int_t *argc, char **argv, void *options, Int_t numOptions, Bool_t noLogo) : TApplication(appClassName, argc, argv, options, numOptions) { // Create an application environment. The TRint environment provides an // interface to the WM manager functionality and eventloop via inheritance // of TApplication and in addition provides interactive access to // the CINT C++ interpreter via the command line. fNcmd = 0; fDefaultPrompt = "root [%d] "; fInterrupt = kFALSE; gBenchmark = new TBenchmark(); if (!noLogo && !NoLogoOpt()) PrintLogo(); // Everybody expects iostream to be available, so load it... ProcessLine("#include <iostream>", kTRUE); ProcessLine("#include <_string>", kTRUE); // for std::string iostream. // Allow the usage of ClassDef and ClassImp in interpreted macros ProcessLine("#include <RtypesCint.h>", kTRUE); // The following lib is also useful to have, make sure they are loaded... gROOT->LoadClass("THtml", "Html"); // Load user functions const char *logon; logon = gEnv->GetValue("Rint.Load", (char*)0); if (logon) { char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission); if (mac) ProcessLine(Form(".L %s",logon),kTRUE); delete [] mac; } // Execute logon macro logon = gEnv->GetValue("Rint.Logon", (char*)0); if (logon && !NoLogOpt()) { char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission); if (mac) ProcessFile(logon); delete [] mac; } gInterpreter->SaveContext(); gInterpreter->SaveGlobalsContext(); // Install interrupt and terminal input handlers TInterruptHandler *ih = new TInterruptHandler(); ih->Add(); SetSignalHandler(ih); // Handle stdin events fInputHandler = new TTermInputHandler(0); fInputHandler->Add(); // Goto into raw terminal input mode char defhist[128]; #ifndef R__VMS sprintf(defhist, "%s/.root_hist", gSystem->Getenv("HOME")); #else sprintf(defhist, "%s.root_hist", gSystem->Getenv("HOME")); #endif logon = gEnv->GetValue("Rint.History", defhist); Gl_histinit((char *)logon); Gl_windowchanged(); // Setup for tab completion gTabCom = new TTabCom; Gl_in_key = &key_pressed; } //______________________________________________________________________________ TRint::~TRint() { } //______________________________________________________________________________ void TRint::Run(Bool_t retrn) { // Main application eventloop. First process files given on the command // line and then go into the main application event loop, unless the -q // command line option was specfied in which case the program terminates. // When retrun is true this method returns even when -q was specified. // // When QuitOpt is true and retrn is false, terminate the application with // an error code equal to either the ProcessLine error (if any) or the // return value of the command casted to a long. Getlinem(kInit, GetPrompt()); Long_t retval = 0; Int_t error = 0; // Process shell command line input files if (InputFiles()) { TIter next(InputFiles()); RETRY { retval = 0; error = 0; Int_t nfile = 0; TObjString *file; while ((file = (TObjString *)next())) { char cmd[256]; if (!fNcmd) printf("\n"); if (file->String().EndsWith(".root")) { const char *rfile = (const char*)file->String(); Printf("Attaching file %s as _file%d...", rfile, nfile); sprintf(cmd, "TFile *_file%d = TFile::Open(\"%s\")", nfile++, rfile); } else { Printf("Processing %s...", (const char*)file->String()); sprintf(cmd, ".x %s", (const char*)file->String()); } Getlinem(kCleanUp, 0); Gl_histadd(cmd); fNcmd++; retval = ProcessLine(cmd, kFALSE, &error); if (error != 0) break; } } ENDTRY; if (QuitOpt()) { if (retrn) return; Terminate(error == 0 ? retval : error); } ClearInputFiles(); Getlinem(kInit, GetPrompt()); } if (QuitOpt()) { printf("\n"); if (retrn) return; Terminate(0); } TApplication::Run(retrn); Getlinem(kCleanUp, 0); } //______________________________________________________________________________ void TRint::PrintLogo() { // Print the ROOT logo on standard output. Int_t iday,imonth,iyear; static const char *months[] = {"January","February","March","April","May", "June","July","August","September","October", "November","December"}; const char *root_version = gROOT->GetVersion(); Int_t idatqq = gROOT->GetVersionDate(); iday = idatqq%100; imonth = (idatqq/100)%100; iyear = (idatqq/10000); char *root_date = Form("%d %s %4d",iday,months[imonth-1],iyear); Printf(" *******************************************"); Printf(" * *"); Printf(" * W E L C O M E to R O O T *"); Printf(" * *"); Printf(" * Version%10s %17s *", root_version, root_date); // Printf(" * Development version *"); Printf(" * *"); Printf(" * You are welcome to visit our Web site *"); Printf(" * http://root.cern.ch *"); Printf(" * *"); Printf(" *******************************************"); if (strstr(gVirtualX->GetName(), "TTF")) { Int_t major, minor, patch; //TTF::Version(major, minor, patch); // avoid dependency on libGraf and hard code, will not change too often major = 2; minor = 1; patch = 3; Printf("\nFreeType Engine v%d.%d.%d used to render TrueType fonts.", major, minor, patch); } #ifdef _REENTRANT else printf("\n"); Printf("Compiled for %s with thread support.", gSystem->GetBuildArch()); #else else printf("\n"); Printf("Compiled for %s.", gSystem->GetBuildArch()); #endif gInterpreter->PrintIntro(); #ifdef R__UNIX // Popdown X logo, only if started with -splash option for (int i = 0; i < Argc(); i++) if (!strcmp(Argv(i), "-splash")) kill(getppid(), SIGUSR1); #endif } //______________________________________________________________________________ char *TRint::GetPrompt() { // Get prompt from interpreter. Either "root [n]" or "end with '}'". char *s = gInterpreter->GetPrompt(); if (s[0]) strcpy(fPrompt, s); else sprintf(fPrompt, fDefaultPrompt.Data(), fNcmd); return fPrompt; } //______________________________________________________________________________ const char *TRint::SetPrompt(const char *newPrompt) { // Set a new default prompt. It returns the previous prompt. // The prompt may contain a %d which will be replaced by the commend // number. The default prompt is "root [%d] ". The maximum length of // the prompt is 55 characters. To set the prompt in an interactive // session do: // root [0] ((TRint*)gROOT->GetApplication())->SetPrompt("aap> ") // aap> static TString op = fDefaultPrompt; if (newPrompt && strlen(newPrompt) <= 55) fDefaultPrompt = newPrompt; else Error("SetPrompt", "newPrompt too long (> 55 characters)"); return op.Data(); } //______________________________________________________________________________ Bool_t TRint::HandleTermInput() { // Handle input coming from terminal. static TStopwatch timer; char *line; if ((line = Getlinem(kOneChar, 0))) { if (line[0] == 0 && Gl_eof()) Terminate(0); gVirtualX->SetKeyAutoRepeat(kTRUE); Gl_histadd(line); TString sline = line; line[0] = 0; // strip off '\n' and leading and trailing blanks sline = sline.Chop(); sline = sline.Strip(TString::kBoth); ReturnPressed((char*)sline.Data()); fInterrupt = kFALSE; if (!gInterpreter->GetMore() && !sline.IsNull()) fNcmd++; // prevent recursive calling of this input handler fInputHandler->DeActivate(); if (gROOT->Timer()) timer.Start(); Bool_t added = kFALSE; #ifdef R__EH try { #endif TRY { ProcessLine(sline); } CATCH(excode) { // enable again input handler fInputHandler->Activate(); added = kTRUE; Throw(excode); } ENDTRY; #ifdef R__EH } // handle every exception catch (...) { // enable again intput handler if (!added) fInputHandler->Activate(); throw; } #endif if (gROOT->Timer()) timer.Print(); // enable again intput handler fInputHandler->Activate(); if (!sline.BeginsWith(".reset")) gInterpreter->EndOfLineAction(); gTabCom->ClearAll(); Getlinem(kInit, GetPrompt()); } return kTRUE; } //______________________________________________________________________________ void TRint::Terminate(Int_t status) { // Terminate the application. Reset the terminal to sane mode and call // the logoff macro defined via Rint.Logoff environment variable. Getlinem(kCleanUp, 0); if (ReturnFromRun()) { gSystem->ExitLoop(); } else { //Execute logoff macro const char *logoff; logoff = gEnv->GetValue("Rint.Logoff", (char*)0); if (logoff && !NoLogOpt()) { char *mac = gSystem->Which(TROOT::GetMacroPath(), logoff, kReadPermission); if (mac) ProcessFile(logoff); delete [] mac; } gSystem->Exit(status); } } //______________________________________________________________________________ void TRint::SetEchoMode(Bool_t mode) { // Set console mode: // // mode = kTRUE - echo input symbols // mode = kFALSE - noecho input symbols Gl_config("noecho", mode ? 0 : 1); } <commit_msg>From Philippe: This patch insures that if an exception or segmentation fault is raised during the 'processing' of the command line argument then the terminal is properly reset.<commit_after>// @(#)root/rint:$Name: $:$Id: TRint.cxx,v 1.34 2004/05/17 12:03:59 rdm Exp $ // Author: Rene Brun 17/02/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // Rint // // // // Rint is the ROOT Interactive Interface. It allows interactive access // // to the ROOT system via the CINT C/C++ interpreter. // // // ////////////////////////////////////////////////////////////////////////// #include "TROOT.h" #include "TClass.h" #include "TVirtualX.h" #include "Getline.h" #include "TStyle.h" #include "TObjectTable.h" #include "TClassTable.h" #include "TStopwatch.h" #include "TBenchmark.h" #include "TRint.h" #include "TSystem.h" #include "TEnv.h" #include "TSysEvtHandler.h" #include "TError.h" #include "TException.h" #include "TInterpreter.h" #include "TObjArray.h" #include "TObjString.h" #include "TFile.h" #include "TMapFile.h" #include "TTabCom.h" #include "TError.h" #ifdef R__UNIX #include <signal.h> extern "C" { extern int G__get_security_error(); extern int G__genericerror(const char* msg); } #endif static Int_t key_pressed(Int_t key) { gApplication->KeyPressed(key); return 0; } //----- Interrupt signal handler ----------------------------------------------- //______________________________________________________________________________ class TInterruptHandler : public TSignalHandler { public: TInterruptHandler() : TSignalHandler(kSigInterrupt, kFALSE) { } Bool_t Notify(); }; //______________________________________________________________________________ Bool_t TInterruptHandler::Notify() { // TRint interrupt handler. if (fDelay) { fDelay++; return kTRUE; } // make sure we use the sbrk heap (in case of mapped files) gMmallocDesc = 0; if (!G__get_security_error()) G__genericerror("\n *** Break *** keyboard interrupt"); else { Break("TInterruptHandler::Notify", "keyboard interrupt"); if (TROOT::Initialized()) { Getlinem(kInit, "Root > "); gInterpreter->RewindDictionary(); Throw(GetSignal()); } } return kTRUE; } //----- Terminal Input file handler -------------------------------------------- //______________________________________________________________________________ class TTermInputHandler : public TFileHandler { public: TTermInputHandler(Int_t fd) : TFileHandler(fd, 1) { } Bool_t Notify(); Bool_t ReadNotify() { return Notify(); } }; //______________________________________________________________________________ Bool_t TTermInputHandler::Notify() { return gApplication->HandleTermInput(); } ClassImp(TRint) //______________________________________________________________________________ TRint::TRint(const char *appClassName, Int_t *argc, char **argv, void *options, Int_t numOptions, Bool_t noLogo) : TApplication(appClassName, argc, argv, options, numOptions) { // Create an application environment. The TRint environment provides an // interface to the WM manager functionality and eventloop via inheritance // of TApplication and in addition provides interactive access to // the CINT C++ interpreter via the command line. fNcmd = 0; fDefaultPrompt = "root [%d] "; fInterrupt = kFALSE; gBenchmark = new TBenchmark(); if (!noLogo && !NoLogoOpt()) PrintLogo(); // Everybody expects iostream to be available, so load it... ProcessLine("#include <iostream>", kTRUE); ProcessLine("#include <_string>", kTRUE); // for std::string iostream. // Allow the usage of ClassDef and ClassImp in interpreted macros ProcessLine("#include <RtypesCint.h>", kTRUE); // The following lib is also useful to have, make sure they are loaded... gROOT->LoadClass("THtml", "Html"); // Load user functions const char *logon; logon = gEnv->GetValue("Rint.Load", (char*)0); if (logon) { char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission); if (mac) ProcessLine(Form(".L %s",logon),kTRUE); delete [] mac; } // Execute logon macro logon = gEnv->GetValue("Rint.Logon", (char*)0); if (logon && !NoLogOpt()) { char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission); if (mac) ProcessFile(logon); delete [] mac; } gInterpreter->SaveContext(); gInterpreter->SaveGlobalsContext(); // Install interrupt and terminal input handlers TInterruptHandler *ih = new TInterruptHandler(); ih->Add(); SetSignalHandler(ih); // Handle stdin events fInputHandler = new TTermInputHandler(0); fInputHandler->Add(); // Goto into raw terminal input mode char defhist[128]; #ifndef R__VMS sprintf(defhist, "%s/.root_hist", gSystem->Getenv("HOME")); #else sprintf(defhist, "%s.root_hist", gSystem->Getenv("HOME")); #endif logon = gEnv->GetValue("Rint.History", defhist); Gl_histinit((char *)logon); Gl_windowchanged(); // Setup for tab completion gTabCom = new TTabCom; Gl_in_key = &key_pressed; } //______________________________________________________________________________ TRint::~TRint() { } //______________________________________________________________________________ void TRint::Run(Bool_t retrn) { // Main application eventloop. First process files given on the command // line and then go into the main application event loop, unless the -q // command line option was specfied in which case the program terminates. // When retrun is true this method returns even when -q was specified. // // When QuitOpt is true and retrn is false, terminate the application with // an error code equal to either the ProcessLine error (if any) or the // return value of the command casted to a long. Getlinem(kInit, GetPrompt()); Long_t retval = 0; Int_t error = 0; // Process shell command line input files if (InputFiles()) { Bool_t needGetlinemInit = kFALSE; TIter next(InputFiles()); RETRY { retval = 0; error = 0; Int_t nfile = 0; TObjString *file; while ((file = (TObjString *)next())) { char cmd[256]; if (!fNcmd) printf("\n"); if (file->String().EndsWith(".root")) { const char *rfile = (const char*)file->String(); Printf("Attaching file %s as _file%d...", rfile, nfile); sprintf(cmd, "TFile *_file%d = TFile::Open(\"%s\")", nfile++, rfile); } else { Printf("Processing %s...", (const char*)file->String()); sprintf(cmd, ".x %s", (const char*)file->String()); } Getlinem(kCleanUp, 0); Gl_histadd(cmd); fNcmd++; // The ProcessLine might throw an 'exception'. In this case, // GetLinem(kInit,"Root >") is called and we are jump back // to RETRY ... and we have to avoid the Getlinem(kInit, GetPrompt()); needGetlinemInit = kFALSE; retval = ProcessLine(cmd, kFALSE, &error); // The ProcessLine has successfully completed and we need // to call Getlinem(kInit, GetPrompt()); needGetlinemInit = kTRUE; if (error != 0) break; } } ENDTRY; if (QuitOpt()) { if (retrn) return; Terminate(error == 0 ? retval : error); } ClearInputFiles(); if (needGetlinemInit) Getlinem(kInit, GetPrompt()); } if (QuitOpt()) { printf("\n"); if (retrn) return; Terminate(0); } TApplication::Run(retrn); Getlinem(kCleanUp, 0); } //______________________________________________________________________________ void TRint::PrintLogo() { // Print the ROOT logo on standard output. Int_t iday,imonth,iyear; static const char *months[] = {"January","February","March","April","May", "June","July","August","September","October", "November","December"}; const char *root_version = gROOT->GetVersion(); Int_t idatqq = gROOT->GetVersionDate(); iday = idatqq%100; imonth = (idatqq/100)%100; iyear = (idatqq/10000); char *root_date = Form("%d %s %4d",iday,months[imonth-1],iyear); Printf(" *******************************************"); Printf(" * *"); Printf(" * W E L C O M E to R O O T *"); Printf(" * *"); Printf(" * Version%10s %17s *", root_version, root_date); // Printf(" * Development version *"); Printf(" * *"); Printf(" * You are welcome to visit our Web site *"); Printf(" * http://root.cern.ch *"); Printf(" * *"); Printf(" *******************************************"); if (strstr(gVirtualX->GetName(), "TTF")) { Int_t major, minor, patch; //TTF::Version(major, minor, patch); // avoid dependency on libGraf and hard code, will not change too often major = 2; minor = 1; patch = 3; Printf("\nFreeType Engine v%d.%d.%d used to render TrueType fonts.", major, minor, patch); } #ifdef _REENTRANT else printf("\n"); Printf("Compiled for %s with thread support.", gSystem->GetBuildArch()); #else else printf("\n"); Printf("Compiled for %s.", gSystem->GetBuildArch()); #endif gInterpreter->PrintIntro(); #ifdef R__UNIX // Popdown X logo, only if started with -splash option for (int i = 0; i < Argc(); i++) if (!strcmp(Argv(i), "-splash")) kill(getppid(), SIGUSR1); #endif } //______________________________________________________________________________ char *TRint::GetPrompt() { // Get prompt from interpreter. Either "root [n]" or "end with '}'". char *s = gInterpreter->GetPrompt(); if (s[0]) strcpy(fPrompt, s); else sprintf(fPrompt, fDefaultPrompt.Data(), fNcmd); return fPrompt; } //______________________________________________________________________________ const char *TRint::SetPrompt(const char *newPrompt) { // Set a new default prompt. It returns the previous prompt. // The prompt may contain a %d which will be replaced by the commend // number. The default prompt is "root [%d] ". The maximum length of // the prompt is 55 characters. To set the prompt in an interactive // session do: // root [0] ((TRint*)gROOT->GetApplication())->SetPrompt("aap> ") // aap> static TString op = fDefaultPrompt; if (newPrompt && strlen(newPrompt) <= 55) fDefaultPrompt = newPrompt; else Error("SetPrompt", "newPrompt too long (> 55 characters)"); return op.Data(); } //______________________________________________________________________________ Bool_t TRint::HandleTermInput() { // Handle input coming from terminal. static TStopwatch timer; char *line; if ((line = Getlinem(kOneChar, 0))) { if (line[0] == 0 && Gl_eof()) Terminate(0); gVirtualX->SetKeyAutoRepeat(kTRUE); Gl_histadd(line); TString sline = line; line[0] = 0; // strip off '\n' and leading and trailing blanks sline = sline.Chop(); sline = sline.Strip(TString::kBoth); ReturnPressed((char*)sline.Data()); fInterrupt = kFALSE; if (!gInterpreter->GetMore() && !sline.IsNull()) fNcmd++; // prevent recursive calling of this input handler fInputHandler->DeActivate(); if (gROOT->Timer()) timer.Start(); Bool_t added = kFALSE; #ifdef R__EH try { #endif TRY { ProcessLine(sline); } CATCH(excode) { // enable again input handler fInputHandler->Activate(); added = kTRUE; Throw(excode); } ENDTRY; #ifdef R__EH } // handle every exception catch (...) { // enable again intput handler if (!added) fInputHandler->Activate(); throw; } #endif if (gROOT->Timer()) timer.Print(); // enable again intput handler fInputHandler->Activate(); if (!sline.BeginsWith(".reset")) gInterpreter->EndOfLineAction(); gTabCom->ClearAll(); Getlinem(kInit, GetPrompt()); } return kTRUE; } //______________________________________________________________________________ void TRint::Terminate(Int_t status) { // Terminate the application. Reset the terminal to sane mode and call // the logoff macro defined via Rint.Logoff environment variable. Getlinem(kCleanUp, 0); if (ReturnFromRun()) { gSystem->ExitLoop(); } else { //Execute logoff macro const char *logoff; logoff = gEnv->GetValue("Rint.Logoff", (char*)0); if (logoff && !NoLogOpt()) { char *mac = gSystem->Which(TROOT::GetMacroPath(), logoff, kReadPermission); if (mac) ProcessFile(logoff); delete [] mac; } gSystem->Exit(status); } } //______________________________________________________________________________ void TRint::SetEchoMode(Bool_t mode) { // Set console mode: // // mode = kTRUE - echo input symbols // mode = kFALSE - noecho input symbols Gl_config("noecho", mode ? 0 : 1); } <|endoftext|>
<commit_before>// $Id$ AliAnalysisTaskSE *AddTaskEMCALTenderUsingDatasetDef( const char *perstr = "LHC11h", const char *pass = 0 /*should not be needed*/ ) { gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEMCALTender.C"); Bool_t distBC = kTRUE; //distance to bad channel Bool_t recalibClus = kTRUE; //recalibrate cluster energy Bool_t recalcClusPos = kTRUE; //recalculate cluster position Bool_t nonLinearCorr = kTRUE; //apply non-linearity Bool_t remExotic = kTRUE; //remove exotic cells Bool_t fidRegion = kFALSE; //apply fiducial cuts Bool_t calibEnergy = kTRUE; //calibrate energy Bool_t calibTime = kTRUE; //calibrate timing Bool_t remBC = kTRUE; //remove bad channels UInt_t nonLinFunct = AliEMCALRecoUtils::kBeamTestCorrected; Bool_t reclusterize = kFALSE; //reclusterize Float_t seedthresh = 0.100; //seed threshold Float_t cellthresh = 0.050; //cell threshold UInt_t clusterizer = AliEMCALRecParam::kClusterizerv2; Bool_t trackMatch = kTRUE; //track matching Bool_t updateCellOnly = kFALSE; //only change if you run your own clusterizer task Float_t timeMin = 100e-9; //minimum time of physical signal in a cell/digit (s) Float_t timeMax = 900e-9; //maximum time of physical signal in a cell/digit (s) Float_t timeCut = 900e-9; //maximum time difference between the digits inside EMC cluster (s) TString period(perstr); period.ToLower(); if (period == "lhc12a15e") nonLinFunct = AliEMCALRecoUtils::kPi0MCv3; else if (period == "lhc12a15a") nonLinFunct = AliEMCALRecoUtils::kPi0MCv2; else if(period == "lhc13b" || period == "lhc13c" || period == "lhc13d" || period == "lhc13e" || period == "lhc13f" || period == "lhc13g" || period == "lhc13b4" || period == "lhc13b4_fix" || period == "lhc13b4_plus") { reclusterize = kTRUE; seedthresh = 0.3; cellthresh = 0.05; else if(period == "lhc13b" || period == "lhc13c" || period == "lhc13d" || period == "lhc13e" || period == "lhc13f" || period == "lhc13g") { timeMin = -50e-9; timeMax = 50e-9; timeCut = 1e6; } } AliAnalysisTaskSE *task = AddTaskEMCALTender( distBC, recalibClus, recalcClusPos, nonLinearCorr, remExotic, fidRegion, calibEnergy, calibTime, remBC, nonLinFunct, reclusterize, seedthresh, cellthresh, clusterizer, trackMatch, updateCellOnly, timeMin, timeMax, timeCut, pass); return task; } <commit_msg>add timing cuts MC pPb<commit_after>// $Id$ AliAnalysisTaskSE *AddTaskEMCALTenderUsingDatasetDef( const char *perstr = "LHC11h", const char *pass = 0 /*should not be needed*/ ) { gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEMCALTender.C"); Bool_t distBC = kTRUE; //distance to bad channel Bool_t recalibClus = kTRUE; //recalibrate cluster energy Bool_t recalcClusPos = kTRUE; //recalculate cluster position Bool_t nonLinearCorr = kTRUE; //apply non-linearity Bool_t remExotic = kTRUE; //remove exotic cells Bool_t fidRegion = kFALSE; //apply fiducial cuts Bool_t calibEnergy = kTRUE; //calibrate energy Bool_t calibTime = kTRUE; //calibrate timing Bool_t remBC = kTRUE; //remove bad channels UInt_t nonLinFunct = AliEMCALRecoUtils::kBeamTestCorrected; Bool_t reclusterize = kFALSE; //reclusterize Float_t seedthresh = 0.100; //seed threshold Float_t cellthresh = 0.050; //cell threshold UInt_t clusterizer = AliEMCALRecParam::kClusterizerv2; Bool_t trackMatch = kTRUE; //track matching Bool_t updateCellOnly = kFALSE; //only change if you run your own clusterizer task Float_t timeMin = 100e-9; //minimum time of physical signal in a cell/digit (s) Float_t timeMax = 900e-9; //maximum time of physical signal in a cell/digit (s) Float_t timeCut = 900e-9; //maximum time difference between the digits inside EMC cluster (s) TString period(perstr); period.ToLower(); if (period == "lhc12a15e") nonLinFunct = AliEMCALRecoUtils::kPi0MCv3; else if (period == "lhc12a15a") nonLinFunct = AliEMCALRecoUtils::kPi0MCv2; else if(period == "lhc13b" || period == "lhc13c" || period == "lhc13d" || period == "lhc13e" || period == "lhc13f" || period == "lhc13g" || period == "lhc13b4" || period == "lhc13b4_fix" || period == "lhc13b4_plus") { reclusterize = kTRUE; seedthresh = 0.3; cellthresh = 0.05; if(period == "lhc13b" || period == "lhc13c" || period == "lhc13d" || period == "lhc13e" || period == "lhc13f" || period == "lhc13g") { timeMin = -50e-9; timeMax = 50e-9; timeCut = 1e6; } else if(period == "lhc13b4" || period == "lhc13b4_fix" || period == "lhc13b4_plus") { timeMin = -1; timeMax = 1e6; timeCut = 1e6; } } AliAnalysisTaskSE *task = AddTaskEMCALTender( distBC, recalibClus, recalcClusPos, nonLinearCorr, remExotic, fidRegion, calibEnergy, calibTime, remBC, nonLinFunct, reclusterize, seedthresh, cellthresh, clusterizer, trackMatch, updateCellOnly, timeMin, timeMax, timeCut, pass); return task; } <|endoftext|>
<commit_before><commit_msg>std::cout to SAL_INFO<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: servobj.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2004-10-04 20:18:13 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_SERVOBJ_HXX #define SC_SERVOBJ_HXX #ifndef _SFXLSTNER_HXX //autogen #include <svtools/lstner.hxx> #endif #ifndef _SVT_LISTENER_HXX #include <svtools/listener.hxx> #endif #ifndef _LINKSRC_HXX //autogen #include <sfx2/linksrc.hxx> #endif #ifndef SC_SCGLOB_HXX #include "global.hxx" #endif #ifndef SC_ADDRESS_HXX #include "address.hxx" #endif class ScDocShell; class ScServerObject; class ScServerObjectSvtListenerForwarder : public SvtListener { ScServerObject* pObj; SfxBroadcaster aBroadcaster; public: ScServerObjectSvtListenerForwarder( ScServerObject* pObjP); virtual ~ScServerObjectSvtListenerForwarder(); virtual void Notify( SvtBroadcaster& rBC, const SfxHint& rHint); }; class ScServerObject : public ::sfx2::SvLinkSource, public SfxListener { private: ScServerObjectSvtListenerForwarder aForwarder; ScDocShell* pDocSh; ScRange aRange; String aItemStr; BOOL bRefreshListener; void Clear(); public: ScServerObject( ScDocShell* pShell, const String& rItem ); virtual ~ScServerObject(); virtual BOOL GetData( ::com::sun::star::uno::Any & rData /*out param*/, const String & rMimeType, BOOL bSynchron = FALSE ); virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType ); void EndListeningAll(); }; //SO2_DECL_REF( ScServerObject ) #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.4.326); FILE MERGED 2005/09/05 15:05:48 rt 1.4.326.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: servobj.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 21:49:48 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SC_SERVOBJ_HXX #define SC_SERVOBJ_HXX #ifndef _SFXLSTNER_HXX //autogen #include <svtools/lstner.hxx> #endif #ifndef _SVT_LISTENER_HXX #include <svtools/listener.hxx> #endif #ifndef _LINKSRC_HXX //autogen #include <sfx2/linksrc.hxx> #endif #ifndef SC_SCGLOB_HXX #include "global.hxx" #endif #ifndef SC_ADDRESS_HXX #include "address.hxx" #endif class ScDocShell; class ScServerObject; class ScServerObjectSvtListenerForwarder : public SvtListener { ScServerObject* pObj; SfxBroadcaster aBroadcaster; public: ScServerObjectSvtListenerForwarder( ScServerObject* pObjP); virtual ~ScServerObjectSvtListenerForwarder(); virtual void Notify( SvtBroadcaster& rBC, const SfxHint& rHint); }; class ScServerObject : public ::sfx2::SvLinkSource, public SfxListener { private: ScServerObjectSvtListenerForwarder aForwarder; ScDocShell* pDocSh; ScRange aRange; String aItemStr; BOOL bRefreshListener; void Clear(); public: ScServerObject( ScDocShell* pShell, const String& rItem ); virtual ~ScServerObject(); virtual BOOL GetData( ::com::sun::star::uno::Any & rData /*out param*/, const String & rMimeType, BOOL bSynchron = FALSE ); virtual void SFX_NOTIFY( SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType ); void EndListeningAll(); }; //SO2_DECL_REF( ScServerObject ) #endif <|endoftext|>
<commit_before>/** * @file FTAddMyTask.C * @author Freja Thoresen <[email protected]> * * @brief Add Q-cummulant forward task to train * * * @ingroup pwglf_forward_scripts_tasks */ /** * @defgroup pwglf_forward_flow Flow * * Code to deal with flow * * @ingroup pwglf_forward_topical */ /** * Add Flow task to train * * @ingroup pwglf_forward_flow */ //#include "AliForwardTaskValidation.h" AliAnalysisTaskSE* AddTaskForwardValidation("name") { std::cout << "AddTaskForwardValidation" << std::endl; return AliForwardTaskValidation::ConnectTask("ftvalid", true); //std::cout << validation_task << std::endl; //return validation_task; } /* * EOF * */ <commit_msg>name in addtask<commit_after>/** * @file FTAddMyTask.C * @author Freja Thoresen <[email protected]> * * @brief Add Q-cummulant forward task to train * * * @ingroup pwglf_forward_scripts_tasks */ /** * @defgroup pwglf_forward_flow Flow * * Code to deal with flow * * @ingroup pwglf_forward_topical */ /** * Add Flow task to train * * @ingroup pwglf_forward_flow */ //#include "AliForwardTaskValidation.h" AliAnalysisTaskSE* AddTaskForwardValidation(name="name") { std::cout << "AddTaskForwardValidation" << std::endl; return AliForwardTaskValidation::ConnectTask("ftvalid", true); //std::cout << validation_task << std::endl; //return validation_task; } /* * EOF * */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: weakref.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-08 09:23:30 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CPPUHELPER_WEAKREF_HXX_ #define _CPPUHELPER_WEAKREF_HXX_ #ifndef _COM_SUN_STAR_UNO_XINTERFACE_HPP_ #include <com/sun/star/uno/XInterface.hpp> #endif namespace com { namespace sun { namespace star { namespace uno { /** @internal */ class OWeakRefListener; /** The WeakReferenceHelper holds a weak reference to an object. This object must implement the ::com::sun::star::uno::XWeak interface. The implementation is thread safe. */ class WeakReferenceHelper { public: /** Default ctor. Creates an empty weak reference. */ inline WeakReferenceHelper() SAL_THROW( () ) : m_pImpl( 0 ) {} /** Copy ctor. Initialize this reference with the same interface as in rWeakRef. @param rWeakRef another weak ref */ WeakReferenceHelper( const WeakReferenceHelper & rWeakRef ) SAL_THROW( () ); /** Initialize this reference with the hard interface reference xInt. If the implementation behind xInt does not support XWeak or XInt is null then this reference will be null. @param xInt another hard interface reference */ WeakReferenceHelper( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > & xInt ) SAL_THROW( () ); /** Releases this reference. */ ~WeakReferenceHelper() SAL_THROW( () ); /** Releases this reference and takes over rWeakRef. @param rWeakRef another weak ref */ WeakReferenceHelper & SAL_CALL operator = ( const WeakReferenceHelper & rWeakRef ) SAL_THROW( () ); /** Releases this reference and takes over hard reference xInt. If the implementation behind xInt does not support XWeak or XInt is null, than this reference is null. @param xInt another hard reference */ inline WeakReferenceHelper & SAL_CALL operator = ( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > & xInt ) SAL_THROW( () ) { return operator = ( WeakReferenceHelper( xInt ) ); } /** Returns true if both weak refs reference to the same object. @param rObj another weak ref @return true, if both weak refs reference to the same object. */ inline sal_Bool SAL_CALL operator == ( const WeakReferenceHelper & rObj ) const SAL_THROW( () ) { return (get() == rObj.get()); } /** Gets a hard reference to the object. @return hard reference or null, if the weakly referenced interface has gone */ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL get() const SAL_THROW( () ); /** Gets a hard reference to the object. @return hard reference or null, if the weakly referenced interface has gone */ inline SAL_CALL operator Reference< XInterface > () const SAL_THROW( () ) { return get(); } protected: /** @internal */ OWeakRefListener * m_pImpl; }; /** The WeakReference<> holds a weak reference to an object. This object must implement the ::com::sun::star::uno::XWeak interface. The implementation is thread safe. @tplparam interface_type type of interface */ template< class interface_type > class WeakReference : public WeakReferenceHelper { public: /** Default ctor. Creates an empty weak reference. */ inline WeakReference() SAL_THROW( () ) : WeakReferenceHelper() {} /** Copy ctor. Initialize this reference with a hard reference. @param rRef another hard ref */ inline WeakReference( const Reference< interface_type > & rRef ) SAL_THROW( () ) : WeakReferenceHelper( rRef ) {} /** Gets a hard reference to the object. @return hard reference or null, if the weakly referenced interface has gone */ inline SAL_CALL operator Reference< interface_type > () const SAL_THROW( () ) { return Reference< interface_type >::query( get() ); } }; } } } } #endif <commit_msg>INTEGRATION: CWS changefileheader (1.6.140); FILE MERGED 2008/04/01 10:54:26 thb 1.6.140.2: #i85898# Stripping all external header guards 2008/03/28 15:25:22 rt 1.6.140.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: weakref.hxx,v $ * $Revision: 1.7 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _CPPUHELPER_WEAKREF_HXX_ #define _CPPUHELPER_WEAKREF_HXX_ #include <com/sun/star/uno/XInterface.hpp> namespace com { namespace sun { namespace star { namespace uno { /** @internal */ class OWeakRefListener; /** The WeakReferenceHelper holds a weak reference to an object. This object must implement the ::com::sun::star::uno::XWeak interface. The implementation is thread safe. */ class WeakReferenceHelper { public: /** Default ctor. Creates an empty weak reference. */ inline WeakReferenceHelper() SAL_THROW( () ) : m_pImpl( 0 ) {} /** Copy ctor. Initialize this reference with the same interface as in rWeakRef. @param rWeakRef another weak ref */ WeakReferenceHelper( const WeakReferenceHelper & rWeakRef ) SAL_THROW( () ); /** Initialize this reference with the hard interface reference xInt. If the implementation behind xInt does not support XWeak or XInt is null then this reference will be null. @param xInt another hard interface reference */ WeakReferenceHelper( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > & xInt ) SAL_THROW( () ); /** Releases this reference. */ ~WeakReferenceHelper() SAL_THROW( () ); /** Releases this reference and takes over rWeakRef. @param rWeakRef another weak ref */ WeakReferenceHelper & SAL_CALL operator = ( const WeakReferenceHelper & rWeakRef ) SAL_THROW( () ); /** Releases this reference and takes over hard reference xInt. If the implementation behind xInt does not support XWeak or XInt is null, than this reference is null. @param xInt another hard reference */ inline WeakReferenceHelper & SAL_CALL operator = ( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > & xInt ) SAL_THROW( () ) { return operator = ( WeakReferenceHelper( xInt ) ); } /** Returns true if both weak refs reference to the same object. @param rObj another weak ref @return true, if both weak refs reference to the same object. */ inline sal_Bool SAL_CALL operator == ( const WeakReferenceHelper & rObj ) const SAL_THROW( () ) { return (get() == rObj.get()); } /** Gets a hard reference to the object. @return hard reference or null, if the weakly referenced interface has gone */ ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL get() const SAL_THROW( () ); /** Gets a hard reference to the object. @return hard reference or null, if the weakly referenced interface has gone */ inline SAL_CALL operator Reference< XInterface > () const SAL_THROW( () ) { return get(); } protected: /** @internal */ OWeakRefListener * m_pImpl; }; /** The WeakReference<> holds a weak reference to an object. This object must implement the ::com::sun::star::uno::XWeak interface. The implementation is thread safe. @tplparam interface_type type of interface */ template< class interface_type > class WeakReference : public WeakReferenceHelper { public: /** Default ctor. Creates an empty weak reference. */ inline WeakReference() SAL_THROW( () ) : WeakReferenceHelper() {} /** Copy ctor. Initialize this reference with a hard reference. @param rRef another hard ref */ inline WeakReference( const Reference< interface_type > & rRef ) SAL_THROW( () ) : WeakReferenceHelper( rRef ) {} /** Gets a hard reference to the object. @return hard reference or null, if the weakly referenced interface has gone */ inline SAL_CALL operator Reference< interface_type > () const SAL_THROW( () ) { return Reference< interface_type >::query( get() ); } }; } } } } #endif <|endoftext|>
<commit_before>#include "testing/testing.hpp" #include "generator/generator_tests_support/test_with_classificator.hpp" #include "generator/osm2meta.hpp" #include "indexer/classificator.hpp" #include "base/logging.hpp" using namespace generator::tests_support; using feature::Metadata; UNIT_TEST(Metadata_ValidateAndFormat_stars) { FeatureBuilderParams params; MetadataTagProcessor p(params); Metadata & md = params.GetMetadata(); // Ignore incorrect values. p("stars", "0"); TEST(md.Empty(), ()); p("stars", "-1"); TEST(md.Empty(), ()); p("stars", "aasdasdas"); TEST(md.Empty(), ()); p("stars", "8"); TEST(md.Empty(), ()); p("stars", "10"); TEST(md.Empty(), ()); p("stars", "910"); TEST(md.Empty(), ()); p("stars", "100"); TEST(md.Empty(), ()); // Check correct values. p("stars", "1"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "1", ()); md.Drop(Metadata::FMD_STARS); p("stars", "2"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "2", ()); md.Drop(Metadata::FMD_STARS); p("stars", "3"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "3", ()); md.Drop(Metadata::FMD_STARS); p("stars", "4"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "4", ()); md.Drop(Metadata::FMD_STARS); p("stars", "5"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "5", ()); md.Drop(Metadata::FMD_STARS); p("stars", "6"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "6", ()); md.Drop(Metadata::FMD_STARS); p("stars", "7"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "7", ()); md.Drop(Metadata::FMD_STARS); // Check almost correct values. p("stars", "4+"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "4", ()); md.Drop(Metadata::FMD_STARS); p("stars", "5s"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "5", ()); md.Drop(Metadata::FMD_STARS); } UNIT_CLASS_TEST(TestWithClassificator, Metadata_ValidateAndFormat_operator) { uint32_t const typeAtm = classif().GetTypeByPath({"amenity", "atm"}); uint32_t const typeFuel = classif().GetTypeByPath({"amenity", "fuel"}); uint32_t const typeCarSharing = classif().GetTypeByPath({"amenity", "car_sharing"}); uint32_t const typeCarRental = classif().GetTypeByPath({"amenity", "car_rantal"}); FeatureBuilderParams params; MetadataTagProcessor p(params); Metadata & md = params.GetMetadata(); // Ignore tag 'operator' if feature have inappropriate type. p("operator", "Some"); TEST(md.Empty(), ()); params.SetType(typeAtm); p("operator", "Some"); TEST_EQUAL(md.Get(Metadata::FMD_OPERATOR), "Some", ()); md.Drop(Metadata::FMD_OPERATOR); params.SetType(typeFuel); p("operator", "Some"); TEST_EQUAL(md.Get(Metadata::FMD_OPERATOR), "Some", ()); md.Drop(Metadata::FMD_OPERATOR); params.SetType(typeCarSharing); params.AddType(typeCarRental); p("operator", "Some"); TEST_EQUAL(md.Get(Metadata::FMD_OPERATOR), "Some", ()); md.Drop(Metadata::FMD_OPERATOR); } UNIT_TEST(Metadata_ValidateAndFormat_height) { FeatureBuilderParams params; MetadataTagProcessor p(params); Metadata & md = params.GetMetadata(); p("height", "0"); TEST(md.Empty(), ()); p("height", "0,0000"); TEST(md.Empty(), ()); p("height", "0.0"); TEST(md.Empty(), ()); p("height", "123"); TEST_EQUAL(md.Get(Metadata::FMD_HEIGHT), "123", ()); md.Drop(Metadata::FMD_HEIGHT); p("height", "123.2"); TEST_EQUAL(md.Get(Metadata::FMD_HEIGHT), "123.2", ()); md.Drop(Metadata::FMD_HEIGHT); p("height", "2 m"); TEST_EQUAL(md.Get(Metadata::FMD_HEIGHT), "2", ()); md.Drop(Metadata::FMD_HEIGHT); p("height", "3-6"); TEST_EQUAL(md.Get(Metadata::FMD_HEIGHT), "6", ()); } UNIT_TEST(Metadata_ValidateAndFormat_wikipedia) { char const * kWikiKey = "wikipedia"; FeatureBuilderParams params; MetadataTagProcessor p(params); Metadata & md = params.GetMetadata(); #ifdef OMIM_OS_MOBILE #define WIKIHOST "m.wikipedia.org" #else #define WIKIHOST "wikipedia.org" #endif p(kWikiKey, "en:Bad %20Data"); TEST_EQUAL(md.Get(Metadata::FMD_WIKIPEDIA), "en:Bad %20Data", ()); TEST_EQUAL(md.GetWikiURL(), "https://en." WIKIHOST "/wiki/Bad_%2520Data", ()); md.Drop(Metadata::FMD_WIKIPEDIA); p(kWikiKey, "ru:Тест_with % sign"); TEST_EQUAL(md.Get(Metadata::FMD_WIKIPEDIA), "ru:Тест with % sign", ()); TEST_EQUAL(md.GetWikiURL(), "https://ru." WIKIHOST "/wiki/Тест_with_%25_sign", ()); md.Drop(Metadata::FMD_WIKIPEDIA); p(kWikiKey, "https://be-tarask.wikipedia.org/wiki/Вялікае_Княства_Літоўскае"); TEST_EQUAL(md.Get(Metadata::FMD_WIKIPEDIA), "be-tarask:Вялікае Княства Літоўскае", ()); TEST_EQUAL(md.GetWikiURL(), "https://be-tarask." WIKIHOST "/wiki/Вялікае_Княства_Літоўскае", ()); md.Drop(Metadata::FMD_WIKIPEDIA); // Final link points to https and mobile version. p(kWikiKey, "http://en.wikipedia.org/wiki/A"); TEST_EQUAL(md.Get(Metadata::FMD_WIKIPEDIA), "en:A", ()); TEST_EQUAL(md.GetWikiURL(), "https://en." WIKIHOST "/wiki/A", ()); md.Drop(Metadata::FMD_WIKIPEDIA); p(kWikiKey, "invalid_input_without_language_and_colon"); TEST(md.Empty(), (md.Get(Metadata::FMD_WIKIPEDIA))); p(kWikiKey, "https://en.wikipedia.org/wiki/"); TEST(md.Empty(), (md.Get(Metadata::FMD_WIKIPEDIA))); p(kWikiKey, "http://wikipedia.org/wiki/Article"); TEST(md.Empty(), (md.Get(Metadata::FMD_WIKIPEDIA))); p(kWikiKey, "http://somesite.org"); TEST(md.Empty(), (md.Get(Metadata::FMD_WIKIPEDIA))); p(kWikiKey, "http://www.spamsitewithaslash.com/"); TEST(md.Empty(), (md.Get(Metadata::FMD_WIKIPEDIA))); p(kWikiKey, "http://.wikipedia.org/wiki/Article"); TEST(md.Empty(), (md.Get(Metadata::FMD_WIKIPEDIA))); // Ignore incorrect prefixes. p(kWikiKey, "ht.tps://en.wikipedia.org/wiki/Whuh"); TEST_EQUAL(md.Get(Metadata::FMD_WIKIPEDIA), "en:Whuh", ()); md.Drop(Metadata::FMD_WIKIPEDIA); p(kWikiKey, "http://ru.google.com/wiki/wutlol"); TEST(md.Empty(), ("Not a wikipedia site.")); #undef WIKIHOST } // Look at: https://wiki.openstreetmap.org/wiki/Key:duration for details // about "duration" format. UNIT_CLASS_TEST(TestWithClassificator, Metadata_ValidateAndFormat_duration) { FeatureBuilderParams params; params.AddType(classif().GetTypeByPath({"route", "ferry"})); MetadataTagProcessor p(params); Metadata & md = params.GetMetadata(); auto const test = [&](std::string const & osm, std::string const & expected) { p("duration", osm); if (expected.empty()) { TEST(md.Empty(), ()); } else { TEST_EQUAL(md.Get(Metadata::FMD_DURATION), expected, ()); md.Drop(Metadata::FMD_DURATION); } }; // "10" - 10 minutes ~ 0.16667 hours test("10", "0.16667"); // 10:00 - 10 hours test("10:00", "10"); test("QWE", ""); // 1:1:1 - 1 hour + 1 minute + 1 second test("1:1:1", "1.0169"); // 10 hours and 30 minutes test("10:30", "10.5"); test("30", "0.5"); test("60", "1"); test("120", "2"); test("35:10", "35.167"); test("35::10", ""); test("", ""); test("0", ""); test("asd", ""); test("10 minutes", ""); test("01:15 h", ""); test("08:00;07:00;06:30", ""); test("3-4 minutes", ""); test("5:00 hours", ""); test("12 min", ""); // means 20 seconds test("PT20S", "0.0055556"); // means 7 minutes test("PT7M", "0.11667"); // means 10 minutes and 40 seconds test("PT10M40S", "0.17778"); test("PT50M", "0.83333"); // means 2 hours test("PT2H", "2"); // means 7 hours and 50 minutes test("PT7H50M", "7.8333"); test("PT60M", "1"); test("PT15M", "0.25"); // means 1000 years, but we don't support such duration. test("PT1000Y", ""); test("PTPT", ""); // means 4 day, but we don't support such duration. test("P4D", ""); test("PT50:20", ""); } <commit_msg>[generator tests] Fix misprint.<commit_after>#include "testing/testing.hpp" #include "generator/generator_tests_support/test_with_classificator.hpp" #include "generator/osm2meta.hpp" #include "indexer/classificator.hpp" #include "base/logging.hpp" using namespace generator::tests_support; using feature::Metadata; UNIT_TEST(Metadata_ValidateAndFormat_stars) { FeatureBuilderParams params; MetadataTagProcessor p(params); Metadata & md = params.GetMetadata(); // Ignore incorrect values. p("stars", "0"); TEST(md.Empty(), ()); p("stars", "-1"); TEST(md.Empty(), ()); p("stars", "aasdasdas"); TEST(md.Empty(), ()); p("stars", "8"); TEST(md.Empty(), ()); p("stars", "10"); TEST(md.Empty(), ()); p("stars", "910"); TEST(md.Empty(), ()); p("stars", "100"); TEST(md.Empty(), ()); // Check correct values. p("stars", "1"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "1", ()); md.Drop(Metadata::FMD_STARS); p("stars", "2"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "2", ()); md.Drop(Metadata::FMD_STARS); p("stars", "3"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "3", ()); md.Drop(Metadata::FMD_STARS); p("stars", "4"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "4", ()); md.Drop(Metadata::FMD_STARS); p("stars", "5"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "5", ()); md.Drop(Metadata::FMD_STARS); p("stars", "6"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "6", ()); md.Drop(Metadata::FMD_STARS); p("stars", "7"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "7", ()); md.Drop(Metadata::FMD_STARS); // Check almost correct values. p("stars", "4+"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "4", ()); md.Drop(Metadata::FMD_STARS); p("stars", "5s"); TEST_EQUAL(md.Get(Metadata::FMD_STARS), "5", ()); md.Drop(Metadata::FMD_STARS); } UNIT_CLASS_TEST(TestWithClassificator, Metadata_ValidateAndFormat_operator) { uint32_t const typeAtm = classif().GetTypeByPath({"amenity", "atm"}); uint32_t const typeFuel = classif().GetTypeByPath({"amenity", "fuel"}); uint32_t const typeCarSharing = classif().GetTypeByPath({"amenity", "car_sharing"}); uint32_t const typeCarRental = classif().GetTypeByPath({"amenity", "car_rental"}); FeatureBuilderParams params; MetadataTagProcessor p(params); Metadata & md = params.GetMetadata(); // Ignore tag 'operator' if feature have inappropriate type. p("operator", "Some"); TEST(md.Empty(), ()); params.SetType(typeAtm); p("operator", "Some"); TEST_EQUAL(md.Get(Metadata::FMD_OPERATOR), "Some", ()); md.Drop(Metadata::FMD_OPERATOR); params.SetType(typeFuel); p("operator", "Some"); TEST_EQUAL(md.Get(Metadata::FMD_OPERATOR), "Some", ()); md.Drop(Metadata::FMD_OPERATOR); params.SetType(typeCarSharing); params.AddType(typeCarRental); p("operator", "Some"); TEST_EQUAL(md.Get(Metadata::FMD_OPERATOR), "Some", ()); md.Drop(Metadata::FMD_OPERATOR); } UNIT_TEST(Metadata_ValidateAndFormat_height) { FeatureBuilderParams params; MetadataTagProcessor p(params); Metadata & md = params.GetMetadata(); p("height", "0"); TEST(md.Empty(), ()); p("height", "0,0000"); TEST(md.Empty(), ()); p("height", "0.0"); TEST(md.Empty(), ()); p("height", "123"); TEST_EQUAL(md.Get(Metadata::FMD_HEIGHT), "123", ()); md.Drop(Metadata::FMD_HEIGHT); p("height", "123.2"); TEST_EQUAL(md.Get(Metadata::FMD_HEIGHT), "123.2", ()); md.Drop(Metadata::FMD_HEIGHT); p("height", "2 m"); TEST_EQUAL(md.Get(Metadata::FMD_HEIGHT), "2", ()); md.Drop(Metadata::FMD_HEIGHT); p("height", "3-6"); TEST_EQUAL(md.Get(Metadata::FMD_HEIGHT), "6", ()); } UNIT_TEST(Metadata_ValidateAndFormat_wikipedia) { char const * kWikiKey = "wikipedia"; FeatureBuilderParams params; MetadataTagProcessor p(params); Metadata & md = params.GetMetadata(); #ifdef OMIM_OS_MOBILE #define WIKIHOST "m.wikipedia.org" #else #define WIKIHOST "wikipedia.org" #endif p(kWikiKey, "en:Bad %20Data"); TEST_EQUAL(md.Get(Metadata::FMD_WIKIPEDIA), "en:Bad %20Data", ()); TEST_EQUAL(md.GetWikiURL(), "https://en." WIKIHOST "/wiki/Bad_%2520Data", ()); md.Drop(Metadata::FMD_WIKIPEDIA); p(kWikiKey, "ru:Тест_with % sign"); TEST_EQUAL(md.Get(Metadata::FMD_WIKIPEDIA), "ru:Тест with % sign", ()); TEST_EQUAL(md.GetWikiURL(), "https://ru." WIKIHOST "/wiki/Тест_with_%25_sign", ()); md.Drop(Metadata::FMD_WIKIPEDIA); p(kWikiKey, "https://be-tarask.wikipedia.org/wiki/Вялікае_Княства_Літоўскае"); TEST_EQUAL(md.Get(Metadata::FMD_WIKIPEDIA), "be-tarask:Вялікае Княства Літоўскае", ()); TEST_EQUAL(md.GetWikiURL(), "https://be-tarask." WIKIHOST "/wiki/Вялікае_Княства_Літоўскае", ()); md.Drop(Metadata::FMD_WIKIPEDIA); // Final link points to https and mobile version. p(kWikiKey, "http://en.wikipedia.org/wiki/A"); TEST_EQUAL(md.Get(Metadata::FMD_WIKIPEDIA), "en:A", ()); TEST_EQUAL(md.GetWikiURL(), "https://en." WIKIHOST "/wiki/A", ()); md.Drop(Metadata::FMD_WIKIPEDIA); p(kWikiKey, "invalid_input_without_language_and_colon"); TEST(md.Empty(), (md.Get(Metadata::FMD_WIKIPEDIA))); p(kWikiKey, "https://en.wikipedia.org/wiki/"); TEST(md.Empty(), (md.Get(Metadata::FMD_WIKIPEDIA))); p(kWikiKey, "http://wikipedia.org/wiki/Article"); TEST(md.Empty(), (md.Get(Metadata::FMD_WIKIPEDIA))); p(kWikiKey, "http://somesite.org"); TEST(md.Empty(), (md.Get(Metadata::FMD_WIKIPEDIA))); p(kWikiKey, "http://www.spamsitewithaslash.com/"); TEST(md.Empty(), (md.Get(Metadata::FMD_WIKIPEDIA))); p(kWikiKey, "http://.wikipedia.org/wiki/Article"); TEST(md.Empty(), (md.Get(Metadata::FMD_WIKIPEDIA))); // Ignore incorrect prefixes. p(kWikiKey, "ht.tps://en.wikipedia.org/wiki/Whuh"); TEST_EQUAL(md.Get(Metadata::FMD_WIKIPEDIA), "en:Whuh", ()); md.Drop(Metadata::FMD_WIKIPEDIA); p(kWikiKey, "http://ru.google.com/wiki/wutlol"); TEST(md.Empty(), ("Not a wikipedia site.")); #undef WIKIHOST } // Look at: https://wiki.openstreetmap.org/wiki/Key:duration for details // about "duration" format. UNIT_CLASS_TEST(TestWithClassificator, Metadata_ValidateAndFormat_duration) { FeatureBuilderParams params; params.AddType(classif().GetTypeByPath({"route", "ferry"})); MetadataTagProcessor p(params); Metadata & md = params.GetMetadata(); auto const test = [&](std::string const & osm, std::string const & expected) { p("duration", osm); if (expected.empty()) { TEST(md.Empty(), ()); } else { TEST_EQUAL(md.Get(Metadata::FMD_DURATION), expected, ()); md.Drop(Metadata::FMD_DURATION); } }; // "10" - 10 minutes ~ 0.16667 hours test("10", "0.16667"); // 10:00 - 10 hours test("10:00", "10"); test("QWE", ""); // 1:1:1 - 1 hour + 1 minute + 1 second test("1:1:1", "1.0169"); // 10 hours and 30 minutes test("10:30", "10.5"); test("30", "0.5"); test("60", "1"); test("120", "2"); test("35:10", "35.167"); test("35::10", ""); test("", ""); test("0", ""); test("asd", ""); test("10 minutes", ""); test("01:15 h", ""); test("08:00;07:00;06:30", ""); test("3-4 minutes", ""); test("5:00 hours", ""); test("12 min", ""); // means 20 seconds test("PT20S", "0.0055556"); // means 7 minutes test("PT7M", "0.11667"); // means 10 minutes and 40 seconds test("PT10M40S", "0.17778"); test("PT50M", "0.83333"); // means 2 hours test("PT2H", "2"); // means 7 hours and 50 minutes test("PT7H50M", "7.8333"); test("PT60M", "1"); test("PT15M", "0.25"); // means 1000 years, but we don't support such duration. test("PT1000Y", ""); test("PTPT", ""); // means 4 day, but we don't support such duration. test("P4D", ""); test("PT50:20", ""); } <|endoftext|>
<commit_before>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2020 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Jay Taves // ============================================================================= // // Class that wraps data contained in a message about Soil Contact Model (SCM) // Deformable terrain. See chrono_vehicle/terrain/SCMDeformableTerrain.* for // more details. // // ============================================================================= #include "chrono_synchrono/flatbuffer/message/SynSCMMessage.h" using namespace chrono::vehicle; namespace chrono { namespace synchrono { namespace Terrain = SynFlatBuffers::Terrain; namespace SCM = SynFlatBuffers::Terrain::SCM; /// Constructors SynSCMMessage::SynSCMMessage(unsigned int source_id, unsigned int destination_id) : SynMessage(source_id, destination_id) {} void SynSCMMessage::ConvertFromFlatBuffers(const SynFlatBuffers::Message* message) { // System of casts from SynFlatBuffers::Message to SynFlatBuffers::Terrain::SCM::State if (message->message_type() != SynFlatBuffers::Type_Terrain_State) return; m_source_id = message->source_id(); m_destination_id = message->destination_id(); auto terrain_state = message->message_as_Terrain_State(); auto state = terrain_state->message_as_SCM_State(); modified_nodes.clear(); auto nodes_size = state->nodes()->size(); for (size_t i = 0; i < nodes_size; i++) { auto fb_node = state->nodes()->Get((flatbuffers::uoffset_t)i); auto node = std::make_pair(ChVector2<>(fb_node->x(), fb_node->y()), fb_node->level()); modified_nodes.push_back(node); } this->time = state->time(); } /// Generate FlatBuffers message from this message's state FlatBufferMessage SynSCMMessage::ConvertToFlatBuffers(flatbuffers::FlatBufferBuilder& builder) { std::vector<SCM::NodeLevel> modified_nodes(this->modified_nodes.size()); for (auto& node : this->modified_nodes) modified_nodes.push_back(SCM::NodeLevel(node.first.x(), node.first.y(), node.second)); auto scm_state = SCM::CreateStateDirect(builder, time, &modified_nodes); auto flatbuffer_state = Terrain::CreateState(builder, Terrain::Type::Type_SCM_State, scm_state.Union()); auto flatbuffer_message = SynFlatBuffers::CreateMessage(builder, // SynFlatBuffers::Type_Terrain_State, // flatbuffer_state.Union(), // m_source_id, m_destination_id); // return flatbuffers::Offset<SynFlatBuffers::Message>(flatbuffer_message); } } // namespace synchrono } // namespace chrono <commit_msg>Fix bug in creating FlatBuffers message for SCM terrain<commit_after>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2020 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Jay Taves // ============================================================================= // // Class that wraps data contained in a message about Soil Contact Model (SCM) // Deformable terrain. See chrono_vehicle/terrain/SCMDeformableTerrain.* for // more details. // // ============================================================================= #include "chrono_synchrono/flatbuffer/message/SynSCMMessage.h" using namespace chrono::vehicle; namespace chrono { namespace synchrono { namespace Terrain = SynFlatBuffers::Terrain; namespace SCM = SynFlatBuffers::Terrain::SCM; /// Constructors SynSCMMessage::SynSCMMessage(unsigned int source_id, unsigned int destination_id) : SynMessage(source_id, destination_id) {} void SynSCMMessage::ConvertFromFlatBuffers(const SynFlatBuffers::Message* message) { // System of casts from SynFlatBuffers::Message to SynFlatBuffers::Terrain::SCM::State if (message->message_type() != SynFlatBuffers::Type_Terrain_State) return; m_source_id = message->source_id(); m_destination_id = message->destination_id(); auto terrain_state = message->message_as_Terrain_State(); auto state = terrain_state->message_as_SCM_State(); modified_nodes.clear(); auto nodes_size = state->nodes()->size(); for (size_t i = 0; i < nodes_size; i++) { auto fb_node = state->nodes()->Get((flatbuffers::uoffset_t)i); auto node = std::make_pair(ChVector2<>(fb_node->x(), fb_node->y()), fb_node->level()); modified_nodes.push_back(node); } this->time = state->time(); } /// Generate FlatBuffers message from this message's state FlatBufferMessage SynSCMMessage::ConvertToFlatBuffers(flatbuffers::FlatBufferBuilder& builder) { std::vector<SCM::NodeLevel> modified_nodes; modified_nodes.reserve(this->modified_nodes.size()); for (const auto& node : this->modified_nodes) modified_nodes.push_back(SCM::NodeLevel(node.first.x(), node.first.y(), node.second)); auto scm_state = SCM::CreateStateDirect(builder, time, &modified_nodes); auto flatbuffer_state = Terrain::CreateState(builder, Terrain::Type::Type_SCM_State, scm_state.Union()); auto flatbuffer_message = SynFlatBuffers::CreateMessage(builder, // SynFlatBuffers::Type_Terrain_State, // flatbuffer_state.Union(), // m_source_id, m_destination_id); // return flatbuffers::Offset<SynFlatBuffers::Message>(flatbuffer_message); } } // namespace synchrono } // namespace chrono <|endoftext|>
<commit_before>/* * ZoteroCollectionsLocal.cpp * * Copyright (C) 2009-20 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "ZoteroCollectionsLocal.hpp" #include <boost/bind.hpp> #include <boost/algorithm/algorithm.hpp> #include <shared_core/Error.hpp> #include <shared_core/json/Json.hpp> #include <core/FileSerializer.hpp> #include <core/Database.hpp> #include <core/system/Process.hpp> #include <session/prefs/UserState.hpp> #include <session/SessionModuleContext.hpp> #include "ZoteroCSL.hpp" #include "session-config.h" using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace zotero { namespace collections { namespace { void execQuery(boost::shared_ptr<database::IConnection> pConnection, const std::string& sql, boost::function<void(const database::Row&)> rowHandler) { database::Rowset rows; database::Query query = pConnection->query(sql); Error error = pConnection->execute(query, rows); if (error) { LOG_ERROR(error); return; } for (database::RowsetIterator it = rows.begin(); it != rows.end(); ++it) { const database::Row& row = *it; rowHandler(row); } } template <typename T> std::string readString(const database::Row& row, T accessor, std::string defaultValue = "") { std::ostringstream ostr; auto& props = row.get_properties(accessor); switch(props.get_data_type()) { case soci::dt_string: ostr << row.get<std::string>(accessor); break; case soci::dt_double: ostr << row.get<double>(accessor); break; case soci::dt_integer: ostr << row.get<int>(accessor); break; case soci::dt_long_long: ostr << row.get<long long>(accessor); break; case soci::dt_unsigned_long_long: ostr << row.get<unsigned long long>(accessor); break; default: ostr << defaultValue; } return ostr.str(); } std::string creatorsSQL(const std::string& name = "") { boost::format fmt(R"( SELECT items.key as key, items.version, creators.firstName as firstName, creators.LastName as lastName, itemCreators.orderIndex, creatorTypes.creatorType as creatorType FROM items join itemTypes on items.itemTypeID = itemTypes.itemTypeID join libraries on items.libraryID = libraries.libraryID %1% join itemCreators on items.itemID = itemCreators.itemID join creators on creators.creatorID = itemCreators.creatorID join creatorTypes on itemCreators.creatorTypeID = creatorTypes.creatorTypeID WHERE libraries.type = 'user' AND itemTypes.typeName <> 'attachment' %2% ORDER BY items.key ASC, itemCreators.orderIndex )"); return boost::str(fmt % (!name.empty() ? "join collections on libraries.libraryID = collections.libraryID" : "") % (!name.empty() ? "AND collections.collectionName = '" + name + "'" : "")); } std::string collectionSQL(const std::string& name = "") { boost::format fmt(R"( SELECT items.key as key, items.version, fields.fieldName as name, itemDataValues.value as value FROM items join libraries on items.libraryID = libraries.libraryID %1% join itemTypes on items.itemTypeID = itemTypes.itemTypeID join itemData on items.itemID = itemData.itemID join itemDataValues on itemData.valueID = itemDataValues.valueID join fields on itemData.fieldID = fields.fieldID join itemTypeFields on (itemTypes.itemTypeID = itemTypeFields.itemTypeID AND fields.fieldID = itemTypeFields.fieldID) WHERE libraries.type = 'user' AND itemTypes.typeName <> 'attachment' %2% ORDER BY items.key ASC, itemTypeFields.orderIndex )"); return boost::str(fmt % (!name.empty() ? "join collectionItems on items.itemID = collectionItems.itemID\n" "join collections on collectionItems.collectionID = collections.collectionID" : "") % (!name.empty() ? "AND collections.collectionName = '" + name + "'" : "")); } ZoteroCollection getCollection(boost::shared_ptr<database::IConnection> pConnection, const std::string& name, const std::string& tableName = "") { // get creators ZoteroCreatorsByKey creators; execQuery(pConnection, creatorsSQL(tableName), [&creators](const database::Row& row) { std::string key = row.get<std::string>("key"); ZoteroCreator creator; creator.firstName = row.get<std::string>("firstName"); creator.lastName = row.get<std::string>("lastName"); creator.creatorType = row.get<std::string>("creatorType"); creators[key].push_back(creator); }); int version = 0; std::map<std::string,std::string> currentItem; json::Array itemsJson; execQuery(pConnection, collectionSQL(tableName), [&creators, &version, &currentItem, &itemsJson](const database::Row& row) { std::string key = row.get<std::string>("key"); std::string currentKey = currentItem.count("key") ? currentItem["key"] : ""; // inception if (currentKey.empty()) { currentItem["key"] = key; } // finished an item else if (key != currentKey) { itemsJson.push_back(sqliteItemToCSL(currentItem, creators)); currentItem.clear(); currentItem["key"] = key; } // update version int rowVersion = row.get<int>("version"); if (rowVersion > version) version = rowVersion; // read the csl std::string name = row.get<std::string>("name"); std::string value = readString(row, "value"); currentItem[name] = value; }); // add the final item (if we had one) if (currentItem.count("key")) itemsJson.push_back(sqliteItemToCSL(currentItem, creators)); // success! ZoteroCollection collection(ZoteroCollectionSpec(name, version)); collection.items = itemsJson; return collection; } ZoteroCollectionSpecs getCollections(boost::shared_ptr<database::IConnection> pConnection) { std::string sql = R"( SELECT collectionName, collections.version FROM collections join libraries on libraries.libraryID = collections.libraryID WHERE libraries.type = 'user' )"; ZoteroCollectionSpecs specs; execQuery(pConnection, sql, [&specs](const database::Row& row) { ZoteroCollectionSpec spec; spec.name = row.get<std::string>("collectionName"); spec.version = row.get<int>("version"); specs.push_back(spec); }); return specs; } ZoteroCollection getLibrary(boost::shared_ptr<database::IConnection> pConnection) { return getCollection(pConnection, kMyLibrary); } int getLibraryVersion(boost::shared_ptr<database::IConnection> pConnection) { int version = 0; execQuery(pConnection, "SELECT MAX(version) AS version from items", [&version](const database::Row& row) { std::string versionStr = readString(row, static_cast<std::size_t>(0), "0"); version = safe_convert::stringTo<int>(versionStr, 0); }); return version; } Error connect(std::string dataDir, boost::shared_ptr<database::IConnection>* ppConnection) { std::string db = dataDir + "/zotero.sqlite"; database::SqliteConnectionOptions options = { db }; return database::connect(options, ppConnection); } void getLocalLibrary(std::string key, ZoteroCollectionSpec cacheSpec, ZoteroCollectionsHandler handler) { // connect to the database boost::shared_ptr<database::IConnection> pConnection; Error error = connect(key, &pConnection); if (error) { handler(error, std::vector<ZoteroCollection>()); return; } // get the library version and reflect the cache back if it's up to date int version = getLibraryVersion(pConnection); if (version <= cacheSpec.version) { handler(error, { cacheSpec }); } else { ZoteroCollection library = getLibrary(pConnection); handler(Success(), std::vector<ZoteroCollection>{ library }); } } void getLocalCollections(std::string key, std::vector<std::string> collections, ZoteroCollectionSpecs cacheSpecs, ZoteroCollectionsHandler handler) { // connect to the database boost::shared_ptr<database::IConnection> pConnection; Error error = connect(key, &pConnection); if (error) { handler(error, std::vector<ZoteroCollection>()); return; } // divide collections into ones we need to do a download for, and one that // we already have an up to date version for ZoteroCollections upToDateCollections; std::vector<std::pair<std::string, ZoteroCollectionSpec>> downloadCollections; // get all of the user's collections ZoteroCollectionSpecs userCollections = getCollections(pConnection); for (auto userCollection : userCollections) { std::string name = userCollection.name; int version = userCollection.version; // see if this is a requested collection bool requested = std::count_if(collections.begin(), collections.end(), [name](const std::string& str) { return boost::algorithm::iequals(name, str); }) > 0 ; if (requested) { // see if we need to do a download for this collection ZoteroCollectionSpecs::const_iterator it = std::find_if( cacheSpecs.begin(), cacheSpecs.end(), [name](ZoteroCollectionSpec spec) { return boost::algorithm::iequals(spec.name,name); } ); if (it != cacheSpecs.end()) { ZoteroCollectionSpec collectionSpec(name, version); if (it->version < version) downloadCollections.push_back(std::make_pair(name, collectionSpec)); else upToDateCollections.push_back(collectionSpec); } else { downloadCollections.push_back(std::make_pair(name, ZoteroCollectionSpec(name, version))); } } } // read collections we need to then append them to already up to date collections ZoteroCollections resultCollections = upToDateCollections; for (auto downloadSpec : downloadCollections) { std::string name = downloadSpec.second.name; ZoteroCollection coll = getCollection(pConnection, name, name); resultCollections.push_back(coll); } handler(Success(), resultCollections); } FilePath userHomeDir() { std::string homeEnv; #ifdef _WIN32 homeEnv = "USERPROFILE"; #else homeEnv = "HOME"; #endif return FilePath(string_utils::systemToUtf8(core::system::getenv(homeEnv))); } // https://www.zotero.org/support/kb/profile_directory FilePath zoteroProfilesDir() { FilePath homeDir = userHomeDir(); std::string profilesDir; #if defined(_WIN32) profilesDir = "AppData\\Roaming\\Zotero\\Zotero\\Profiles"; #elif defined(__APPLE__) profilesDir = "Library/Application Support/Zotero/Profiles"; #else profilesDir = ".zotero/zotero"; #endif return homeDir.completeChildPath(profilesDir); } // https://www.zotero.org/support/zotero_data FilePath defaultZoteroDataDir() { FilePath homeDir = userHomeDir(); return homeDir.completeChildPath("Zotero"); } FilePath detectZoteroDataDir() { // we'll fall back to the default if we can't find another dir in the profile FilePath dataDir = defaultZoteroDataDir(); // find the zotero profiles dir FilePath profilesDir = zoteroProfilesDir(); if (profilesDir.exists()) { // there will be one path in the directory std::vector<FilePath> children; Error error = profilesDir.getChildren(children); if (error) LOG_ERROR(error); if (children.size() > 0) { // there will be a single directory inside the profiles dir FilePath profileDir = children[0]; FilePath prefsFile = profileDir.completeChildPath("prefs.js"); if (prefsFile.exists()) { // read the prefs.js file std::string prefs; error = core::readStringFromFile(prefsFile, &prefs); if (error) LOG_ERROR(error); // look for the zotero.dataDir pref boost::smatch match; boost::regex regex("user_pref\\(\"extensions.zotero.dataDir\",\\s*\"([^\"]+)\"\\);"); if (boost::regex_search(prefs, match, regex)) { // set dataDiroly if the path exists FilePath profileDataDir(match[1]); if (profileDataDir.exists()) dataDir = profileDataDir; } } } } // return the data dir return dataDir; } } // end anonymous namespace bool localZoteroAvailable() { // availability based on server vs. desktop #ifdef RSTUDIO_SERVER bool local = false; #else bool local = true; #endif // however, also make it available in debug mode for local dev/test #ifndef NDEBUG local = true; #endif return local; } // Detect the Zotero data directory and return it if it exists FilePath detectedZoteroDataDirectory() { if (localZoteroAvailable()) { FilePath dataDir = detectZoteroDataDir(); if (dataDir.exists()) return dataDir; else return FilePath(); } else { return FilePath(); } } // Returns the zoteroDataDirectory (if any). This will return a valid FilePath // if the user has specified a zotero data dir in the preferences; OR if // a zotero data dir was detected on the system. In the former case the // path may not exist (and this should be logged as an error) FilePath zoteroDataDirectory() { std::string dataDir = prefs::userState().zoteroDataDir(); if (!dataDir.empty()) return module_context::resolveAliasedPath(dataDir); else return detectedZoteroDataDirectory(); } ZoteroCollectionSource localCollections() { ZoteroCollectionSource source; source.getLibrary = getLocalLibrary; source.getCollections = getLocalCollections; return source; } } // end namespace collections } // end namespace zotero } // end namespace modules } // end namespace session } // end namespace rstudio <commit_msg>Read itemType as a field for items<commit_after>/* * ZoteroCollectionsLocal.cpp * * Copyright (C) 2009-20 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #include "ZoteroCollectionsLocal.hpp" #include <boost/bind.hpp> #include <boost/algorithm/algorithm.hpp> #include <shared_core/Error.hpp> #include <shared_core/json/Json.hpp> #include <core/FileSerializer.hpp> #include <core/Database.hpp> #include <core/system/Process.hpp> #include <session/prefs/UserState.hpp> #include <session/SessionModuleContext.hpp> #include "ZoteroCSL.hpp" #include "session-config.h" using namespace rstudio::core; namespace rstudio { namespace session { namespace modules { namespace zotero { namespace collections { namespace { void execQuery(boost::shared_ptr<database::IConnection> pConnection, const std::string& sql, boost::function<void(const database::Row&)> rowHandler) { database::Rowset rows; database::Query query = pConnection->query(sql); Error error = pConnection->execute(query, rows); if (error) { LOG_ERROR(error); return; } for (database::RowsetIterator it = rows.begin(); it != rows.end(); ++it) { const database::Row& row = *it; rowHandler(row); } } template <typename T> std::string readString(const database::Row& row, T accessor, std::string defaultValue = "") { std::ostringstream ostr; auto& props = row.get_properties(accessor); switch(props.get_data_type()) { case soci::dt_string: ostr << row.get<std::string>(accessor); break; case soci::dt_double: ostr << row.get<double>(accessor); break; case soci::dt_integer: ostr << row.get<int>(accessor); break; case soci::dt_long_long: ostr << row.get<long long>(accessor); break; case soci::dt_unsigned_long_long: ostr << row.get<unsigned long long>(accessor); break; default: ostr << defaultValue; } return ostr.str(); } std::string creatorsSQL(const std::string& name = "") { boost::format fmt(R"( SELECT items.key as key, items.version, creators.firstName as firstName, creators.LastName as lastName, itemCreators.orderIndex, creatorTypes.creatorType as creatorType FROM items join itemTypes on items.itemTypeID = itemTypes.itemTypeID join libraries on items.libraryID = libraries.libraryID %1% join itemCreators on items.itemID = itemCreators.itemID join creators on creators.creatorID = itemCreators.creatorID join creatorTypes on itemCreators.creatorTypeID = creatorTypes.creatorTypeID WHERE libraries.type = 'user' AND itemTypes.typeName <> 'attachment' %2% ORDER BY items.key ASC, itemCreators.orderIndex )"); return boost::str(fmt % (!name.empty() ? "join collections on libraries.libraryID = collections.libraryID" : "") % (!name.empty() ? "AND collections.collectionName = '" + name + "'" : "")); } std::string collectionSQL(const std::string& name = "") { boost::format fmt(R"( SELECT items.key as key, items.version, fields.fieldName as name, itemDataValues.value as value, itemTypeFields.orderIndex as fieldOrder FROM items join libraries on items.libraryID = libraries.libraryID %1% join itemTypes on items.itemTypeID = itemTypes.itemTypeID join itemData on items.itemID = itemData.itemID join itemDataValues on itemData.valueID = itemDataValues.valueID join fields on itemData.fieldID = fields.fieldID join itemTypeFields on (itemTypes.itemTypeID = itemTypeFields.itemTypeID AND fields.fieldID = itemTypeFields.fieldID) WHERE libraries.type = 'user' AND itemTypes.typeName <> 'attachment' %2% UNION SELECT items.key as key, items.version, 'type' as name, itemTypes.typeName as value, 0 as fieldOrder FROM items join itemTypes on items.itemTypeID = itemTypes.itemTypeID join libraries on items.libraryID = libraries.libraryID %1% WHERE libraries.type = 'user' AND itemTypes.typeName <> 'attachment' %2% ORDER BY key ASC, fieldOrder ASC )"); return boost::str(fmt % (!name.empty() ? "join collectionItems on items.itemID = collectionItems.itemID\n" "join collections on collectionItems.collectionID = collections.collectionID" : "") % (!name.empty() ? "AND collections.collectionName = '" + name + "'" : "")); } ZoteroCollection getCollection(boost::shared_ptr<database::IConnection> pConnection, const std::string& name, const std::string& tableName = "") { // get creators ZoteroCreatorsByKey creators; execQuery(pConnection, creatorsSQL(tableName), [&creators](const database::Row& row) { std::string key = row.get<std::string>("key"); ZoteroCreator creator; creator.firstName = row.get<std::string>("firstName"); creator.lastName = row.get<std::string>("lastName"); creator.creatorType = row.get<std::string>("creatorType"); creators[key].push_back(creator); }); int version = 0; std::map<std::string,std::string> currentItem; json::Array itemsJson; execQuery(pConnection, collectionSQL(tableName), [&creators, &version, &currentItem, &itemsJson](const database::Row& row) { std::string key = row.get<std::string>("key"); std::string currentKey = currentItem.count("key") ? currentItem["key"] : ""; // inception if (currentKey.empty()) { currentItem["key"] = key; } // finished an item else if (key != currentKey) { itemsJson.push_back(sqliteItemToCSL(currentItem, creators)); currentItem.clear(); currentItem["key"] = key; } // update version int rowVersion = row.get<int>("version"); if (rowVersion > version) version = rowVersion; // read the csl std::string name = row.get<std::string>("name"); std::string value = readString(row, "value"); currentItem[name] = value; }); // add the final item (if we had one) if (currentItem.count("key")) itemsJson.push_back(sqliteItemToCSL(currentItem, creators)); // success! ZoteroCollection collection(ZoteroCollectionSpec(name, version)); collection.items = itemsJson; return collection; } ZoteroCollectionSpecs getCollections(boost::shared_ptr<database::IConnection> pConnection) { std::string sql = R"( SELECT collectionName, collections.version FROM collections join libraries on libraries.libraryID = collections.libraryID WHERE libraries.type = 'user' )"; ZoteroCollectionSpecs specs; execQuery(pConnection, sql, [&specs](const database::Row& row) { ZoteroCollectionSpec spec; spec.name = row.get<std::string>("collectionName"); spec.version = row.get<int>("version"); specs.push_back(spec); }); return specs; } ZoteroCollection getLibrary(boost::shared_ptr<database::IConnection> pConnection) { return getCollection(pConnection, kMyLibrary); } int getLibraryVersion(boost::shared_ptr<database::IConnection> pConnection) { int version = 0; execQuery(pConnection, "SELECT MAX(version) AS version from items", [&version](const database::Row& row) { std::string versionStr = readString(row, static_cast<std::size_t>(0), "0"); version = safe_convert::stringTo<int>(versionStr, 0); }); return version; } Error connect(std::string dataDir, boost::shared_ptr<database::IConnection>* ppConnection) { std::string db = dataDir + "/zotero.sqlite"; database::SqliteConnectionOptions options = { db }; return database::connect(options, ppConnection); } void getLocalLibrary(std::string key, ZoteroCollectionSpec cacheSpec, ZoteroCollectionsHandler handler) { // connect to the database boost::shared_ptr<database::IConnection> pConnection; Error error = connect(key, &pConnection); if (error) { handler(error, std::vector<ZoteroCollection>()); return; } // get the library version and reflect the cache back if it's up to date int version = getLibraryVersion(pConnection); if (version <= cacheSpec.version) { handler(error, { cacheSpec }); } else { ZoteroCollection library = getLibrary(pConnection); handler(Success(), std::vector<ZoteroCollection>{ library }); } } void getLocalCollections(std::string key, std::vector<std::string> collections, ZoteroCollectionSpecs cacheSpecs, ZoteroCollectionsHandler handler) { // connect to the database boost::shared_ptr<database::IConnection> pConnection; Error error = connect(key, &pConnection); if (error) { handler(error, std::vector<ZoteroCollection>()); return; } // divide collections into ones we need to do a download for, and one that // we already have an up to date version for ZoteroCollections upToDateCollections; std::vector<std::pair<std::string, ZoteroCollectionSpec>> downloadCollections; // get all of the user's collections ZoteroCollectionSpecs userCollections = getCollections(pConnection); for (auto userCollection : userCollections) { std::string name = userCollection.name; int version = userCollection.version; // see if this is a requested collection bool requested = std::count_if(collections.begin(), collections.end(), [name](const std::string& str) { return boost::algorithm::iequals(name, str); }) > 0 ; if (requested) { // see if we need to do a download for this collection ZoteroCollectionSpecs::const_iterator it = std::find_if( cacheSpecs.begin(), cacheSpecs.end(), [name](ZoteroCollectionSpec spec) { return boost::algorithm::iequals(spec.name,name); } ); if (it != cacheSpecs.end()) { ZoteroCollectionSpec collectionSpec(name, version); if (it->version < version) downloadCollections.push_back(std::make_pair(name, collectionSpec)); else upToDateCollections.push_back(collectionSpec); } else { downloadCollections.push_back(std::make_pair(name, ZoteroCollectionSpec(name, version))); } } } // read collections we need to then append them to already up to date collections ZoteroCollections resultCollections = upToDateCollections; for (auto downloadSpec : downloadCollections) { std::string name = downloadSpec.second.name; ZoteroCollection coll = getCollection(pConnection, name, name); resultCollections.push_back(coll); } handler(Success(), resultCollections); } FilePath userHomeDir() { std::string homeEnv; #ifdef _WIN32 homeEnv = "USERPROFILE"; #else homeEnv = "HOME"; #endif return FilePath(string_utils::systemToUtf8(core::system::getenv(homeEnv))); } // https://www.zotero.org/support/kb/profile_directory FilePath zoteroProfilesDir() { FilePath homeDir = userHomeDir(); std::string profilesDir; #if defined(_WIN32) profilesDir = "AppData\\Roaming\\Zotero\\Zotero\\Profiles"; #elif defined(__APPLE__) profilesDir = "Library/Application Support/Zotero/Profiles"; #else profilesDir = ".zotero/zotero"; #endif return homeDir.completeChildPath(profilesDir); } // https://www.zotero.org/support/zotero_data FilePath defaultZoteroDataDir() { FilePath homeDir = userHomeDir(); return homeDir.completeChildPath("Zotero"); } FilePath detectZoteroDataDir() { // we'll fall back to the default if we can't find another dir in the profile FilePath dataDir = defaultZoteroDataDir(); // find the zotero profiles dir FilePath profilesDir = zoteroProfilesDir(); if (profilesDir.exists()) { // there will be one path in the directory std::vector<FilePath> children; Error error = profilesDir.getChildren(children); if (error) LOG_ERROR(error); if (children.size() > 0) { // there will be a single directory inside the profiles dir FilePath profileDir = children[0]; FilePath prefsFile = profileDir.completeChildPath("prefs.js"); if (prefsFile.exists()) { // read the prefs.js file std::string prefs; error = core::readStringFromFile(prefsFile, &prefs); if (error) LOG_ERROR(error); // look for the zotero.dataDir pref boost::smatch match; boost::regex regex("user_pref\\(\"extensions.zotero.dataDir\",\\s*\"([^\"]+)\"\\);"); if (boost::regex_search(prefs, match, regex)) { // set dataDiroly if the path exists FilePath profileDataDir(match[1]); if (profileDataDir.exists()) dataDir = profileDataDir; } } } } // return the data dir return dataDir; } } // end anonymous namespace bool localZoteroAvailable() { // availability based on server vs. desktop #ifdef RSTUDIO_SERVER bool local = false; #else bool local = true; #endif // however, also make it available in debug mode for local dev/test #ifndef NDEBUG local = true; #endif return local; } // Detect the Zotero data directory and return it if it exists FilePath detectedZoteroDataDirectory() { if (localZoteroAvailable()) { FilePath dataDir = detectZoteroDataDir(); if (dataDir.exists()) return dataDir; else return FilePath(); } else { return FilePath(); } } // Returns the zoteroDataDirectory (if any). This will return a valid FilePath // if the user has specified a zotero data dir in the preferences; OR if // a zotero data dir was detected on the system. In the former case the // path may not exist (and this should be logged as an error) FilePath zoteroDataDirectory() { std::string dataDir = prefs::userState().zoteroDataDir(); if (!dataDir.empty()) return module_context::resolveAliasedPath(dataDir); else return detectedZoteroDataDirectory(); } ZoteroCollectionSource localCollections() { ZoteroCollectionSource source; source.getLibrary = getLocalLibrary; source.getCollections = getLocalCollections; return source; } } // end namespace collections } // end namespace zotero } // end namespace modules } // end namespace session } // end namespace rstudio <|endoftext|>
<commit_before>#include "system_info.h" #include <QObject> SystemInfo::SystemInfo() { QStringList lines = FileUtil::readListFromFile(PROC_CPUINFO) .filter(QRegExp("^model name")); QStringList cpuMhz = FileUtil::readListFromFile(PROC_CPUINFO) .filter(QRegExp("^cpu MHz")); if (! lines.isEmpty()) { QStringList model = lines.at(0).trimmed().split(":").at(1).split("@"); QStringList cpumhz = cpuMhz.at(0).trimmed().split(":").at(1).split("@"); if ( model.count() > 0) { QRegExp regexp("\\s+"); QString space(" "); this->cpuModel = model.at(0).trimmed().replace(regexp, space); this->cpuSpeed = cpuMhz.at(0).trimmed().replace(regexp, space); } } else { QString unknown(QObject::tr("Unknown")); this->cpuModel = unknown; this->cpuSpeed = unknown; } CpuInfo ci; this->cpuCore = QString::number(ci.getCpuCoreCount()); // get username QString name = qgetenv("USER"); if (name.isEmpty()) name = qgetenv("USERNAME"); try { if (name.isEmpty()) name = CommandUtil::exec("whoami").trimmed(); } catch (QString &ex) { qCritical() << ex; } username = name; } QString SystemInfo::getUsername() const { return username; } QString SystemInfo::getHostname() const { return QSysInfo::machineHostName(); } QString SystemInfo::getPlatform() const { return QString("%1 %2") .arg(QSysInfo::kernelType()) .arg(QSysInfo::currentCpuArchitecture()); } QString SystemInfo::getDistribution() const { return QSysInfo::prettyProductName(); } QString SystemInfo::getKernel() const { return QSysInfo::kernelVersion(); } QString SystemInfo::getCpuModel() const { return this->cpuModel; } QString SystemInfo::getCpuSpeed() const { return this->cpuSpeed; } QString SystemInfo::getCpuCore() const { return this->cpuCore; } QFileInfoList SystemInfo::getCrashReports() const { QDir reports("/var/crash"); return reports.entryInfoList(QDir::Files); } QFileInfoList SystemInfo::getAppLogs() const { QDir logs("/var/log"); return logs.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot); } QFileInfoList SystemInfo::getAppCaches() const { QString homePath = QStandardPaths::writableLocation(QStandardPaths::HomeLocation); QDir caches(homePath + "/.cache"); return caches.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot); } <commit_msg>SytemInfo : Fix my naming blunder.<commit_after>#include "system_info.h" #include <QObject> SystemInfo::SystemInfo() { QStringList lines = FileUtil::readListFromFile(PROC_CPUINFO) .filter(QRegExp("^model name")); QStringList cpuMhz = FileUtil::readListFromFile(PROC_CPUINFO) .filter(QRegExp("^cpu MHz")); if (! lines.isEmpty()) { QStringList model = lines.at(0).trimmed().split(":").at(1).split("@"); QStringList cpumhz = cpuMhz.at(0).trimmed().split(":").at(1).split("@"); if ( model.count() > 0) { QRegExp regexp("\\s+"); QString space(" "); this->cpuModel = model.at(0).trimmed().replace(regexp, space); this->cpuSpeed = cpumhz.at(0).trimmed().replace(regexp, space); } } else { QString unknown(QObject::tr("Unknown")); this->cpuModel = unknown; this->cpuSpeed = unknown; } CpuInfo ci; this->cpuCore = QString::number(ci.getCpuCoreCount()); // get username QString name = qgetenv("USER"); if (name.isEmpty()) name = qgetenv("USERNAME"); try { if (name.isEmpty()) name = CommandUtil::exec("whoami").trimmed(); } catch (QString &ex) { qCritical() << ex; } username = name; } QString SystemInfo::getUsername() const { return username; } QString SystemInfo::getHostname() const { return QSysInfo::machineHostName(); } QString SystemInfo::getPlatform() const { return QString("%1 %2") .arg(QSysInfo::kernelType()) .arg(QSysInfo::currentCpuArchitecture()); } QString SystemInfo::getDistribution() const { return QSysInfo::prettyProductName(); } QString SystemInfo::getKernel() const { return QSysInfo::kernelVersion(); } QString SystemInfo::getCpuModel() const { return this->cpuModel; } QString SystemInfo::getCpuSpeed() const { return this->cpuSpeed; } QString SystemInfo::getCpuCore() const { return this->cpuCore; } QFileInfoList SystemInfo::getCrashReports() const { QDir reports("/var/crash"); return reports.entryInfoList(QDir::Files); } QFileInfoList SystemInfo::getAppLogs() const { QDir logs("/var/log"); return logs.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot); } QFileInfoList SystemInfo::getAppCaches() const { QString homePath = QStandardPaths::writableLocation(QStandardPaths::HomeLocation); QDir caches(homePath + "/.cache"); return caches.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot); } <|endoftext|>
<commit_before>#ifndef STAN_MATH_GPU_OPENCL_CONTEXT_HPP #define STAN_MATH_GPU_OPENCL_CONTEXT_HPP #ifdef STAN_OPENCL #define __CL_ENABLE_EXCEPTIONS #include <stan/math/prim/arr/err/check_opencl.hpp> #include <stan/math/prim/scal/err/logic_error.hpp> #include <CL/cl.hpp> #include <cmath> #include <fstream> #include <map> #include <vector> #define DEVICE_FILTER CL_DEVICE_TYPE_GPU /** * @file stan/math/gpu/opencl_context.hpp * @brief Initialization for OpenCL: * 1. find OpenCL platforms and devices available * 2. create context * 3. set up job queue * 4. initialize kernel groups */ namespace stan { namespace math { // TODO(Rok): select some other platform/device than 0 // TODO(Rok): option to turn profiling OFF /** * The class that represents the OpenCL runtime * * The class is used to find the OpenCL supported * platforms/devices and initialize the OpenCL * context/command queue. * */ class opencl_context { private: const char* description_; cl::Context oclContext_; cl::CommandQueue oclQueue_; cl::Platform oclPlatform_; cl::Device oclDevice_; std::vector<cl::Platform> allPlatforms; std::vector<cl::Device> allDevices; size_t max_workgroup_size_; typedef std::map<const char*, const char*> map_string; typedef std::map<const char*, cl::Kernel> map_kernel; typedef std::map<const char*, bool> map_bool; public: map_string kernel_groups; map_string kernel_strings; map_kernel kernels; map_bool compiled_kernels; const char* dummy_kernel; void init_kernel_groups(); void init_platforms(); void init_devices(); void init_context_queue(); void init_program(); void compile_kernel_group(const char* group); cl::Kernel get_kernel(const char* name); opencl_context() { dummy_kernel = "__kernel void dummy(__global const int* foo) { };"; try { init_kernel_groups(); init_platforms(); init_devices(); init_context_queue(); init_program(); } catch (const cl::Error &e) { check_ocl_error("build", e); } } // delete copy and move constructors and assign operators opencl_context(opencl_context const&) = delete; opencl_context(opencl_context&&) = delete; opencl_context& operator = (opencl_context const&) = delete; opencl_context& operator = (opencl_context &&) = delete; /** * Returns the description of the OpenCL * platform and device that is used. * */ inline const char* description() const { return description_; } /** * Returns the reference to the * OpenCL context. If no context was created, * a new context is created. * */ inline cl::Context &context() { return oclContext_; } /** * Returns the reference to the active * OpenCL command queue. If no context * and queue were created, * a new context and queue are created and * the reference to the new queue is returned. * */ inline cl::CommandQueue &queue() { return oclQueue_; } /** * Returns the reference to the active * OpenCL command queue. If no context * and queue were created, * a new context and queue are created and * the reference to the new queue is returned. * */ inline int maxWorkgroupSize() { return max_workgroup_size_; } }; inline void opencl_context::init_platforms() { cl::Platform::get(&allPlatforms); if (allPlatforms.size() == 0) { logic_error("OpenCL Initialization", "[Platform]", "", "No OpenCL platforms found"); } oclPlatform_ = allPlatforms[0]; } inline void opencl_context::init_devices() { oclPlatform_.getDevices(DEVICE_FILTER, &allDevices); // TODO(Steve): This should throw which platform if (allDevices.size() == 0) { logic_error("OpenCL Initialization", "[Device]", "", "No OpenCL devices found on the selected platform."); } oclDevice_ = allDevices[0]; } // This also grabs the description and max workgroup size inline void opencl_context::init_context_queue() { std::ostringstream message; // hack to remove -Waddress, -Wnonnull-compare warnings from GCC 6 message << "Device " << oclDevice_.getInfo<CL_DEVICE_NAME>() << " on the platform " << oclPlatform_.getInfo<CL_PLATFORM_NAME>(); std::string description_ = message.str(); allDevices[0].getInfo<size_t>(CL_DEVICE_MAX_WORK_GROUP_SIZE, &max_workgroup_size_); oclContext_ = cl::Context(allDevices); oclQueue_ = cl::CommandQueue(oclContext_, oclDevice_, CL_QUEUE_PROFILING_ENABLE, NULL); } inline void opencl_context::init_program() { // Compile the dummy kernel used for timing purposes cl::Program::Sources source( 1, std::make_pair(dummy_kernel, strlen(dummy_kernel))); cl::Program program_ = cl::Program(oclContext_, source); try { program_.build(allDevices); kernels["dummy"] = cl::Kernel(program_, "dummy", NULL); compiled_kernels["timing"] = true; } catch (const cl::Error &e) { logic_error( "OpenCL Initialization", e.what(), e.err(), "\nRetrieving build log\n", program_.getBuildInfo<CL_PROGRAM_BUILD_LOG>(allDevices[0]).c_str()); } } /** * Initalizes the global std::map variables that * hold the OpenCL kernel sources, the groups to * which each kernel is assigned to and the * information about which kernel was already compiled. * */ inline void opencl_context::init_kernel_groups() { // To identify the kernel group kernel_groups["transpose"] = "basic_matrix"; kernel_groups["copy"] = "basic_matrix"; kernel_groups["zeros"] = "basic_matrix"; kernel_groups["identity"] = "basic_matrix"; kernel_groups["copy_triangular"] = "basic_matrix"; kernel_groups["copy_triangular_transposed"] = "basic_matrix"; kernel_groups["add"] = "basic_matrix"; kernel_groups["subtract"] = "basic_matrix"; kernel_groups["copy_submatrix"] = "basic_matrix"; kernel_groups["scalar_mul_diagonal"] = "matrix_multiply"; kernel_groups["scalar_mul"] = "matrix_multiply"; kernel_groups["basic_multiply"] = "matrix_multiply"; kernel_groups["multiply_self_transposed"] = "matrix_multiply"; kernel_groups["lower_tri_inv_step1"] = "matrix_inverse"; kernel_groups["lower_tri_inv_step2"] = "matrix_inverse"; kernel_groups["lower_tri_inv_step3"] = "matrix_inverse"; kernel_groups["cholesky_block"] = "cholesky_decomposition"; kernel_groups["check_nan"] = "check_gpu"; kernel_groups["check_symmetric"] = "check_gpu"; kernel_groups["check_diagonal_zeros"] = "check_gpu"; kernel_groups["dummy"] = "timing"; // Kernel group strings // the dummy kernel is the only one not included in files // so it is treated before the loop that iterates // through kernels to load all kernel_strings["timing"] = dummy_kernel; kernel_strings["check_gpu"] = #include <stan/math/prim/mat/fun/kern_gpu/check_gpu.cl> // NOLINT ; // NOLINT kernel_strings["cholesky_decomposition"] = #include <stan/math/prim/mat/fun/kern_gpu/cholesky_decomposition.cl> // NOLINT ; // NOLINT kernel_strings["matrix_inverse"] = #include <stan/math/prim/mat/fun/kern_gpu/matrix_inverse.cl> // NOLINT ; // NOLINT kernel_strings["matrix_multiply"] = #include <stan/math/prim/mat/fun/kern_gpu/matrix_multiply.cl> // NOLINT ; // NOLINT kernel_strings["basic_matrix"] = #include <stan/math/prim/mat/fun/kern_gpu/basic_matrix.cl> // NOLINT ; // NOLINT // Check if the kernels were already compiled compiled_kernels["basic_matrix"] = false; compiled_kernels["matrix_multiply"] = false; compiled_kernels["timing"] = false; compiled_kernels["matrix_inverse"] = false; compiled_kernels["cholesky_decomposition"] = false; compiled_kernels["check_gpu"] = false; } /** * Compiles all the kernel in the specified group * * @param group The kernel group name * */ inline void opencl_context::compile_kernel_group(const char* group) { cl::Context &ctx = context(); std::vector<cl::Device> devices = ctx.getInfo<CL_CONTEXT_DEVICES>(); const char* kernel_source = kernel_strings[group]; cl::Program::Sources source( 1, std::make_pair(kernel_source, strlen(kernel_source))); cl::Program program_ = cl::Program(ctx, source); try { char temp[100]; int local = 32; int gpu_local_max = sqrt(maxWorkgroupSize()); if (gpu_local_max < local) local = gpu_local_max; // parameters that have special limits are for now handled here // kernels with paramters will be compiled separately // for now we have static parameters, so this will be OK snprintf(temp, sizeof(temp), "-D TS=%d -D TS1=%d -D TS2=%d ", local, local, local); program_.build(devices, temp); cl_int err = CL_SUCCESS; // Iterate over the kernel list // and get all the kernels from this group for (auto it : kernel_groups) { if (strcmp(group, it.second) == 0) { kernels[(it.first)] = cl::Kernel(program_, it.first, &err); } } } catch (const cl::Error &e) { logic_error( "\n OpenCL Initialization", e.what(), e.err(), "\nRetrieving build log\n", program_.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[0]).c_str()); } } /** * Returns the reference to the compiled kernel. * If the kernel has not yet been compiled, * the kernel group is compiled first. * * @param name The kernel name * */ inline cl::Kernel opencl_context::get_kernel(const char* name) { // Compile the kernel group and return the kernel if (!compiled_kernels[kernel_groups[name]]) { compile_kernel_group(kernel_groups[name]); compiled_kernels[kernel_groups[name]] = true; } return kernels[name]; } static opencl_context opencl_context; } // namespace math } // namespace stan #endif #endif <commit_msg>added the doxygen comments for the opencl_context.hpp<commit_after>#ifndef STAN_MATH_GPU_OPENCL_CONTEXT_HPP #define STAN_MATH_GPU_OPENCL_CONTEXT_HPP #ifdef STAN_OPENCL #define __CL_ENABLE_EXCEPTIONS #include <stan/math/prim/arr/err/check_opencl.hpp> #include <stan/math/prim/scal/err/logic_error.hpp> #include <CL/cl.hpp> #include <cmath> #include <fstream> #include <map> #include <vector> #define DEVICE_FILTER CL_DEVICE_TYPE_GPU /** * @file stan/math/gpu/opencl_context.hpp * @brief Initialization for OpenCL: * 1. find OpenCL platforms and devices available * 2. create context * 3. set up job queue * 4. initialize kernel groups */ namespace stan { namespace math { // TODO(Rok): select some other platform/device than 0 // TODO(Rok): option to turn profiling OFF /** * The class that represents the OpenCL runtime * * The class is used to find the OpenCL supported * platforms/devices and initialize the OpenCL * context/command queue. * */ class opencl_context { private: const char* description_; cl::Context oclContext_; cl::CommandQueue oclQueue_; cl::Platform oclPlatform_; cl::Device oclDevice_; std::vector<cl::Platform> allPlatforms; std::vector<cl::Device> allDevices; size_t max_workgroup_size_; typedef std::map<const char*, const char*> map_string; typedef std::map<const char*, cl::Kernel> map_kernel; typedef std::map<const char*, bool> map_bool; public: map_string kernel_groups; map_string kernel_strings; map_kernel kernels; map_bool compiled_kernels; const char* dummy_kernel; void init_kernel_groups(); void init_platforms(); void init_devices(); void init_context_queue(); void init_program(); void compile_kernel_group(const char* group); cl::Kernel get_kernel(const char* name); /** * The constructor for the opencl_context class. * It initializes the kernel groups, devices, context, * queue and compiles the dummy kernel. * * @throw std::domain_error if an OpenCL error occurs */ opencl_context() { dummy_kernel = "__kernel void dummy(__global const int* foo) { };"; try { init_kernel_groups(); init_platforms(); init_devices(); init_context_queue(); init_program(); } catch (const cl::Error &e) { check_ocl_error("build", e); } } /*! The copy and move constructors and assign operators are disabled */ opencl_context(opencl_context const&) = delete; opencl_context(opencl_context&&) = delete; opencl_context& operator = (opencl_context const&) = delete; opencl_context& operator = (opencl_context &&) = delete; /** * Returns the description of the OpenCL * platform and device that is used. * */ inline const char* description() const { return description_; } /** * Returns the reference to the * OpenCL context. If no context was created, * a new context is created. * */ inline cl::Context &context() { return oclContext_; } /** * Returns the reference to the active * OpenCL command queue. If no context * and queue were created, * a new context and queue are created and * the reference to the new queue is returned. * */ inline cl::CommandQueue &queue() { return oclQueue_; } /** * Returns the maximum workgroup size for the * device in the context. */ inline int maxWorkgroupSize() { return max_workgroup_size_; } }; /** * Retrieves the OpenCL platforms on the system and * assigns the first platform as the target platform * * @throw std::logic_error if no OpenCL platforms are found */ inline void opencl_context::init_platforms() { cl::Platform::get(&allPlatforms); if (allPlatforms.size() == 0) { logic_error("OpenCL Initialization", "[Platform]", "", "No OpenCL platforms found"); } oclPlatform_ = allPlatforms[0]; } /** * Retrieves the devices from the platform. * and assigns the first found device * as the target device. * * @throw std::logic_error if no OpenCL supported devices * are found on the target platform */ inline void opencl_context::init_devices() { oclPlatform_.getDevices(DEVICE_FILTER, &allDevices); // TODO(Steve): This should throw which platform if (allDevices.size() == 0) { logic_error("OpenCL Initialization", "[Device]", "", "No OpenCL devices found on the selected platform."); } oclDevice_ = allDevices[0]; } /** * Initializes the OpenCL context and queue. * This function also retrieves the information * on the description and the maximum workgroup size * of the device. * */ inline void opencl_context::init_context_queue() { std::ostringstream message; // hack to remove -Waddress, -Wnonnull-compare warnings from GCC 6 message << "Device " << oclDevice_.getInfo<CL_DEVICE_NAME>() << " on the platform " << oclPlatform_.getInfo<CL_PLATFORM_NAME>(); std::string description_ = message.str(); allDevices[0].getInfo<size_t>(CL_DEVICE_MAX_WORK_GROUP_SIZE, &max_workgroup_size_); oclContext_ = cl::Context(allDevices); oclQueue_ = cl::CommandQueue(oclContext_, oclDevice_, CL_QUEUE_PROFILING_ENABLE, NULL); } /** * Compiles the dummy kernel that is used for * profiling purposes. * * @throw std::logic_error if the dummy kernel has errors * */ inline void opencl_context::init_program() { // Compile the dummy kernel used for timing purposes cl::Program::Sources source( 1, std::make_pair(dummy_kernel, strlen(dummy_kernel))); cl::Program program_ = cl::Program(oclContext_, source); try { program_.build(allDevices); kernels["dummy"] = cl::Kernel(program_, "dummy", NULL); compiled_kernels["timing"] = true; } catch (const cl::Error &e) { logic_error( "OpenCL Initialization", e.what(), e.err(), "\nRetrieving build log\n", program_.getBuildInfo<CL_PROGRAM_BUILD_LOG>(allDevices[0]).c_str()); } } /** * Initalizes the global std::map variables that * hold the OpenCL kernel sources, the groups to * which each kernel is assigned to and the * information about which kernel was already compiled. * */ inline void opencl_context::init_kernel_groups() { // To identify the kernel group kernel_groups["transpose"] = "basic_matrix"; kernel_groups["copy"] = "basic_matrix"; kernel_groups["zeros"] = "basic_matrix"; kernel_groups["identity"] = "basic_matrix"; kernel_groups["copy_triangular"] = "basic_matrix"; kernel_groups["copy_triangular_transposed"] = "basic_matrix"; kernel_groups["add"] = "basic_matrix"; kernel_groups["subtract"] = "basic_matrix"; kernel_groups["copy_submatrix"] = "basic_matrix"; kernel_groups["scalar_mul_diagonal"] = "matrix_multiply"; kernel_groups["scalar_mul"] = "matrix_multiply"; kernel_groups["basic_multiply"] = "matrix_multiply"; kernel_groups["multiply_self_transposed"] = "matrix_multiply"; kernel_groups["lower_tri_inv_step1"] = "matrix_inverse"; kernel_groups["lower_tri_inv_step2"] = "matrix_inverse"; kernel_groups["lower_tri_inv_step3"] = "matrix_inverse"; kernel_groups["cholesky_block"] = "cholesky_decomposition"; kernel_groups["check_nan"] = "check_gpu"; kernel_groups["check_symmetric"] = "check_gpu"; kernel_groups["check_diagonal_zeros"] = "check_gpu"; kernel_groups["dummy"] = "timing"; // Kernel group strings // the dummy kernel is the only one not included in files // so it is treated before the loop that iterates // through kernels to load all kernel_strings["timing"] = dummy_kernel; kernel_strings["check_gpu"] = #include <stan/math/prim/mat/fun/kern_gpu/check_gpu.cl> // NOLINT ; // NOLINT kernel_strings["cholesky_decomposition"] = #include <stan/math/prim/mat/fun/kern_gpu/cholesky_decomposition.cl> // NOLINT ; // NOLINT kernel_strings["matrix_inverse"] = #include <stan/math/prim/mat/fun/kern_gpu/matrix_inverse.cl> // NOLINT ; // NOLINT kernel_strings["matrix_multiply"] = #include <stan/math/prim/mat/fun/kern_gpu/matrix_multiply.cl> // NOLINT ; // NOLINT kernel_strings["basic_matrix"] = #include <stan/math/prim/mat/fun/kern_gpu/basic_matrix.cl> // NOLINT ; // NOLINT // Check if the kernels were already compiled compiled_kernels["basic_matrix"] = false; compiled_kernels["matrix_multiply"] = false; compiled_kernels["timing"] = false; compiled_kernels["matrix_inverse"] = false; compiled_kernels["cholesky_decomposition"] = false; compiled_kernels["check_gpu"] = false; } /** * Compiles all the kernela in the specified group * * @param group The kernel group name * * @throw std::logic_error if there are compilation errors * when compiling the specified kernel group sources * */ inline void opencl_context::compile_kernel_group(const char* group) { cl::Context &ctx = context(); std::vector<cl::Device> devices = ctx.getInfo<CL_CONTEXT_DEVICES>(); const char* kernel_source = kernel_strings[group]; cl::Program::Sources source( 1, std::make_pair(kernel_source, strlen(kernel_source))); cl::Program program_ = cl::Program(ctx, source); try { char temp[100]; int local = 32; int gpu_local_max = sqrt(maxWorkgroupSize()); if (gpu_local_max < local) local = gpu_local_max; // parameters that have special limits are for now handled here // kernels with paramters will be compiled separately // for now we have static parameters, so this will be OK snprintf(temp, sizeof(temp), "-D TS=%d -D TS1=%d -D TS2=%d ", local, local, local); program_.build(devices, temp); cl_int err = CL_SUCCESS; // Iterate over the kernel list // and get all the kernels from this group for (auto it : kernel_groups) { if (strcmp(group, it.second) == 0) { kernels[(it.first)] = cl::Kernel(program_, it.first, &err); } } } catch (const cl::Error &e) { logic_error( "\n OpenCL Initialization", e.what(), e.err(), "\nRetrieving build log\n", program_.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[0]).c_str()); } } /** * Returns the reference to the compiled kernel. * If the kernel has not yet been compiled, * the kernel group is compiled first. * * @param name The kernel name * * @return a copy of the cl::Kernel object */ inline cl::Kernel opencl_context::get_kernel(const char* name) { // Compile the kernel group and return the kernel if (!compiled_kernels[kernel_groups[name]]) { compile_kernel_group(kernel_groups[name]); compiled_kernels[kernel_groups[name]] = true; } return kernels[name]; } static opencl_context opencl_context; } // namespace math } // namespace stan #endif #endif <|endoftext|>
<commit_before>#include "bs_mesh_stdafx.h" #include "py_rs_mesh.h" #include "bs_mesh_grdecl.h" #include "export_python_wrapper.h" #include "py_pair_converter.h" #include <boost/python/tuple.hpp> #ifdef BSPY_EXPORTING_PLUGIN using namespace boost::python; namespace blue_sky { namespace python { PY_EXPORTER (mesh_grdecl_exporter, rs_mesh_iface_exporter) .def ("get_ext_to_int", &T::get_ext_to_int, args(""), "Return reference to external-to-internal mesh index") .def ("get_int_to_ext", &T::get_int_to_ext, args(""), "Return reference to internal-to-external mesh index") .def ("get_volumes", &T::get_volumes, args(""), "Return reference to volumes vector") .def ("get_dimensions_range", &T::get_dimensions_range, args("dim1_max, dim1_min, dim2_max, dim2_min, dim3_max, dim3_min"), "Get dimensions ranges") .def ("get_element_size", &T::get_element_size, args ("n_elem, dx, dy, dz"), "get elements sizes") .def ("get_element_ijk_to_int", &T::get_element_ijk_to_int, args ("i, j, k"), "get elements sizes") .def ("get_n_active_elements", &T::get_n_active_elements, args (""), "Get elements sizes") .def ("calc_element_tops", &T::calc_element_tops, args (""), "Calc element tops") .def ("calc_element_center", &T::calc_element_center, args (""), "Calc element center"); PY_EXPORTER_END; }} // eof blue_sky::python namespace { using namespace blue_sky; using namespace blue_sky::python; // same as grdecl exporter, but also export gen_coord_zcorn template <typename T> struct mesh_grdecl_exporter_plus { typedef t_long int_t; typedef t_double fp_t; typedef spv_float spfp_storarr_t; typedef spv_long spi_arr_t; typedef typename spi_arr_t::pure_pointed_t int_arr_t; static tuple refine_mesh(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points, fp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD) { spi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type()); std::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh(nx, ny, coord, zcorn, points, hit_idx, m_thresh, b_thresh); return make_tuple(r.first, r.second, nx, ny, hit_idx); } // overloads static tuple refine_mesh1(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points) { return refine_mesh(nx, ny, coord, zcorn, points); } static tuple refine_mesh2(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points, fp_t m_thresh) { return refine_mesh(nx, ny, coord, zcorn, points, m_thresh); } template <typename class_t> static class_t & export_class (class_t &class__) { using namespace boost::python; mesh_grdecl_exporter<T>::export_class (class__) .def("gen_coord_zcorn", &T::gen_coord_zcorn, args("nx, ny, nz, dx, dy, dz"), "Generate COORD & ZCORN from given dimensions") .staticmethod("gen_coord_zcorn") .def("refine_mesh", &refine_mesh, "Refine existing mesh in given points") .def("refine_mesh", &refine_mesh1, "Refine existing mesh in given points") .def("refine_mesh", &refine_mesh2, "Refine existing mesh in given points") //.def("refine_mesh", &T::refine_mesh, args("nx, ny, coord, zcorn, points"), "Refine existing mesh in given points") .staticmethod("refine_mesh") ; return class__; } }; template< class fp_type > void reg_sparray_pair() { // register converter from pair of returned arrayes to python list typedef smart_ptr< bs_array< fp_type > > spfp_array; typedef std::pair< spfp_array, spfp_array > array_pair; typedef bspy_converter< pair_traits< array_pair > > array_pair_converter; array_pair_converter::register_to_py(); array_pair_converter::register_from_py(); } } // eof hidden namespace namespace blue_sky { namespace python { void py_export_mesh_grdecl () { class_exporter< bs_mesh_grdecl, rs_mesh_iface, mesh_grdecl_exporter_plus >::export_class ("mesh_grdecl"); //reg_sparray_pair< float >(); reg_sparray_pair< double >(); } }} // namespace blue_sky::python #endif <commit_msg>-- Fix COORD-ZCONR array pair Python bindings (explicit bs_nparray)<commit_after>#include "bs_mesh_stdafx.h" #include "py_rs_mesh.h" #include "bs_mesh_grdecl.h" #include "export_python_wrapper.h" #include "py_pair_converter.h" #include <boost/python/tuple.hpp> #ifdef BSPY_EXPORTING_PLUGIN using namespace boost::python; namespace blue_sky { namespace python { PY_EXPORTER (mesh_grdecl_exporter, rs_mesh_iface_exporter) .def ("get_ext_to_int", &T::get_ext_to_int, args(""), "Return reference to external-to-internal mesh index") .def ("get_int_to_ext", &T::get_int_to_ext, args(""), "Return reference to internal-to-external mesh index") .def ("get_volumes", &T::get_volumes, args(""), "Return reference to volumes vector") .def ("get_dimensions_range", &T::get_dimensions_range, args("dim1_max, dim1_min, dim2_max, dim2_min, dim3_max, dim3_min"), "Get dimensions ranges") .def ("get_element_size", &T::get_element_size, args ("n_elem, dx, dy, dz"), "get elements sizes") .def ("get_element_ijk_to_int", &T::get_element_ijk_to_int, args ("i, j, k"), "get elements sizes") .def ("get_n_active_elements", &T::get_n_active_elements, args (""), "Get elements sizes") .def ("calc_element_tops", &T::calc_element_tops, args (""), "Calc element tops") .def ("calc_element_center", &T::calc_element_center, args (""), "Calc element center"); PY_EXPORTER_END; }} // eof blue_sky::python namespace { using namespace blue_sky; using namespace blue_sky::python; // same as grdecl exporter, but also export gen_coord_zcorn template <typename T> struct mesh_grdecl_exporter_plus { typedef t_long int_t; typedef t_double fp_t; typedef spv_float spfp_storarr_t; typedef spv_long spi_arr_t; typedef typename spi_arr_t::pure_pointed_t int_arr_t; static tuple refine_mesh(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points, fp_t m_thresh = DEF_CELL_MERGE_THRESHOLD, fp_t b_thresh = DEF_BAND_THRESHOLD) { spi_arr_t hit_idx = BS_KERNEL.create_object(int_arr_t::bs_type()); std::pair< spfp_storarr_t, spfp_storarr_t > r = T::refine_mesh(nx, ny, coord, zcorn, points, hit_idx, m_thresh, b_thresh); return make_tuple(r.first, r.second, nx, ny, hit_idx); } // overloads static tuple refine_mesh1(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points) { return refine_mesh(nx, ny, coord, zcorn, points); } static tuple refine_mesh2(int_t nx, int_t ny, spfp_storarr_t coord, spfp_storarr_t zcorn, spfp_storarr_t points, fp_t m_thresh) { return refine_mesh(nx, ny, coord, zcorn, points, m_thresh); } template <typename class_t> static class_t & export_class (class_t &class__) { using namespace boost::python; mesh_grdecl_exporter<T>::export_class (class__) .def("gen_coord_zcorn", &T::gen_coord_zcorn, args("nx, ny, nz, dx, dy, dz"), "Generate COORD & ZCORN from given dimensions") .staticmethod("gen_coord_zcorn") .def("refine_mesh", &refine_mesh, "Refine existing mesh in given points") .def("refine_mesh", &refine_mesh1, "Refine existing mesh in given points") .def("refine_mesh", &refine_mesh2, "Refine existing mesh in given points") //.def("refine_mesh", &T::refine_mesh, args("nx, ny, coord, zcorn, points"), "Refine existing mesh in given points") .staticmethod("refine_mesh") ; return class__; } }; template< class fp_type > void reg_sparray_pair() { // register converter from pair of returned arrayes to python list typedef smart_ptr< bs_array< fp_type, bs_nparray > > spfp_array; typedef std::pair< spfp_array, spfp_array > array_pair; typedef bspy_converter< pair_traits< array_pair > > array_pair_converter; array_pair_converter::register_to_py(); array_pair_converter::register_from_py(); } } // eof hidden namespace namespace blue_sky { namespace python { void py_export_mesh_grdecl () { class_exporter< bs_mesh_grdecl, rs_mesh_iface, mesh_grdecl_exporter_plus >::export_class ("mesh_grdecl"); //reg_sparray_pair< float >(); reg_sparray_pair< double >(); } }} // namespace blue_sky::python #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: fuarea.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2004-01-20 10:55:56 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #include "fuarea.hxx" #include <svx/svxids.hrc> #ifndef _SVX_TAB_AREA_HXX //autogen #include <svx/tabarea.hxx> #endif #ifndef _SV_MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef _SFXINTITEM_HXX //autogen #include <svtools/intitem.hxx> #endif #ifndef _SFXSTRITEM_HXX //autogen #include <svtools/stritem.hxx> #endif #ifndef _SFXREQUEST_HXX //autogen #include <sfx2/request.hxx> #endif #ifndef _SFXVIEWFRM_HXX #include <sfx2/viewfrm.hxx> #endif #ifndef _SFX_BINDINGS_HXX //autogen #include <sfx2/bindings.hxx> #endif #ifndef SD_VIEW_SHELL_HXX #include "ViewShell.hxx" #endif #include "drawdoc.hxx" #ifndef SD_VIEW_HXX #include "View.hxx" #endif #ifndef SD_WINDOW_HXX #include "Window.hxx" #endif #include "app.hrc" namespace sd { TYPEINIT1( FuArea, FuPoor ); /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuArea::FuArea ( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq) : FuPoor(pViewSh, pWin, pView, pDoc, rReq) { const SfxItemSet* pArgs = rReq.GetArgs(); if( !pArgs ) { // erst einmal alle eingabeparameter fuer den dialog retten SfxItemSet aInputAttr( pDoc->GetPool() ); pView->GetAttributes( aInputAttr ); const XFillStyleItem &rIFillStyleItem = (const XFillStyleItem &) aInputAttr.Get (XATTR_FILLSTYLE); const XFillColorItem &rIFillColorItem = (const XFillColorItem &) aInputAttr.Get (XATTR_FILLCOLOR); const XFillGradientItem &rIFillGradientItem = (const XFillGradientItem &) aInputAttr.Get (XATTR_FILLGRADIENT); const XFillHatchItem &rIFillHatchItem = (const XFillHatchItem &) aInputAttr.Get (XATTR_FILLHATCH); const XFillBitmapItem &rIXFillBitmapItem = (const XFillBitmapItem &) aInputAttr.Get (XATTR_FILLBITMAP); SfxItemSet* pNewAttr = new SfxItemSet( pDoc->GetPool() ); pView->GetAttributes( *pNewAttr ); SvxAreaTabDialog* pDlg = new SvxAreaTabDialog( NULL, pNewAttr, pDoc, pView ); if ( pDlg->Execute() == RET_OK ) { pView->SetAttributes (*(pDlg->GetOutputItemSet ())); } // Attribute wurden geaendert, Listboxes in Objectbars muessen aktualisiert werden static USHORT SidArray[] = { SID_ATTR_FILL_STYLE, SID_ATTR_FILL_COLOR, SID_ATTR_FILL_GRADIENT, SID_ATTR_FILL_HATCH, SID_ATTR_FILL_BITMAP, 0 }; pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray ); delete pDlg; delete pNewAttr; } rReq.Ignore (); } } // end of namespace sd <commit_msg>INTEGRATION: CWS dialogdiet (1.2.316); FILE MERGED 2004/01/17 01:28:08 mwu 1.2.316.1: DialogDiet 2004_01_17<commit_after>/************************************************************************* * * $RCSfile: fuarea.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2004-02-04 10:03:45 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #include "fuarea.hxx" #include <svx/svxids.hrc> #ifndef _SVX_TAB_AREA_HXX //autogen #include <svx/tabarea.hxx> #endif #ifndef _SV_MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef _SFXINTITEM_HXX //autogen #include <svtools/intitem.hxx> #endif #ifndef _SFXSTRITEM_HXX //autogen #include <svtools/stritem.hxx> #endif #ifndef _SFXREQUEST_HXX //autogen #include <sfx2/request.hxx> #endif #ifndef _SFXVIEWFRM_HXX #include <sfx2/viewfrm.hxx> #endif #ifndef _SFX_BINDINGS_HXX //autogen #include <sfx2/bindings.hxx> #endif #ifndef SD_VIEW_SHELL_HXX #include "ViewShell.hxx" #endif #include "drawdoc.hxx" #ifndef SD_VIEW_HXX #include "View.hxx" #endif #ifndef SD_WINDOW_HXX #include "Window.hxx" #endif #include "app.hrc" #include <svx/svxdlg.hxx> //CHINA001 #include <svx/dialogs.hrc> //CHINA001 namespace sd { TYPEINIT1( FuArea, FuPoor ); /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuArea::FuArea ( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq) : FuPoor(pViewSh, pWin, pView, pDoc, rReq) { const SfxItemSet* pArgs = rReq.GetArgs(); if( !pArgs ) { // erst einmal alle eingabeparameter fuer den dialog retten SfxItemSet aInputAttr( pDoc->GetPool() ); pView->GetAttributes( aInputAttr ); const XFillStyleItem &rIFillStyleItem = (const XFillStyleItem &) aInputAttr.Get (XATTR_FILLSTYLE); const XFillColorItem &rIFillColorItem = (const XFillColorItem &) aInputAttr.Get (XATTR_FILLCOLOR); const XFillGradientItem &rIFillGradientItem = (const XFillGradientItem &) aInputAttr.Get (XATTR_FILLGRADIENT); const XFillHatchItem &rIFillHatchItem = (const XFillHatchItem &) aInputAttr.Get (XATTR_FILLHATCH); const XFillBitmapItem &rIXFillBitmapItem = (const XFillBitmapItem &) aInputAttr.Get (XATTR_FILLBITMAP); SfxItemSet* pNewAttr = new SfxItemSet( pDoc->GetPool() ); pView->GetAttributes( *pNewAttr ); //CHINA001 SvxAreaTabDialog* pDlg = new SvxAreaTabDialog( NULL, pNewAttr, pDoc, pView ); SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create(); DBG_ASSERT(pFact, "Dialogdiet Factory fail!");//CHINA001 AbstractSvxAreaTabDialog * pDlg = pFact->CreateSvxAreaTabDialog( NULL, pNewAttr, pDoc, ResId(RID_SVXDLG_AREA), pView); DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001 if ( pDlg->Execute() == RET_OK ) { pView->SetAttributes (*(pDlg->GetOutputItemSet ())); } // Attribute wurden geaendert, Listboxes in Objectbars muessen aktualisiert werden static USHORT SidArray[] = { SID_ATTR_FILL_STYLE, SID_ATTR_FILL_COLOR, SID_ATTR_FILL_GRADIENT, SID_ATTR_FILL_HATCH, SID_ATTR_FILL_BITMAP, 0 }; pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray ); delete pDlg; delete pNewAttr; } rReq.Ignore (); } } // end of namespace sd <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: diactrl.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: kz $ $Date: 2006-12-12 17:41:36 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SD_DIACTRL_HXX #define _SD_DIACTRL_HXX #ifndef SD_DLGCTRLS_HXX #include "dlgctrls.hxx" #endif #ifndef _SFXINTITEM_HXX //autogen #include <svtools/intitem.hxx> #endif #ifndef _SFX_BINDINGS_HXX #include <sfx2/bindings.hxx> #endif #ifndef _SVX_ITEMWIN_HXX //autogen #include <svx/itemwin.hxx> #endif #ifndef _SV_FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _SV_FIELD_HXX //autogen #include <vcl/field.hxx> #endif #ifndef _SV_TOOLBOX_HXX //autogen #include <vcl/toolbox.hxx> #endif #ifndef _SFXTBXCTRL_HXX //autogen #include <sfx2/tbxctrl.hxx> #endif #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif //======================================================================== // SdPagesField: class SdPagesField : public SvxMetricField { private: ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > m_xFrame; protected: virtual void Modify(); public: SdPagesField( Window* pParent, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, WinBits nBits = WB_BORDER | WB_SPIN | WB_REPEAT ); ~SdPagesField(); void UpdatePagesField( const SfxUInt16Item* pItem ); }; //======================================================================== // SdTbxCtlDiaPages: //======================================================================== class SdTbxCtlDiaPages : public SfxToolBoxControl { public: virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ); virtual Window* CreateItemWindow( Window *pParent ); SFX_DECL_TOOLBOX_CONTROL(); SdTbxCtlDiaPages( USHORT nSlotId, USHORT nId, ToolBox& rTbx ); ~SdTbxCtlDiaPages(); }; #endif // _SD_DIACTRL_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.7.298); FILE MERGED 2008/04/01 15:35:21 thb 1.7.298.3: #i85898# Stripping all external header guards 2008/04/01 12:39:03 thb 1.7.298.2: #i85898# Stripping all external header guards 2008/03/31 13:58:12 rt 1.7.298.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: diactrl.hxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SD_DIACTRL_HXX #define _SD_DIACTRL_HXX #include "dlgctrls.hxx" #include <svtools/intitem.hxx> #include <sfx2/bindings.hxx> #include <svx/itemwin.hxx> #include <vcl/fixed.hxx> #include <vcl/field.hxx> #include <vcl/toolbox.hxx> #include <sfx2/tbxctrl.hxx> #include <com/sun/star/frame/XFrame.hpp> //======================================================================== // SdPagesField: class SdPagesField : public SvxMetricField { private: ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > m_xFrame; protected: virtual void Modify(); public: SdPagesField( Window* pParent, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& rFrame, WinBits nBits = WB_BORDER | WB_SPIN | WB_REPEAT ); ~SdPagesField(); void UpdatePagesField( const SfxUInt16Item* pItem ); }; //======================================================================== // SdTbxCtlDiaPages: //======================================================================== class SdTbxCtlDiaPages : public SfxToolBoxControl { public: virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ); virtual Window* CreateItemWindow( Window *pParent ); SFX_DECL_TOOLBOX_CONTROL(); SdTbxCtlDiaPages( USHORT nSlotId, USHORT nId, ToolBox& rTbx ); ~SdTbxCtlDiaPages(); }; #endif // _SD_DIACTRL_HXX <|endoftext|>
<commit_before>#ifndef _SDD_HOM_EXPRESSION_SIMPLE_HH_ #define _SDD_HOM_EXPRESSION_SIMPLE_HH_ #include <algorithm> // any_of, copy, find #include <cassert> #include <utility> // pair #include <vector> #include "sdd/dd/definition.hh" #include "sdd/hom/context_fwd.hh" #include "sdd/hom/definition_fwd.hh" #include "sdd/hom/evaluation_error.hh" #include "sdd/hom/expression/evaluator.hh" #include "sdd/hom/expression/stacks.hh" #include "sdd/order/order.hh" namespace sdd { namespace hom { namespace expr { /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief template <typename C> struct simple { /// @brief Needed by mem::variant. using result_type = SDD<C>; /// @brief A variable type. using variable_type = typename C::Variable; /// @brief The type of a set of values. using values_type = typename C::Values; /// @brief The evaluation's context. context<C>& cxt_; /// @brief The target of the evaluated expression. const order_position_type target_; /// @brief User evaluator of the expression. evaluator_base<C>& eval_; /// @brief Constructor. simple(context<C>& cxt, order_position_type target, evaluator_base<C>& eval) : cxt_(cxt), target_(target), eval_(eval) {} /// @brief Evaluation on hierarchical nodes. SDD<C> operator()( const hierarchical_node<C>& node, const SDD<C>& s , const order<C>& o , const std::shared_ptr<app_stack<C>>& app, const std::shared_ptr<res_stack<C>>& res , order_positions_iterator cit, order_positions_iterator end) const { auto& sdd_cxt = cxt_.sdd_context(); if (not o.contains(o.position(), target_)) // not the last level? { const bool nested_variables = std::any_of( cit, end , [&](order_position_type pos) { return o.contains(o.position(), pos); }); if (not nested_variables) { // We are not interested in this level, thus the visitor is propagated to the next level. dd::square_union<C, SDD<C>> su; su.reserve(node.size()); for (const auto& arc : node) { const SDD<C> successor = visit_self(*this, arc.successor(), o.next(), app, res, cit, end); su.add(successor, arc.valuation()); } return SDD<C>(o.variable(), su(cxt_.sdd_context())); } else { // We are interested in this level, but the target is not nested into it. Thus, we must // propagate on both nesteds SDD and successors. dd::sum_builder<C, SDD<C>> operands(node.size()); try { for (const auto& arc : node) { // push on stacks const auto local_app = std::make_shared<app_stack<C>>(arc.successor(), o.next(), app); const auto local_res = std::make_shared<res_stack<C>>(res); const auto nested = visit_self( *this, arc.valuation(), o.nested(), local_app, local_res , cit, end); assert(not local_res->result.empty() && "Invalid empty successor result"); operands.add( SDD<C>( o.variable(), nested , dd::sum<C>(sdd_cxt, std::move(local_res->result)))); } return dd::sum<C>(sdd_cxt, std::move(operands)); } catch (top<C>& t) { evaluation_error<C> e(s); e.add_top(t); throw e; } } } else { // Final level, we just need to propagate in the nested SDD. dd::sum_builder<C, SDD<C>> operands(node.size()); for (const auto& arc : node) { const auto nested = visit_self(*this, arc.valuation(), o.nested(), app, res, cit, end); operands.add(SDD<C>(o.variable(), nested, arc.successor())); } try { return dd::sum<C>(sdd_cxt, std::move(operands)); } catch (top<C>& t) { evaluation_error<C> e(s); e.add_top(t); throw e; } } } /// @brief Evaluation on flat nodes. SDD<C> operator()( const flat_node<C>& node, const SDD<C>& s , const order<C>& o , const std::shared_ptr<app_stack<C>>& app, const std::shared_ptr<res_stack<C>>& res , order_positions_iterator cit, order_positions_iterator end) const { auto& sdd_cxt = cxt_.sdd_context(); const bool last_level = o.position() == target_; const bool update_values = std::find(cit, end, o.position()) != end; if (update_values) { // Narrow the range for future searches of identifiers. cit = std::next(cit); } if (last_level) { dd::sum_builder<C, SDD<C>> operands(node.size()); for (const auto& arc : node) { if (update_values) { eval_.update(o.identifier(), arc.valuation()); } operands.add(SDD<C>(o.variable(), eval_.evaluate(), arc.successor())); } try { return dd::sum<C>(sdd_cxt, std::move(operands)); } catch (top<C>& t) { evaluation_error<C> e(s); e.add_top(t); throw e; } } else { // Not the last level, we just need to update values if necessary and to propagate on // successors. dd::square_union<C, values_type> su; for (const auto& arc : node) { if (update_values) { eval_.update(o.identifier(), arc.valuation()); } const auto successor = visit_self(*this, arc.successor(), o.next(), app, res, cit, end); su.add(successor, arc.valuation()); } return SDD<C>(o.variable(), su(sdd_cxt)); } } /// @brief Evaluation on |1|. SDD<C> operator()( const one_terminal<C>&, const SDD<C>& , const order<C>& o , const std::shared_ptr<app_stack<C>>& app, const std::shared_ptr<res_stack<C>>& res , order_positions_iterator cit, order_positions_iterator end) const { assert(app && "Target never encountered while evaluating SimpleExpression"); // Continue to the stacked successor of a previously visited hierachical node. const auto stacked_succ = visit_self(*this, app->sdd, app->ord, app->next, res->next, cit, end); res->result.add(stacked_succ); return sdd::one<C>(); } /// @brief Evaluation on |0|. /// /// Should never happen. SDD<C> operator()( const zero_terminal<C>&, const SDD<C>& , const order<C>& , const std::shared_ptr<app_stack<C>>&, const std::shared_ptr<res_stack<C>>& , order_positions_iterator, order_positions_iterator) const noexcept { assert(false); __builtin_unreachable(); } }; // struct simple /*------------------------------------------------------------------------------------------------*/ }}} // namespace sdd::hom::expr #endif // _SDD_HOM_EXPRESSION_SIMPLE_HH_ <commit_msg>Remove useless header inclusion.<commit_after>#ifndef _SDD_HOM_EXPRESSION_SIMPLE_HH_ #define _SDD_HOM_EXPRESSION_SIMPLE_HH_ #include <algorithm> // any_of, copy, find #include <cassert> #include <utility> // pair #include "sdd/dd/definition.hh" #include "sdd/hom/context_fwd.hh" #include "sdd/hom/definition_fwd.hh" #include "sdd/hom/evaluation_error.hh" #include "sdd/hom/expression/evaluator.hh" #include "sdd/hom/expression/stacks.hh" #include "sdd/order/order.hh" namespace sdd { namespace hom { namespace expr { /*------------------------------------------------------------------------------------------------*/ /// @internal /// @brief template <typename C> struct simple { /// @brief Needed by mem::variant. using result_type = SDD<C>; /// @brief A variable type. using variable_type = typename C::Variable; /// @brief The type of a set of values. using values_type = typename C::Values; /// @brief The evaluation's context. context<C>& cxt_; /// @brief The target of the evaluated expression. const order_position_type target_; /// @brief User evaluator of the expression. evaluator_base<C>& eval_; /// @brief Constructor. simple(context<C>& cxt, order_position_type target, evaluator_base<C>& eval) : cxt_(cxt), target_(target), eval_(eval) {} /// @brief Evaluation on hierarchical nodes. SDD<C> operator()( const hierarchical_node<C>& node, const SDD<C>& s , const order<C>& o , const std::shared_ptr<app_stack<C>>& app, const std::shared_ptr<res_stack<C>>& res , order_positions_iterator cit, order_positions_iterator end) const { auto& sdd_cxt = cxt_.sdd_context(); if (not o.contains(o.position(), target_)) // not the last level? { const bool nested_variables = std::any_of( cit, end , [&](order_position_type pos) { return o.contains(o.position(), pos); }); if (not nested_variables) { // We are not interested in this level, thus the visitor is propagated to the next level. dd::square_union<C, SDD<C>> su; su.reserve(node.size()); for (const auto& arc : node) { const SDD<C> successor = visit_self(*this, arc.successor(), o.next(), app, res, cit, end); su.add(successor, arc.valuation()); } return SDD<C>(o.variable(), su(cxt_.sdd_context())); } else { // We are interested in this level, but the target is not nested into it. Thus, we must // propagate on both nesteds SDD and successors. dd::sum_builder<C, SDD<C>> operands(node.size()); try { for (const auto& arc : node) { // push on stacks const auto local_app = std::make_shared<app_stack<C>>(arc.successor(), o.next(), app); const auto local_res = std::make_shared<res_stack<C>>(res); const auto nested = visit_self( *this, arc.valuation(), o.nested(), local_app, local_res , cit, end); assert(not local_res->result.empty() && "Invalid empty successor result"); operands.add( SDD<C>( o.variable(), nested , dd::sum<C>(sdd_cxt, std::move(local_res->result)))); } return dd::sum<C>(sdd_cxt, std::move(operands)); } catch (top<C>& t) { evaluation_error<C> e(s); e.add_top(t); throw e; } } } else { // Final level, we just need to propagate in the nested SDD. dd::sum_builder<C, SDD<C>> operands(node.size()); for (const auto& arc : node) { const auto nested = visit_self(*this, arc.valuation(), o.nested(), app, res, cit, end); operands.add(SDD<C>(o.variable(), nested, arc.successor())); } try { return dd::sum<C>(sdd_cxt, std::move(operands)); } catch (top<C>& t) { evaluation_error<C> e(s); e.add_top(t); throw e; } } } /// @brief Evaluation on flat nodes. SDD<C> operator()( const flat_node<C>& node, const SDD<C>& s , const order<C>& o , const std::shared_ptr<app_stack<C>>& app, const std::shared_ptr<res_stack<C>>& res , order_positions_iterator cit, order_positions_iterator end) const { auto& sdd_cxt = cxt_.sdd_context(); const bool last_level = o.position() == target_; const bool update_values = std::find(cit, end, o.position()) != end; if (update_values) { // Narrow the range for future searches of identifiers. cit = std::next(cit); } if (last_level) { dd::sum_builder<C, SDD<C>> operands(node.size()); for (const auto& arc : node) { if (update_values) { eval_.update(o.identifier(), arc.valuation()); } operands.add(SDD<C>(o.variable(), eval_.evaluate(), arc.successor())); } try { return dd::sum<C>(sdd_cxt, std::move(operands)); } catch (top<C>& t) { evaluation_error<C> e(s); e.add_top(t); throw e; } } else { // Not the last level, we just need to update values if necessary and to propagate on // successors. dd::square_union<C, values_type> su; for (const auto& arc : node) { if (update_values) { eval_.update(o.identifier(), arc.valuation()); } const auto successor = visit_self(*this, arc.successor(), o.next(), app, res, cit, end); su.add(successor, arc.valuation()); } return SDD<C>(o.variable(), su(sdd_cxt)); } } /// @brief Evaluation on |1|. SDD<C> operator()( const one_terminal<C>&, const SDD<C>& , const order<C>& o , const std::shared_ptr<app_stack<C>>& app, const std::shared_ptr<res_stack<C>>& res , order_positions_iterator cit, order_positions_iterator end) const { assert(app && "Target never encountered while evaluating SimpleExpression"); // Continue to the stacked successor of a previously visited hierachical node. const auto stacked_succ = visit_self(*this, app->sdd, app->ord, app->next, res->next, cit, end); res->result.add(stacked_succ); return sdd::one<C>(); } /// @brief Evaluation on |0|. /// /// Should never happen. SDD<C> operator()( const zero_terminal<C>&, const SDD<C>& , const order<C>& , const std::shared_ptr<app_stack<C>>&, const std::shared_ptr<res_stack<C>>& , order_positions_iterator, order_positions_iterator) const noexcept { assert(false); __builtin_unreachable(); } }; // struct simple /*------------------------------------------------------------------------------------------------*/ }}} // namespace sdd::hom::expr #endif // _SDD_HOM_EXPRESSION_SIMPLE_HH_ <|endoftext|>
<commit_before>/** * @file main.cpp * * @brief File containing main Q-Learning algorithm and all necessary associated functions to implementing this routine. * * @author Machine Learning Team 2015-2016 * @date March, 2016 */ //#define _USE_MATH_DEFINES -> for VS #include <cmath> #include <cstdlib> #include <ctime> #include <string> #include <sstream> #include <fstream> #include "StateSpace.h" #include "PriorityQueue.h" #include "State.h" #include "encoder.h" #include "CreateModule.h" /** * @brief Gives a std::string representation of a primitive type. * * @remark Can be used to print priority queue contents. * @param x Primitive type such as int, double, long ... * @return std::string conversion of param x */ template<typename T> std::string to_string(T x) { return static_cast<std::ostringstream&>((std::ostringstream() << std::dec << x)).str(); } /** * @brief Determines whether a file exists / is accessible * * @param filename File to check for * @return true if file exists, false if not or is inaccessible */ bool fileExists(const char* filename) { std::ifstream file(filename); return file.good(); } /** * @brief Analog to temperature variable in Boltzmann Distribution, computes 'evolution variable' of system. * * This function computes a normal distribution over the parameterised number of loop iterations in order * to provide a function which explores the state space dilligently initially which then decays off to the * optimal solution after a large number of loop iterations. * * The normal distribution used by this function is: * * \f[ a e^{-\frac{bt^2}{c}} + \epsilon \f] * * where a, b and c are scaling coefficients (see method body) and \f$\epsilon\f$ is some small offset. * * @param t Number of loop iterations. * @return Value of normal distribution at t loop iterations. */ double probabilityFluxDensityCoefficient(unsigned long t); /** * @brief Selects an action to perform based on a stochastic factor, epsilon, and past experiences * * @param a_queue A priority queue instance storing integral types with double type priorities, * represents the queue of possible actions with pre-initialised priority levels. * @param epsilon Fraction determining randomness of greedy search, 0.0 = completely random. * @return integer corresponding to chosen action */ int selectAction_EpsilonGreedy(const PriorityQueue<int, double>& a_queue, double epsilon); /** * @brief Selects an action to perform based on experience, iterations and probabilities. * * @param a_queue A priority queue instance storing integral types with double type priorities, * represents the queue of possible actions with pre-initialised priority levels. * @param iterations Number of iterations completed * @return integer corresponding to chosen action */ int selectAction_BoltzmannFactor(const PriorityQueue<int, double>& a_queue, unsigned long iterations); /** * @brief Updates the utility (Q-value) of the system. * * Utility (Q-Value) of the system is updated via the Temporal Difference Learning Rule given by the following equation, * * \f[ Q_{i+1} (s,a) = Q_i (s,a) + \alpha [R(s') + \gamma \underset{a}{max} Q(s',a) - Q_i (s,a)] \f] * * where Q represents the utility of a state-action pair, \f$ \alpha \f$ is the learning rate, \f$ \gamma \f$ is the discount * factor and \f$ max_a (Q) \f$ yields the action-maximum of the Q space. The learning rate should be set to a low value for * highly stochastic, asymmetric systems or a high value for a lowly stochastic, symmetric system - this value lies between 0 and 1. * The discount factor (also in the interval [0,1]) represents the time considerations of the learning algorithm, lower values indicate * "living in the moment", whilst higher values indicate "planning for the future". * * @param space Reference to StateSpace object * @param action Integer code to previous performed action * @param new_state Reference to State instance giving the new system state * @param old_state Reference to State instance giving the old system state * @param alpha Learning rate of temporal difference learning algorithm (in the interval [0,1]) * @param gamma Discount factor applied to q-learning equation (in the interval [0,1]) */ void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma); /** * @brief Performs all proxy initialisation through NAO SDK functions and structures, setting up a connection * to the robot and allowing use of movement tools and body info libraries. * * @return A vector of size 3 where the first element contains the body info proxy (type AL::ALProxy), the second * element contains the movement tools proxy (type AL::ALProxy) and the third element contains the motion * proxy (type AL::ALMotionProxy). */ std::vector<AL::ALProxy> robotProxyInitialisation() { // Libraries to load std::string bodyLibName = "bodyinfo"; std::string movementLibName = "movementtools"; // Name of camera module in library std::string bodyModuleName = "BodyInfo"; std::string movementModuleName = "MovementTools"; // Set broker name, ip and port, finding first available port from 54000 const std::string brokerName = "MotionTimingBroker"; int brokerPort = qi::os::findAvailablePort(54000); const std::string brokerIp = "0.0.0.0"; // Default parent port and ip int pport = 9559; std::string pip = "127.0.0.1"; // Need this for SOAP serialisation of floats to work setlocale(LC_NUMERIC, "C"); // Create a broker boost::shared_ptr<AL::ALBroker> broker; try { broker = AL::ALBroker::createBroker( brokerName, brokerIp, brokerPort, pip, pport, 0); } // Throw error and quit if a broker could not be created catch (...) { std::cerr << "Failed to connect broker to: " << pip << ":" << pport << std::endl; AL::ALBrokerManager::getInstance()->killAllBroker(); AL::ALBrokerManager::kill(); return 1; } // Add the broker to NAOqi AL::ALBrokerManager::setInstance(broker->fBrokerManager.lock()); AL::ALBrokerManager::getInstance()->addBroker(broker); CreateModule(movementLibName, movementModuleName, broker, false, true); CreateModule(bodyLibName, bodyModuleName, broker, false, true); std::vector<AL::ALProxy> proxyVec; // initialise proxies AL::ALProxy bodyInfoProxy(bodyModuleName, pip, pport); AL::ALProxy movementToolsProxy(movementModuleName, pip, pport); AL::ALMotionProxy motion(pip, pport); proxyVec.push_back(bodyInfoProxy); proxyVec.push_back(movementToolsProxy); proxyVec.push_back(motion); return proxyVec; } /** * @brief Program launcher! * * Contains all initialisations including setting up the StateSpace and connecting to robot via a proxy. Holds main * program loop to perform algorithm continuously using calls to selectAction and updateQ sequentially to update * utilities and choose most optimal actions to perform based on position and velocity. * * @return Program exit code */ int main() { // initialise proxies and robot connection and set movementToolsProxy object to 2nd // element of robotProxyInitialisation return vector AL::ALProxy movementToolsProxy = robotProxyInitialisation()[1]; // Learning rate - set low for highly stochastic systems, high for less random and more symmetric systems const double alpha = 0.8; // Discount factor - set low for disregarding future events, high for taking the future into more consideration const double gamma = 0.5; // Seed PRNG with current system time std::srand(static_cast<unsigned int>(std::time(NULL))); // possible actions, initialise starting action to full forwards motion int action_forwards = FORWARD; int action_backwards = BACKWARD; int chosen_action = action_forwards; // create a priority queue to copy to all the state space priority queues PriorityQueue<int, double> initiator_queue(MAX); // enqueue possible actions with intial zero utilities to initiator_queue initiator_queue.enqueueWithPriority(action_forwards, 0); initiator_queue.enqueueWithPriority(action_backwards, 0); // create encoder and calibrate to current angle Encoder encoder; encoder.Calibrate(); std::cout << "Encoder angle calibrated... " << std::endl; //pause briefly to allow the robot to be given a push if desired qi::os::msleep(5000); //create the state space, initialised with number of bins for angle and velocity // and maximum angle and velocities for discretisation limits (alter if necessary) const int angleBins = 100; const int velocityBins = 50; const double angleMax = 0.25*M_PI; const double velocityMax = 1.0; StateSpace space(angleBins, velocityBins, angleMax, velocityMax, initiator_queue); const char* serializedSpacePath = "serializedStateSpaceData.txt"; // create output file to send encoder data to const char* encoderDataPath = "encoderData.txt"; std::ofstream encoderOutput(encoderDataPath); // if file containing previous state space data exists // get handle to this file and stream contents to space object if (fileExists(serializedSpacePath)) { std::ifstream inputFile(serializedSpacePath); std::string firstFileLine; std::getline(inputFile, firstFileLine); // if file is not empty, save file data to state space object if (!firstFileLine.empty()) inputFile >> space; } // Create State objects for current state and previous state State current_state(0.0, 0.0, FORWARD); State old_state(0.0, 0.0, FORWARD); // initialise epsilon parameter for greedy search to 0.0 (fully stochastic) double epsilon = 0.0; std::cout << "Initialisation complete!" << std::endl; bool useEpsilonGreedy = true; // Each iteration currently requires 700ms time for action performing // => increase maxIterations for longer learning times const unsigned long maxIterations = 500UL; for(unsigned long i = 0; i < maxIterations; ++i) { // set current state angle to angle received from encoder // and set current state velocity to difference in new and // old state angles over some time difference current_state.theta = M_PI * (encoder.GetAngle()) / 180; current_state.theta_dot = (current_state.theta - old_state.theta) / 700; //Needs actual time current_state.robot_state = static_cast<ROBOT_STATE>(chosen_action); // save encoder data to encoderData.txt output file encoderOutput << current_state.theta << std::endl; // call updateQ function with state space, previous and current states // and learning rate, discount factor updateQ(space, chosen_action, old_state, current_state, alpha, gamma); // set old_state to current_state old_state = current_state; // after 100 iterations, start slowly increasing epsilon to // reduce stochasticity of action learning if (i > 100) { epsilon += 0.005; } // determine chosen_action for current state if (useEpsilonGreedy) chosen_action = selectAction_EpsilonGreedy(space[current_state], epsilon); else chosen_action = selectAction_BoltzmannFactor(space[current_state], i); // depending upon chosen action, call robot movement tools proxy with either // swingForwards or swingBackwards commands. (chosen_action) ? movementToolsProxy.callVoid("swingForwards") : movementToolsProxy.callVoid("swingBackwards"); } // create output file for sending final contents of StateSpace object to, allowing // use of previously acquired learning runs to use for future learning runs std::ofstream serializedStateSpace(serializedSpacePath); serializedStateSpace<<space; serializedStateSpace.close(); encoderOutput.close(); return 1; } double probabilityFluxDensityCoefficient(unsigned long t) { return 100.0*std::exp((-8.0*t*t) / (2600.0*2600.0)) + 0.1;//0.1 is an offset } int selectAction_BoltzmannFactor(const PriorityQueue<int, double>& a_queue, unsigned long iterations) { typedef std::vector<std::pair<int, double> > VecPair ; //turn priority queue into a vector of pairs VecPair vec = a_queue.saveOrderedQueueAsVector(); //sum for partition function double sum = 0.0; // calculate partition function by iterating over action-values for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) { sum += std::exp((iter->second) / probabilityFluxDensityCoefficient(iterations)); } // compute Boltzmann factors for action-values and enqueue to vec for (VecPair::iterator iter = vec.begin(); iter < vec.end(); ++iter) { iter->second = std::exp(iter->second / probabilityFluxDensityCoefficient(iterations)) / sum; } // calculate cumulative probability distribution for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) { //second member of pair becomes addition of its current value //and that of the index before it if (iter != vec.begin()) iter->second += (iter-1)->second; } //generate RN between 0 and 1 double rand_num = static_cast<double>(rand()) / RAND_MAX; // choose action based on random number relation to priorities within action queue for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) { if (rand_num < iter->second) return iter->first; } return -1; //note that this line should never be reached } int selectAction_EpsilonGreedy(const PriorityQueue<int, double>& a_queue, double epsilon) { // generate random number between 0 and 1 double rand_num = static_cast<double>(rand()) / RAND_MAX; // if random double is less than epsilon, take action of front element of queue // i.e. the action with current highest utility value if(rand_num < epsilon){ return a_queue.peekFront().first; } // else generate another random double and use this to access a random // element in the queue to take action from rand_num = static_cast<double>(rand()) / RAND_MAX; return a_queue[ round( rand_num*(a_queue.getSize()-1) ) ].first; } void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma) { //oldQ value reference double oldQ = space[old_state].search(action).second; //reward given to current state double R = new_state.getReward(); //optimal Q value for new state i.e. first element double maxQ = space[new_state].peekFront().second; //new Q value determined by Q learning algorithm double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ); // change priority of action to new Q value space[old_state].changePriority(action, newQ); } <commit_msg>Cleaned up main file<commit_after>/** * @file main.cpp * * @brief File containing main Q-Learning algorithm and all necessary associated functions to implementing this routine. * * @author Machine Learning Team 2015-2016 * @date March, 2016 */ // Uncomment for use with Visual Studio C++ Compiler //#define _USE_MATH_DEFINES #include <cmath> #include <cstdlib> #include <ctime> #include <string> #include <sstream> #include <fstream> #include "StateSpace.h" #include "PriorityQueue.h" #include "State.h" #include "encoder.h" #include "CreateModule.h" /** * @brief Gives a std::string representation of a primitive type. * * @remark Can be used to print priority queue contents. * @param x Primitive type such as int, double, long ... * @return std::string conversion of param x */ template<typename T> std::string to_string(T x) { return static_cast<std::ostringstream&>((std::ostringstream() << std::dec << x)).str(); } /** * @brief Determines whether a file exists / is accessible * * @param filename File to check for * @return true if file exists, false if not or is inaccessible */ bool fileExists(const char* filename) { std::ifstream file(filename); return file.good(); } /** * @brief Analog to temperature variable in Boltzmann Distribution, computes 'evolution variable' of system. * * This function computes a normal distribution over the parameterised number of loop iterations in order * to provide a function which explores the state space dilligently initially which then decays off to the * optimal solution after a large number of loop iterations. * * The normal distribution used by this function is: * * \f[ a e^{-\frac{bt^2}{c}} + \epsilon \f] * * where a, b and c are scaling coefficients (see method body) and \f$\epsilon\f$ is some small offset. * * @param t Number of loop iterations. * @return Value of normal distribution at t loop iterations. */ double probabilityFluxDensityCoefficient(unsigned long t); /** * @brief Selects an action to perform based on a stochastic factor, epsilon, and past experiences * * @param a_queue A priority queue instance storing integral types with double type priorities, * represents the queue of possible actions with pre-initialised priority levels. * @param epsilon Fraction determining randomness of greedy search, 0.0 = completely random. * @return integer corresponding to chosen action */ int selectAction_EpsilonGreedy(const PriorityQueue<int, double>& a_queue, double epsilon); /** * @brief Selects an action to perform based on experience, iterations and probabilities. * * @param a_queue A priority queue instance storing integral types with double type priorities, * represents the queue of possible actions with pre-initialised priority levels. * @param iterations Number of iterations completed * @return integer corresponding to chosen action */ int selectAction_BoltzmannFactor(const PriorityQueue<int, double>& a_queue, unsigned long iterations); /** * @brief Updates the utility (Q-value) of the system. * * Utility (Q-Value) of the system is updated via the Temporal Difference Learning Rule given by the following equation, * * \f[ Q_{i+1} (s,a) = Q_i (s,a) + \alpha [R(s') + \gamma \underset{a}{max} Q(s',a) - Q_i (s,a)] \f] * * where Q represents the utility of a state-action pair, \f$ \alpha \f$ is the learning rate, \f$ \gamma \f$ is the discount * factor and \f$ max_a (Q) \f$ yields the action-maximum of the Q space. The learning rate should be set to a low value for * highly stochastic, asymmetric systems or a high value for a lowly stochastic, symmetric system - this value lies between 0 and 1. * The discount factor (also in the interval [0,1]) represents the time considerations of the learning algorithm, lower values indicate * "living in the moment", whilst higher values indicate "planning for the future". * * @param space Reference to StateSpace object * @param action Integer code to previous performed action * @param new_state Reference to State instance giving the new system state * @param old_state Reference to State instance giving the old system state * @param alpha Learning rate of temporal difference learning algorithm (in the interval [0,1]) * @param gamma Discount factor applied to q-learning equation (in the interval [0,1]) */ void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma); /** * @brief Performs all proxy initialisation through NAO SDK functions and structures, setting up a connection * to the robot and allowing use of movement tools and body info libraries. * * @return A vector of size 3 where the first element contains the body info proxy (type AL::ALProxy), the second * element contains the movement tools proxy (type AL::ALProxy) and the third element contains the motion * proxy (type AL::ALMotionProxy). */ std::vector<AL::ALProxy> robotProxyInitialisation() { // Libraries to load std::string bodyLibName = "bodyinfo"; std::string movementLibName = "movementtools"; // Name of camera module in library std::string bodyModuleName = "BodyInfo"; std::string movementModuleName = "MovementTools"; // Set broker name, ip and port, finding first available port from 54000 const std::string brokerName = "MotionTimingBroker"; int brokerPort = qi::os::findAvailablePort(54000); const std::string brokerIp = "0.0.0.0"; // Default parent port and ip int pport = 9559; std::string pip = "127.0.0.1"; // Need this for SOAP serialisation of floats to work setlocale(LC_NUMERIC, "C"); // Create a broker boost::shared_ptr<AL::ALBroker> broker; try { broker = AL::ALBroker::createBroker( brokerName, brokerIp, brokerPort, pip, pport, 0); } // Throw error and quit if a broker could not be created catch (...) { std::cerr << "Failed to connect broker to: " << pip << ":" << pport << std::endl; AL::ALBrokerManager::getInstance()->killAllBroker(); AL::ALBrokerManager::kill(); return 1; } // Add the broker to NAOqi AL::ALBrokerManager::setInstance(broker->fBrokerManager.lock()); AL::ALBrokerManager::getInstance()->addBroker(broker); CreateModule(movementLibName, movementModuleName, broker, false, true); CreateModule(bodyLibName, bodyModuleName, broker, false, true); std::vector<AL::ALProxy> proxyVec; // initialise proxies AL::ALProxy bodyInfoProxy(bodyModuleName, pip, pport); AL::ALProxy movementToolsProxy(movementModuleName, pip, pport); AL::ALMotionProxy motion(pip, pport); proxyVec.push_back(bodyInfoProxy); proxyVec.push_back(movementToolsProxy); proxyVec.push_back(motion); return proxyVec; } /** * @brief Program launcher! * * Contains all initialisations including setting up the StateSpace and connecting to robot via a proxy. Holds main * program loop to perform algorithm continuously using calls to selectAction and updateQ sequentially to update * utilities and choose most optimal actions to perform based on position and velocity. * * @return Program exit code */ int main() { // initialise proxies and robot connection and set movementToolsProxy object to 2nd // element of robotProxyInitialisation return vector AL::ALProxy movementToolsProxy = robotProxyInitialisation()[1]; // Learning rate - set low for highly stochastic systems, high for less random and more symmetric systems const double alpha = 0.8; // Discount factor - set low for disregarding future events, high for taking the future into more consideration const double gamma = 0.5; // Seed PRNG with current system time std::srand(static_cast<unsigned int>(std::time(NULL))); // possible actions, initialise starting action to full forwards motion int action_forwards = FORWARD; int action_backwards = BACKWARD; int chosen_action = action_forwards; // create a priority queue to copy to all the state space priority queues PriorityQueue<int, double> initiator_queue(MAX); // enqueue possible actions with intial zero utilities to initiator_queue initiator_queue.enqueueWithPriority(action_forwards, 0); initiator_queue.enqueueWithPriority(action_backwards, 0); // create encoder and calibrate to current angle Encoder encoder; encoder.Calibrate(); std::cout << "Encoder angle calibrated... " << std::endl; //pause briefly to allow the robot to be given a push if desired qi::os::msleep(5000); //create the state space, initialised with number of bins for angle and velocity // and maximum angle and velocities for discretisation limits (alter if necessary) const int angleBins = 100; const int velocityBins = 50; const double angleMax = 0.25*M_PI; const double velocityMax = 1.0; StateSpace space(angleBins, velocityBins, angleMax, velocityMax, initiator_queue); const char* serializedSpacePath = "serializedStateSpaceData.txt"; // create output file to send encoder data to const char* encoderDataPath = "encoderData.txt"; std::ofstream encoderOutput(encoderDataPath); // if file containing previous state space data exists // get handle to this file and stream contents to space object if (fileExists(serializedSpacePath)) { std::ifstream inputFile(serializedSpacePath); std::string firstFileLine; std::getline(inputFile, firstFileLine); // if file is not empty, save file data to state space object if (!firstFileLine.empty()) inputFile >> space; } // Create State objects for current state and previous state State current_state(0.0, 0.0, FORWARD); State old_state(0.0, 0.0, FORWARD); // initialise epsilon parameter for greedy search to 0.0 (fully stochastic) double epsilon = 0.0; std::cout << "Initialisation complete!" << std::endl; bool useEpsilonGreedy = true; // Each iteration currently requires 700ms time for action performing // => increase maxIterations for longer learning times const unsigned long maxIterations = 500UL; for(unsigned long i = 0; i < maxIterations; ++i) { // set current state angle to angle received from encoder // and set current state velocity to difference in new and // old state angles over some time difference current_state.theta = M_PI * (encoder.GetAngle()) / 180; current_state.theta_dot = (current_state.theta - old_state.theta) / 700; //Needs actual time current_state.robot_state = static_cast<ROBOT_STATE>(chosen_action); // save encoder data to encoderData.txt output file encoderOutput << current_state.theta << std::endl; // call updateQ function with state space, previous and current states // and learning rate, discount factor updateQ(space, chosen_action, old_state, current_state, alpha, gamma); // set old_state to current_state old_state = current_state; // after 100 iterations, start slowly increasing epsilon to // reduce stochasticity of action learning if (i > 100) { epsilon += 0.005; } // determine chosen_action for current state if (useEpsilonGreedy) chosen_action = selectAction_EpsilonGreedy(space[current_state], epsilon); else chosen_action = selectAction_BoltzmannFactor(space[current_state], i); // depending upon chosen action, call robot movement tools proxy with either // swingForwards or swingBackwards commands. (chosen_action) ? movementToolsProxy.callVoid("swingForwards") : movementToolsProxy.callVoid("swingBackwards"); } // create output file for sending final contents of StateSpace object to, allowing // use of previously acquired learning runs to use for future learning runs std::ofstream serializedStateSpace(serializedSpacePath); serializedStateSpace<<space; serializedStateSpace.close(); encoderOutput.close(); return 1; } double probabilityFluxDensityCoefficient(unsigned long t) { return 100.0*std::exp((-8.0*t*t) / (2600.0*2600.0)) + 0.1;//0.1 is an offset } int selectAction_BoltzmannFactor(const PriorityQueue<int, double>& a_queue, unsigned long iterations) { typedef std::vector<std::pair<int, double> > VecPair ; //turn priority queue into a vector of pairs VecPair vec = a_queue.saveOrderedQueueAsVector(); //sum for partition function double sum = 0.0; // calculate partition function by iterating over action-values for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) { sum += std::exp((iter->second) / probabilityFluxDensityCoefficient(iterations)); } // compute Boltzmann factors for action-values and enqueue to vec for (VecPair::iterator iter = vec.begin(); iter < vec.end(); ++iter) { iter->second = std::exp(iter->second / probabilityFluxDensityCoefficient(iterations)) / sum; } // calculate cumulative probability distribution for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) { //second member of pair becomes addition of its current value //and that of the index before it if (iter != vec.begin()) iter->second += (iter-1)->second; } //generate RN between 0 and 1 double rand_num = static_cast<double>(rand()) / RAND_MAX; // choose action based on random number relation to priorities within action queue for (VecPair::iterator iter = vec.begin(), end = vec.end(); iter < end; ++iter) { if (rand_num < iter->second) return iter->first; } return -1; //note that this line should never be reached } int selectAction_EpsilonGreedy(const PriorityQueue<int, double>& a_queue, double epsilon) { // generate random number between 0 and 1 double rand_num = static_cast<double>(rand()) / RAND_MAX; // if random double is less than epsilon, take action of front element of queue // i.e. the action with current highest utility value if(rand_num < epsilon){ return a_queue.peekFront().first; } // else generate another random double and use this to access a random // element in the queue to take action from rand_num = static_cast<double>(rand()) / RAND_MAX; return a_queue[ round( rand_num*(a_queue.getSize()-1) ) ].first; } void updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma) { //oldQ value reference double oldQ = space[old_state].search(action).second; //reward given to current state double R = new_state.getReward(); //optimal Q value for new state i.e. first element double maxQ = space[new_state].peekFront().second; //new Q value determined by Q learning algorithm double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ); // change priority of action to new Q value space[old_state].changePriority(action, newQ); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: desktopcontext.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2004-05-10 13:00:40 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _DESKTOP_DESKTOPCONTEXT_HXX_ #include "desktopcontext.hxx" #endif #include <vcl/svapp.hxx> #include <javainteractionhandler.hxx> using namespace rtl; using namespace com::sun::star::uno; using namespace com::sun::star::task; namespace desktop { DesktopContext::DesktopContext( const Reference< XCurrentContext > & ctx ) : m_xNextContext( ctx ) { } Any SAL_CALL DesktopContext::getValueByName( const OUString& Name) throw (RuntimeException) { Any retVal; if ( 0 == Name.compareToAscii( DESKTOP_ENVIRONMENT_NAME ) ) { retVal = makeAny( Application::GetDesktopEnvironment() ); } else if ( 0 == Name.compareToAscii( JAVA_INTERACTION_HANDLER_NAME )) { retVal = makeAny( Reference< XInteractionHandler >( new JavaInteractionHandler()) ); } else if( m_xNextContext.is() ) { // Call next context in chain if found retVal = m_xNextContext->getValueByName( Name ); } return retVal; } } <commit_msg>INTEGRATION: CWS jl22 (1.2.272); FILE MERGED 2005/06/22 14:58:45 jl 1.2.272.1: #i37020<commit_after>/************************************************************************* * * $RCSfile: desktopcontext.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2005-07-07 13:20:21 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _DESKTOP_DESKTOPCONTEXT_HXX_ #include "desktopcontext.hxx" #endif #include <vcl/svapp.hxx> #include <svtools/javainteractionhandler.hxx> using namespace rtl; using namespace com::sun::star::uno; using namespace com::sun::star::task; namespace desktop { DesktopContext::DesktopContext( const Reference< XCurrentContext > & ctx ) : m_xNextContext( ctx ) { } Any SAL_CALL DesktopContext::getValueByName( const OUString& Name) throw (RuntimeException) { Any retVal; if ( 0 == Name.compareToAscii( DESKTOP_ENVIRONMENT_NAME ) ) { retVal = makeAny( Application::GetDesktopEnvironment() ); } else if ( 0 == Name.compareToAscii( JAVA_INTERACTION_HANDLER_NAME )) { retVal = makeAny( Reference< XInteractionHandler >( new svt::JavaInteractionHandler()) ); } else if( m_xNextContext.is() ) { // Call next context in chain if found retVal = m_xNextContext->getValueByName( Name ); } return retVal; } } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "svl/sharedstring.hxx" namespace svl { SharedString SharedString::getEmptyString() { // unicode string array for empty string is globally shared in OUString. // Let's take advantage of that. rtl_uString* pData = NULL; rtl_uString_new(&pData); return SharedString(pData, pData); } SharedString::SharedString() : mpData(NULL), mpDataIgnoreCase(NULL) {} SharedString::SharedString( rtl_uString* pData, rtl_uString* pDataIgnoreCase ) : mpData(pData), mpDataIgnoreCase(pDataIgnoreCase) { if (mpData) rtl_uString_acquire(mpData); if (mpDataIgnoreCase) rtl_uString_acquire(mpDataIgnoreCase); } SharedString::SharedString( const OUString& rStr ) : mpData(rStr.pData), mpDataIgnoreCase(NULL) { rtl_uString_acquire(mpData); } SharedString::SharedString( const SharedString& r ) : mpData(r.mpData), mpDataIgnoreCase(r.mpDataIgnoreCase) { if (mpData) rtl_uString_acquire(mpData); if (mpDataIgnoreCase) rtl_uString_acquire(mpDataIgnoreCase); } SharedString::~SharedString() { if (mpData) rtl_uString_release(mpData); if (mpDataIgnoreCase) rtl_uString_release(mpDataIgnoreCase); } SharedString& SharedString::operator= ( const SharedString& r ) { if (mpData) rtl_uString_release(mpData); if (mpDataIgnoreCase) rtl_uString_release(mpDataIgnoreCase); mpData = r.mpData; mpDataIgnoreCase = r.mpDataIgnoreCase; if (mpData) rtl_uString_acquire(mpData); if (mpDataIgnoreCase) rtl_uString_acquire(mpDataIgnoreCase); return *this; } bool SharedString::operator== ( const SharedString& r ) const { // Only compare case sensitive strings. if (mpData) { if (!r.mpData) return false; if (mpData->length != r.mpData->length) return false; return rtl_ustr_reverseCompare_WithLength(mpData->buffer, mpData->length, r.mpData->buffer, r.mpData->length) == 0; } return !r.mpData; } bool SharedString::operator!= ( const SharedString& r ) const { return !operator== (r); } OUString SharedString::getString() const { return mpData ? OUString(mpData) : OUString(); } rtl_uString* SharedString::getData() { return mpData; } const rtl_uString* SharedString::getData() const { return mpData; } rtl_uString* SharedString::getDataIgnoreCase() { return mpDataIgnoreCase; } const rtl_uString* SharedString::getDataIgnoreCase() const { return mpDataIgnoreCase; } bool SharedString::isValid() const { return mpData != NULL; } bool SharedString::isEmpty() const { return mpData == NULL || mpData->length == 0; } sal_Int32 SharedString::getLength() const { return mpData ? mpData->length : 0; } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Compare by pointers first.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "svl/sharedstring.hxx" namespace svl { SharedString SharedString::getEmptyString() { // unicode string array for empty string is globally shared in OUString. // Let's take advantage of that. rtl_uString* pData = NULL; rtl_uString_new(&pData); return SharedString(pData, pData); } SharedString::SharedString() : mpData(NULL), mpDataIgnoreCase(NULL) {} SharedString::SharedString( rtl_uString* pData, rtl_uString* pDataIgnoreCase ) : mpData(pData), mpDataIgnoreCase(pDataIgnoreCase) { if (mpData) rtl_uString_acquire(mpData); if (mpDataIgnoreCase) rtl_uString_acquire(mpDataIgnoreCase); } SharedString::SharedString( const OUString& rStr ) : mpData(rStr.pData), mpDataIgnoreCase(NULL) { rtl_uString_acquire(mpData); } SharedString::SharedString( const SharedString& r ) : mpData(r.mpData), mpDataIgnoreCase(r.mpDataIgnoreCase) { if (mpData) rtl_uString_acquire(mpData); if (mpDataIgnoreCase) rtl_uString_acquire(mpDataIgnoreCase); } SharedString::~SharedString() { if (mpData) rtl_uString_release(mpData); if (mpDataIgnoreCase) rtl_uString_release(mpDataIgnoreCase); } SharedString& SharedString::operator= ( const SharedString& r ) { if (mpData) rtl_uString_release(mpData); if (mpDataIgnoreCase) rtl_uString_release(mpDataIgnoreCase); mpData = r.mpData; mpDataIgnoreCase = r.mpDataIgnoreCase; if (mpData) rtl_uString_acquire(mpData); if (mpDataIgnoreCase) rtl_uString_acquire(mpDataIgnoreCase); return *this; } bool SharedString::operator== ( const SharedString& r ) const { // Only compare case sensitive strings. if (mpData == r.mpData) return true; if (mpData) { if (!r.mpData) return false; if (mpData->length != r.mpData->length) return false; return rtl_ustr_reverseCompare_WithLength(mpData->buffer, mpData->length, r.mpData->buffer, r.mpData->length) == 0; } return !r.mpData; } bool SharedString::operator!= ( const SharedString& r ) const { return !operator== (r); } OUString SharedString::getString() const { return mpData ? OUString(mpData) : OUString(); } rtl_uString* SharedString::getData() { return mpData; } const rtl_uString* SharedString::getData() const { return mpData; } rtl_uString* SharedString::getDataIgnoreCase() { return mpDataIgnoreCase; } const rtl_uString* SharedString::getDataIgnoreCase() const { return mpDataIgnoreCase; } bool SharedString::isValid() const { return mpData != NULL; } bool SharedString::isEmpty() const { return mpData == NULL || mpData->length == 0; } sal_Int32 SharedString::getLength() const { return mpData ? mpData->length : 0; } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include "PlayState.h" #include "Level.h" #include "Renderer.h" #include "Platform.h" #include "Player.h" #include "Object.h" PlayState::PlayState() { mTestBkgd = nullptr; mPlayer = nullptr; } PlayState::~PlayState() { } void PlayState::init() { <<<<<<< HEAD mLevel = new Level("Maptest.txt"); /* mLevel->addObject(new Platform(Vec2(100, 600), 100, 100, "../imgs/platforms/platform.jpg")); mLevel->addObject(new Platform(Vec2(400, 500), 200, 100, "../imgs/platforms/platform.jpg")); mLevel->addObject(new Platform(Vec2(900, 620), 100, 200, "../imgs/platforms/platform.jpg")); mPlayer = mLevel->addPlayer(500, 400); */ ======= mLevel = new Level("test.txt"); mPlayer = mLevel->addPlayer(500, 400); mLevel->addObject(new Platform(Vec2(100, 600), 100, 100, "../imgs/platforms/platform.jpg")); mLevel->addObject(new Platform(Vec2(400, 500), 200, 100, "../imgs/platforms/platform.jpg")); mLevel->addObject(new Platform(Vec2(900, 620), 100, 200, "../imgs/platforms/platform.jpg")); >>>>>>> 84a33f16e53443eabccaf402969a899fae5745e4 } void PlayState::cleanup() { delete mLevel; } void PlayState::update(float dt) { mLevel->update(dt); } void PlayState::draw(Renderer* renderer) { // draw test bkgd if(mTestBkgd != nullptr) renderer->drawTexture(Vec2(0, 0), 1024, 768, mTestBkgd); else mTestBkgd = renderer->loadTexture("../imgs/backgrounds/skygrad.jpg"); mLevel->draw(renderer); } void PlayState::handleEvent(SDL_Event e) { //If a key was pressed if( e.type == SDL_KEYDOWN && e.key.repeat == 0 ) { //Adjust the velocity switch( e.key.keysym.sym ) { case SDLK_UP: mPlayer->addVel(0, -speed); break; case SDLK_DOWN: mPlayer->addVel(0, +speed); break; case SDLK_LEFT: mPlayer->addVel(-speed, 0); break; case SDLK_RIGHT: mPlayer->addVel(+speed, 0); break; } } //If a key was released else if( e.type == SDL_KEYUP && e.key.repeat == 0 ) { //Adjust the velocity switch( e.key.keysym.sym ) { case SDLK_UP: mPlayer->addVel(0, +speed); break; case SDLK_DOWN: mPlayer->addVel(0, -speed); break; case SDLK_LEFT: mPlayer->addVel(+speed, 0); break; case SDLK_RIGHT: mPlayer->addVel(-speed, 0); break; } } } <commit_msg>fixat merge<commit_after>#include "PlayState.h" #include "Level.h" #include "Renderer.h" #include "Platform.h" #include "Player.h" #include "Object.h" PlayState::PlayState() { mTestBkgd = nullptr; mPlayer = nullptr; } PlayState::~PlayState() { } void PlayState::init() { mLevel = new Level("Maptest.txt"); } void PlayState::cleanup() { delete mLevel; } void PlayState::update(float dt) { mLevel->update(dt); } void PlayState::draw(Renderer* renderer) { // draw test bkgd if(mTestBkgd != nullptr) renderer->drawTexture(Vec2(0, 0), 1024, 768, mTestBkgd); else mTestBkgd = renderer->loadTexture("../imgs/backgrounds/skygrad.jpg"); mLevel->draw(renderer); } void PlayState::handleEvent(SDL_Event e) { //If a key was pressed if( e.type == SDL_KEYDOWN && e.key.repeat == 0 ) { //Adjust the velocity switch( e.key.keysym.sym ) { case SDLK_UP: mPlayer->addVel(0, -speed); break; case SDLK_DOWN: mPlayer->addVel(0, +speed); break; case SDLK_LEFT: mPlayer->addVel(-speed, 0); break; case SDLK_RIGHT: mPlayer->addVel(+speed, 0); break; } } //If a key was released else if( e.type == SDL_KEYUP && e.key.repeat == 0 ) { //Adjust the velocity switch( e.key.keysym.sym ) { case SDLK_UP: mPlayer->addVel(0, +speed); break; case SDLK_DOWN: mPlayer->addVel(0, -speed); break; case SDLK_LEFT: mPlayer->addVel(+speed, 0); break; case SDLK_RIGHT: mPlayer->addVel(-speed, 0); break; } } } <|endoftext|>
<commit_before><commit_msg>revert lunatic commit, restore paste<commit_after><|endoftext|>
<commit_before>// @(#)root/ged:$Name: $:$Id: TGedFrame.cxx,v 1.21 2007/02/07 09:00:41 antcheva Exp $ // Author: Ilka Antcheva 10/05/04 /************************************************************************* * Copyright (C) 1995-2002, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TGedFrame // // // // Base frame for implementing GUI - a service class. // // // ////////////////////////////////////////////////////////////////////////// #include "TGedFrame.h" #include "TGedEditor.h" #include "TG3DLine.h" #include "TClass.h" #include "TCanvas.h" #include "TGLabel.h" #include "TGToolTip.h" #include "TGCanvas.h" #include "TGScrollBar.h" #include "snprintf.h" ClassImp(TGedFrame) //______________________________________________________________________________ TGedFrame::TGedFrame(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGCompositeFrame(p, width, height, options, back), fInit(kTRUE), fGedEditor(0), fModelClass(0), fLayoutHints(0), fAvoidSignal(kFALSE), fExtraTabs(0), fPriority(50) { // Constructor of the base GUI attribute frame. fName = ""; fGedEditor = TGedEditor::GetFrameCreator(); SetCleanup(kDeepCleanup); } //______________________________________________________________________________ TGedFrame::~TGedFrame() { // Destructor of the base GUI attribute frame. if (fExtraTabs) { TGedSubFrame* sf; TIter next(fExtraTabs); while ((sf = (TGedSubFrame*) next()) != 0) { delete sf->fFrame; fExtraTabs->Remove(sf); delete sf; } delete fExtraTabs; } delete fLayoutHints; // Destructor of TGCompositeFrame will do the rest. } //______________________________________________________________________________ void TGedFrame::Update() { // Update the current pad when an attribute is changed via GUI. fGedEditor->Update(this); } //______________________________________________________________________________ Option_t *TGedFrame::GetDrawOption() const { // Get draw options of the selected object. if (!fGedEditor->GetPad()) return ""; TListIter next(fGedEditor->GetPad()->GetListOfPrimitives()); TObject *obj; while ((obj = next())) { if (obj == fGedEditor->GetModel()) return next.GetOption(); } return ""; } //______________________________________________________________________________ TGLayoutHints* TGedFrame::GetLayoutHints() { // Get layout hints with which is added to TGedEditor frame. if (fLayoutHints == 0){ fLayoutHints = new TGLayoutHints(kLHintsTop | kLHintsExpandX, 2, 2, 2, 2); fLayoutHints->AddReference(); } return fLayoutHints; } //______________________________________________________________________________ void TGedFrame::MakeTitle(const char *title) { // Create attribute frame title. TGCompositeFrame *f1 = new TGCompositeFrame(this, 145, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f1->AddFrame(new TGLabel(f1, title), new TGLayoutHints(kLHintsLeft, 1, 1, 0, 0)); f1->AddFrame(new TGHorizontal3DLine(f1), new TGLayoutHints(kLHintsExpandX, 5, 5, 7, 7)); AddFrame(f1, new TGLayoutHints(kLHintsTop, 0, 0, 2, 0)); } //______________________________________________________________________________ void TGedFrame::AddExtraTab(TGedSubFrame* sf) { // Adds tab container to list of extra tabs. if (fExtraTabs == 0) fExtraTabs = new TList(); fExtraTabs->Add(sf); sf->fFrame->SetCleanup(kDeepCleanup); } //______________________________________________________________________________ TGVerticalFrame* TGedFrame::CreateEditorTabSubFrame(const Text_t* name) { // Create a vertical frame to be used by 'owner' in extra tab 'name'. // The new frame is registered into the sub-frame list. TGCompositeFrame* tabcont = fGedEditor->GetEditorTab(name); TGVerticalFrame* newframe = new TGVerticalFrame(tabcont); AddExtraTab(new TGedFrame::TGedSubFrame(TString(name), newframe)); return newframe; } //______________________________________________________________________________ void TGedFrame::Refresh(TObject* model) { // Refresh the GUI info about the object attributes. SetModel(model); } //______________________________________________________________________________ void TGedFrame::SetDrawOption(Option_t *option) { // Set drawing option for object. This option only affects // the drawing style and is stored in the option field of the // TObjOptLink supporting a TPad's primitive list (TList). if (!fGedEditor->GetPad() || !option) return; TListIter next(fGedEditor->GetPad()->GetListOfPrimitives()); delete fGedEditor->GetPad()->FindObject("Tframe"); TObject *obj; while ((obj = next())) { if (obj == fGedEditor->GetModel()) { next.SetOption(option); fGedEditor->GetPad()->Modified(); fGedEditor->GetPad()->Update(); return; } } } //______________________________________________________________________________ void TGedFrame::ActivateBaseClassEditors(TClass* cl) { // Provide list of editors for base-classes. // In this class we return all classed with editors found via recursive // descent into list of base classes. // Override to control which editors are actually shown (see TH2Editor). // printf("%s::FillListOfBaseEditors %s\n", IsA()->GetName(), cl->GetName()); if (cl->GetListOfBases()->IsEmpty() == kFALSE) { fGedEditor->ActivateEditors(cl->GetListOfBases(), kTRUE); } } //______________________________________________________________________________ TGedNameFrame::TGedNameFrame(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGedFrame(p, width, height, options | kVerticalFrame, back) { // Create the frame containing the selected object name. fPriority = 0; f1 = new TGCompositeFrame(this, 145, 10, kHorizontalFrame | kFixedWidth | kOwnBackground); f1->AddFrame(new TGLabel(f1,"Name"), new TGLayoutHints(kLHintsLeft, 1, 1, 0, 0)); f1->AddFrame(new TGHorizontal3DLine(f1), new TGLayoutHints(kLHintsExpandX, 5, 5, 7, 7)); AddFrame(f1, new TGLayoutHints(kLHintsTop)); f2 = new TGCompositeFrame(this, 80, 20, kHorizontalFrame | kFixedWidth); fLabel = new TGLabel(f2, ""); f2->AddFrame(fLabel, new TGLayoutHints(kLHintsLeft, 1, 1, 0, 0)); AddFrame(f2, new TGLayoutHints(kLHintsTop, 1, 1, 0, 0)); // Set red color for the name. Pixel_t color; gClient->GetColorByName("#ff0000", color); fLabel->SetTextColor(color, kFALSE); // create tool tip with delay 300 ms fTip = new TGToolTip(fClient->GetDefaultRoot(), this, "TGedNameFrame", 500); AddInput(kEnterWindowMask | kLeaveWindowMask | kKeyPressMask | kButtonPressMask); } //______________________________________________________________________________ TGedNameFrame::~TGedNameFrame() { // Destructor. fLayoutHints = 0; // will be deleted via deep-cleanup of tab-containers delete fTip; } //______________________________________________________________________________ Bool_t TGedNameFrame::HandleCrossing(Event_t *event) { // Handle mouse crossing event for tooltip. if (event->fType == kEnterNotify) fTip->Reset(); else fTip->Hide(); return kFALSE; } //______________________________________________________________________________ Bool_t TGedNameFrame::HandleButton(Event_t * /*event*/) { // Handle mouse button event. if (fTip) fTip->Hide(); return kFALSE; } //______________________________________________________________________________ void TGedNameFrame::SetModel(TObject* obj) { // Sets text for the label. TString string; if (obj == 0) { fLabel->SetText(new TGString("Object not selected")); return; } string.Append(obj->GetName()); string.Append("::"); string.Append(obj->ClassName()); fLabel->SetText(new TGString(string)); string = Form("Name: '%s'; Title: '%s'; Class: '%s'", obj->GetName(), obj->GetTitle(), obj->ClassName()); fTip->SetText(string); // Resize label-frame to a reasonable width. { TGCanvas *canvas = fGedEditor->GetTGCanvas(); TGVScrollBar *vsb = canvas->GetVScrollbar(); Int_t hscrollw = (vsb && vsb->IsMapped()) ? vsb->GetWidth() : 0; Int_t labwidth = TMath::Min(fLabel->GetDefaultSize().fWidth, canvas->GetWidth() - 10 - hscrollw); f2->SetWidth(TMath::Max(labwidth, 80)); } } <commit_msg>From Matevz: Break tooltip with name, title and class of the object into multiple lines.<commit_after>// @(#)root/ged:$Name: $:$Id: TGedFrame.cxx,v 1.22 2007/05/23 15:43:30 rdm Exp $ // Author: Ilka Antcheva 10/05/04 /************************************************************************* * Copyright (C) 1995-2002, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TGedFrame // // // // Base frame for implementing GUI - a service class. // // // ////////////////////////////////////////////////////////////////////////// #include "TGedFrame.h" #include "TGedEditor.h" #include "TG3DLine.h" #include "TClass.h" #include "TCanvas.h" #include "TGLabel.h" #include "TGToolTip.h" #include "TGCanvas.h" #include "TGScrollBar.h" #include "snprintf.h" ClassImp(TGedFrame) //______________________________________________________________________________ TGedFrame::TGedFrame(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGCompositeFrame(p, width, height, options, back), fInit(kTRUE), fGedEditor(0), fModelClass(0), fLayoutHints(0), fAvoidSignal(kFALSE), fExtraTabs(0), fPriority(50) { // Constructor of the base GUI attribute frame. fName = ""; fGedEditor = TGedEditor::GetFrameCreator(); SetCleanup(kDeepCleanup); } //______________________________________________________________________________ TGedFrame::~TGedFrame() { // Destructor of the base GUI attribute frame. if (fExtraTabs) { TGedSubFrame* sf; TIter next(fExtraTabs); while ((sf = (TGedSubFrame*) next()) != 0) { delete sf->fFrame; fExtraTabs->Remove(sf); delete sf; } delete fExtraTabs; } delete fLayoutHints; // Destructor of TGCompositeFrame will do the rest. } //______________________________________________________________________________ void TGedFrame::Update() { // Update the current pad when an attribute is changed via GUI. fGedEditor->Update(this); } //______________________________________________________________________________ Option_t *TGedFrame::GetDrawOption() const { // Get draw options of the selected object. if (!fGedEditor->GetPad()) return ""; TListIter next(fGedEditor->GetPad()->GetListOfPrimitives()); TObject *obj; while ((obj = next())) { if (obj == fGedEditor->GetModel()) return next.GetOption(); } return ""; } //______________________________________________________________________________ TGLayoutHints* TGedFrame::GetLayoutHints() { // Get layout hints with which is added to TGedEditor frame. if (fLayoutHints == 0){ fLayoutHints = new TGLayoutHints(kLHintsTop | kLHintsExpandX, 2, 2, 2, 2); fLayoutHints->AddReference(); } return fLayoutHints; } //______________________________________________________________________________ void TGedFrame::MakeTitle(const char *title) { // Create attribute frame title. TGCompositeFrame *f1 = new TGCompositeFrame(this, 145, 10, kHorizontalFrame | kFitWidth | kFixedWidth | kOwnBackground); f1->AddFrame(new TGLabel(f1, title), new TGLayoutHints(kLHintsLeft, 1, 1, 0, 0)); f1->AddFrame(new TGHorizontal3DLine(f1), new TGLayoutHints(kLHintsExpandX, 5, 5, 7, 7)); AddFrame(f1, new TGLayoutHints(kLHintsTop, 0, 0, 2, 0)); } //______________________________________________________________________________ void TGedFrame::AddExtraTab(TGedSubFrame* sf) { // Adds tab container to list of extra tabs. if (fExtraTabs == 0) fExtraTabs = new TList(); fExtraTabs->Add(sf); sf->fFrame->SetCleanup(kDeepCleanup); } //______________________________________________________________________________ TGVerticalFrame* TGedFrame::CreateEditorTabSubFrame(const Text_t* name) { // Create a vertical frame to be used by 'owner' in extra tab 'name'. // The new frame is registered into the sub-frame list. TGCompositeFrame* tabcont = fGedEditor->GetEditorTab(name); TGVerticalFrame* newframe = new TGVerticalFrame(tabcont); AddExtraTab(new TGedFrame::TGedSubFrame(TString(name), newframe)); return newframe; } //______________________________________________________________________________ void TGedFrame::Refresh(TObject* model) { // Refresh the GUI info about the object attributes. SetModel(model); } //______________________________________________________________________________ void TGedFrame::SetDrawOption(Option_t *option) { // Set drawing option for object. This option only affects // the drawing style and is stored in the option field of the // TObjOptLink supporting a TPad's primitive list (TList). if (!fGedEditor->GetPad() || !option) return; TListIter next(fGedEditor->GetPad()->GetListOfPrimitives()); delete fGedEditor->GetPad()->FindObject("Tframe"); TObject *obj; while ((obj = next())) { if (obj == fGedEditor->GetModel()) { next.SetOption(option); fGedEditor->GetPad()->Modified(); fGedEditor->GetPad()->Update(); return; } } } //______________________________________________________________________________ void TGedFrame::ActivateBaseClassEditors(TClass* cl) { // Provide list of editors for base-classes. // In this class we return all classed with editors found via recursive // descent into list of base classes. // Override to control which editors are actually shown (see TH2Editor). // printf("%s::FillListOfBaseEditors %s\n", IsA()->GetName(), cl->GetName()); if (cl->GetListOfBases()->IsEmpty() == kFALSE) { fGedEditor->ActivateEditors(cl->GetListOfBases(), kTRUE); } } //______________________________________________________________________________ TGedNameFrame::TGedNameFrame(const TGWindow *p, Int_t width, Int_t height, UInt_t options, Pixel_t back) : TGedFrame(p, width, height, options | kVerticalFrame, back) { // Create the frame containing the selected object name. fPriority = 0; f1 = new TGCompositeFrame(this, 145, 10, kHorizontalFrame | kFixedWidth | kOwnBackground); f1->AddFrame(new TGLabel(f1,"Name"), new TGLayoutHints(kLHintsLeft, 1, 1, 0, 0)); f1->AddFrame(new TGHorizontal3DLine(f1), new TGLayoutHints(kLHintsExpandX, 5, 5, 7, 7)); AddFrame(f1, new TGLayoutHints(kLHintsTop)); f2 = new TGCompositeFrame(this, 80, 20, kHorizontalFrame | kFixedWidth); fLabel = new TGLabel(f2, ""); f2->AddFrame(fLabel, new TGLayoutHints(kLHintsLeft, 1, 1, 0, 0)); AddFrame(f2, new TGLayoutHints(kLHintsTop, 1, 1, 0, 0)); // Set red color for the name. Pixel_t color; gClient->GetColorByName("#ff0000", color); fLabel->SetTextColor(color, kFALSE); // create tool tip with delay 300 ms fTip = new TGToolTip(fClient->GetDefaultRoot(), this, "TGedNameFrame", 500); AddInput(kEnterWindowMask | kLeaveWindowMask | kKeyPressMask | kButtonPressMask); } //______________________________________________________________________________ TGedNameFrame::~TGedNameFrame() { // Destructor. fLayoutHints = 0; // will be deleted via deep-cleanup of tab-containers delete fTip; } //______________________________________________________________________________ Bool_t TGedNameFrame::HandleCrossing(Event_t *event) { // Handle mouse crossing event for tooltip. if (event->fType == kEnterNotify) fTip->Reset(); else fTip->Hide(); return kFALSE; } //______________________________________________________________________________ Bool_t TGedNameFrame::HandleButton(Event_t * /*event*/) { // Handle mouse button event. if (fTip) fTip->Hide(); return kFALSE; } //______________________________________________________________________________ void TGedNameFrame::SetModel(TObject* obj) { // Sets text for the label. TString string; if (obj == 0) { fLabel->SetText(new TGString("Object not selected")); return; } string.Append(obj->GetName()); string.Append("::"); string.Append(obj->ClassName()); fLabel->SetText(new TGString(string)); string = Form("Name: %s\nTitle: %s\nClass: %s", obj->GetName(), obj->GetTitle(), obj->ClassName()); fTip->SetText(string); // Resize label-frame to a reasonable width. { TGCanvas *canvas = fGedEditor->GetTGCanvas(); TGVScrollBar *vsb = canvas->GetVScrollbar(); Int_t hscrollw = (vsb && vsb->IsMapped()) ? vsb->GetWidth() : 0; Int_t labwidth = TMath::Min(fLabel->GetDefaultSize().fWidth, canvas->GetWidth() - 10 - hscrollw); f2->SetWidth(TMath::Max(labwidth, 80)); } } <|endoftext|>
<commit_before>/* Copyright 2014 Andrew Schwartzmeyer * * Source file for derived genetic algorithm class */ #include <algorithm> #include <iostream> #include "genetic_algorithm.hpp" #include "random_generator.hpp" const Individual Genetic::mutate(const Individual & subject) const { // GA mutation sequence using a normal distribution Individual mutant = subject; // non-const copy to mutate int_dist percent(0, 100); normal_dist delta_dist(mean, stddev); // unit Gaussian distribution for delta for (parameter & gene : mutant) // short circuit for problem.chance == 1 if (problem.chance || percent(rg.engine) < int(100 * problem.chance)) mutant.mutate(gene, gene * delta_dist(rg.engine)); const Individual Genetic::mutate(const Individual & subject) const { Individual mutant = subject; // non-const copy to mutate int_dist percent(0, 100); switch(mutation_type) { case 'g': gaussian_mutate(mutant, percent); break; case 'j': jumping_mutate(mutant, percent); break; } // update fitness mutant.fitness = problem.fitness(mutant); return mutant; } const Genetic::population Genetic::selection(const Genetic::population & generation) const { // implements tournament selection, returning desired number of best parents population parents; int_dist population_dist(0, population_size - 1); // closed interval, so (-1) for (int i = 0; i < crossover_size; ++i) { population contestants; // create tournament of random members drawn from generation for (int i = 0; i < tournament_size; ++i) contestants.emplace_back(generation[population_dist(rg.engine)]); // select best member from each tournament parents.emplace_back(*std::max_element(contestants.begin(), contestants.end())); } // return best Individual from a set of contestants return parents; } const Genetic::population Genetic::crossover(const Genetic::population & parents) const { population children = parents; int_dist percent(0, 100); // arithmetic binary crossover if (crossover_size == 2) { real_dist alpha_dist(-0.1, 1.1); for (unsigned long i = 0; i < parents[0].size(); ++i) { parameter alpha = alpha_dist(rg.engine); // recombine each child with crossover_chance probability if (crossover_chance || percent(rg.engine) < int(100 * crossover_chance)) children[0][i] = alpha * parents[0][i] + (1 - alpha) * parents[1][i]; if (crossover_chance || percent(rg.engine) < int(100 * crossover_chance)) children[1][i] = (1 - alpha) * parents[0][i] + alpha * parents[1][i]; } } else { // implement uniform crossover } // update fitnesses for (Individual & child : children) child.fitness = problem.fitness(child); return children; } const Individual Genetic::solve() const { while(true) { // create initial population population generation; for (int i = 0; i < population_size; ++i) generation.emplace_back(problem.potential()); // generations loop for (long i = 0; i < problem.iterations; ++i) { // find generation's best member const Individual best = *std::max_element(generation.begin(), generation.end()); // terminating condition if (best.fitness > problem.goal) return best; // std::cout << best.fitness << '\n'; // selection and mutation stage population offspring; while(offspring.size() != population_size) { // tournament selection of parents const population parents = selection(generation); // crossover const population children = crossover(parents); // add mutated children to offspring for (const Individual child : children) offspring.emplace_back(mutate(child)); } // replace generation with offspring generation.swap(offspring); // elitism replacement of random individuals int_dist population_dist(0, population_size - 1); // closed interval, so (-1) for (int i = 0; i < elitism; ++i) generation[population_dist(rg.engine)] = best; } std::cout << "Exhausted generations!\n"; } } <commit_msg>Abstracting out GA Gaussian mutation sequence<commit_after>/* Copyright 2014 Andrew Schwartzmeyer * * Source file for derived genetic algorithm class */ #include <algorithm> #include <iostream> #include "genetic_algorithm.hpp" #include "random_generator.hpp" void Genetic::gaussian_mutate(Individual & mutant, int_dist & percent) const { // GA mutation sequence using a normal distribution normal_dist delta_dist(mean, stddev); // unit Gaussian distribution for delta for (parameter & gene : mutant) // short circuit for problem.chance == 1 if (problem.chance || percent(rg.engine) < int(100 * problem.chance)) mutant.mutate(gene, gene * delta_dist(rg.engine)); } const Individual Genetic::mutate(const Individual & subject) const { Individual mutant = subject; // non-const copy to mutate int_dist percent(0, 100); switch(mutation_type) { case 'g': gaussian_mutate(mutant, percent); break; case 'j': jumping_mutate(mutant, percent); break; } // update fitness mutant.fitness = problem.fitness(mutant); return mutant; } const Genetic::population Genetic::selection(const Genetic::population & generation) const { // implements tournament selection, returning desired number of best parents population parents; int_dist population_dist(0, population_size - 1); // closed interval, so (-1) for (int i = 0; i < crossover_size; ++i) { population contestants; // create tournament of random members drawn from generation for (int i = 0; i < tournament_size; ++i) contestants.emplace_back(generation[population_dist(rg.engine)]); // select best member from each tournament parents.emplace_back(*std::max_element(contestants.begin(), contestants.end())); } // return best Individual from a set of contestants return parents; } const Genetic::population Genetic::crossover(const Genetic::population & parents) const { population children = parents; int_dist percent(0, 100); // arithmetic binary crossover if (crossover_size == 2) { real_dist alpha_dist(-0.1, 1.1); for (unsigned long i = 0; i < parents[0].size(); ++i) { parameter alpha = alpha_dist(rg.engine); // recombine each child with crossover_chance probability if (crossover_chance || percent(rg.engine) < int(100 * crossover_chance)) children[0][i] = alpha * parents[0][i] + (1 - alpha) * parents[1][i]; if (crossover_chance || percent(rg.engine) < int(100 * crossover_chance)) children[1][i] = (1 - alpha) * parents[0][i] + alpha * parents[1][i]; } } else { // implement uniform crossover } // update fitnesses for (Individual & child : children) child.fitness = problem.fitness(child); return children; } const Individual Genetic::solve() const { while(true) { // create initial population population generation; for (int i = 0; i < population_size; ++i) generation.emplace_back(problem.potential()); // generations loop for (long i = 0; i < problem.iterations; ++i) { // find generation's best member const Individual best = *std::max_element(generation.begin(), generation.end()); // terminating condition if (best.fitness > problem.goal) return best; // std::cout << best.fitness << '\n'; // selection and mutation stage population offspring; while(offspring.size() != population_size) { // tournament selection of parents const population parents = selection(generation); // crossover const population children = crossover(parents); // add mutated children to offspring for (const Individual child : children) offspring.emplace_back(mutate(child)); } // replace generation with offspring generation.swap(offspring); // elitism replacement of random individuals int_dist population_dist(0, population_size - 1); // closed interval, so (-1) for (int i = 0; i < elitism; ++i) generation[population_dist(rg.engine)] = best; } std::cout << "Exhausted generations!\n"; } } <|endoftext|>
<commit_before>void Config() { // ============================= // Root file // ============================= // Create the output file TFile *rootfile = new TFile("galice.root","recreate"); rootfile->SetCompressionLevel(2); // Set External decayer AliDecayer* decayer = new AliDecayerPythia(); decayer->SetForceDecay(kAll); decayer->Init(); gMC->SetExternalDecayer(decayer); // ============================= // Geant4 // ============================= // load Geant4 and AliRoot steer libraries if (!gInterpreter->IsLoaded("g4libs.C")) gROOT->LoadMacro("g4libs.C"); gInterpreter->ProcessLine("g4libs()"); gInterpreter->ProcessLine("steerlibs()"); // Create Geant4 if (!gInterpreter->IsLoaded("g4menu.C")) gROOT->LoadMacro("g4menu.C"); gInterpreter->ProcessLine("CreateGeant4()"); // Physics process control // (in development) gMC ->SetProcess("DCAY",1); gMC ->SetProcess("PAIR",1); gMC ->SetProcess("COMP",1); gMC ->SetProcess("PHOT",1); gMC ->SetProcess("PFIS",0); gMC ->SetProcess("DRAY",0); gMC ->SetProcess("ANNI",1); gMC ->SetProcess("BREM",1); gMC ->SetProcess("MUNU",1); //xx gMC ->SetProcess("CKOV",1); gMC ->SetProcess("HADR",1); //Select pure GEANH (HADR 1) or GEANH/NUCRIN (HADR 3) gMC ->SetProcess("LOSS",2); gMC ->SetProcess("MULS",1); //xx gMC ->SetProcess("RAYL",1); // Energy cuts // (in development) Float_t cut = 1.e-3; // 1MeV cut by default gMC ->SetCut("CUTGAM",cut); gMC ->SetCut("CUTELE",cut); gMC ->SetCut("CUTNEU",cut); gMC ->SetCut("CUTHAD",cut); gMC ->SetCut("CUTMUO",cut); gMC ->SetCut("BCUTE",cut); gMC ->SetCut("BCUTM",cut); gMC ->SetCut("DCUTE",cut); gMC ->SetCut("DCUTM",cut); //xx gMC ->SetCut("PPCUTM",cut); // ============================= // Event generator // ============================= // --- Specify event type to be tracked through the ALICE setup // --- All positions are in cm, angles in degrees, and P and E in GeV int nParticles; if (gSystem->Getenv("CONFIG_NPARTICLES")) nParticles = atoi(gSystem->Getenv("CONFIG_NPARTICLES")); else nParticles = 500; AliGenHIJINGpara *gener = new AliGenHIJINGpara(nParticles); gener->SetMomentumRange(0,999); gener->SetPhiRange(0,360); gener->SetThetaRange(0.,180.); gener->SetOrigin(0,0,0); //vertex position gener->SetSigma(0,0,0); //Sigma in (X,Y,Z) (cm) on IP position gener->Init(); // Activate this line if you want the vertex smearing to happen // track by track //gener->SetVertexSmear(perTrack); // ============================= // Magnetic field // ============================= //?? gAlice->SetField(-999,2); //Specify maximum magnetic field in Tesla (neg. ==> default field) // ============================= // Alice modules // ============================= //Bool_t isSetInteractively = false; Bool_t isSetInteractively = true; if (!isSetInteractively) { // Load modules libraries gInterpreter->ProcessLine("detlibs()"); // Select modules Int_t iABSO=1; Int_t iCASTOR=1; Int_t iDIPO=1; Int_t iFMD=1; Int_t iFRAME=1; Int_t iHALL=1; Int_t iITS=1; Int_t iMAG=1; Int_t iMUON=1; Int_t iPHOS=1; Int_t iPIPE=1; Int_t iPMD=1; Int_t iRICH=1; Int_t iSHIL=1; Int_t iSTART=1; Int_t iTOF=1; Int_t iTPC=1; Int_t iTRD=1; Int_t iZDC=1; // Exclude detectors that do not work with Geant4 iCASTOR=0; // Detectors with temporary problem iZDC=0; // From G3 Config.C // Without any modification //=================== Alice BODY parameters ============================= AliBODY *BODY = new AliBODY("BODY","Alice envelop"); if(iMAG) { //=================== MAG parameters ============================ // --- Start with Magnet since detector layouts may be depending --- // --- on the selected Magnet dimensions --- AliMAG *MAG = new AliMAG("MAG","Magnet"); } if(iABSO) { //=================== ABSO parameters ============================ AliABSO *ABSO = new AliABSOv0("ABSO","Muon Absorber"); } if(iDIPO) { //=================== DIPO parameters ============================ AliDIPO *DIPO = new AliDIPOv2("DIPO","Dipole version 2"); } if(iHALL) { //=================== HALL parameters ============================ AliHALL *HALL = new AliHALL("HALL","Alice Hall"); } if(iFRAME) { //=================== FRAME parameters ============================ AliFRAME *FRAME = new AliFRAMEv1("FRAME","Space Frame"); } if(iSHIL) { //=================== SHIL parameters ============================ AliSHIL *SHIL = new AliSHILv0("SHIL","Shielding"); } if(iPIPE) { //=================== PIPE parameters ============================ AliPIPE *PIPE = new AliPIPEv0("PIPE","Beam Pipe"); } if(iITS) { //=================== ITS parameters ============================ // // As the innermost detector in ALICE, the Inner Tracking System "impacts" on // almost all other detectors. This involves the fact that the ITS geometry // still has several options to be followed in parallel in order to determine // the best set-up which minimizes the induced background. All the geometries // available to date are described in the following. Read carefully the comments // and use the default version (the only one uncommented) unless you are making // comparisons and you know what you are doing. In this case just uncomment the // ITS geometry you want to use and run Aliroot. // // Detailed geometries: // // // //AliITS *ITS = new AliITSv5symm("ITS","Updated ITS TDR detailed version with symmetric services"); // AliITS *ITS = new AliITSv5asymm("ITS","Updates ITS TDR detailed version with asymmetric services"); // //AliITSvPPRasymm *ITS = new AliITSvPPRasymm("ITS","New ITS PPR detailed version with asymmetric services"); //ITS->SetMinorVersion(2); //ITS->SetReadDet(kFALSE); //ITS->SetWriteDet("$ALICE_ROOT/ITS/ITSgeometry_vPPRasymm2.det"); //ITS->SetThicknessDet1(300.); // detector thickness on layer 1 must be in the range [100,300] //ITS->SetThicknessDet2(300.); // detector thickness on layer 2 must be in the range [100,300] //ITS->SetThicknessChip1(300.); // chip thickness on layer 1 must be in the range [150,300] //ITS->SetThicknessChip2(300.); // chip thickness on layer 2 must be in the range [150,300] //ITS->SetRails(1); // 1 --> rails in ; 0 --> rails out //ITS->SetCoolingFluid(1); // 1 --> water ; 0 --> freon // //AliITSvPPRsymm *ITS = new AliITSvPPRsymm("ITS","New ITS PPR detailed version with symmetric services"); //ITS->SetMinorVersion(2); //ITS->SetReadDet(kFALSE); //ITS->SetWriteDet("$ALICE_ROOT/ITS/ITSgeometry_vPPRsymm2.det"); //ITS->SetThicknessDet1(300.); // detector thickness on layer 1 must be in the range [100,300] //ITS->SetThicknessDet2(300.); // detector thickness on layer 2 must be in the range [100,300] //ITS->SetThicknessChip1(300.); // chip thickness on layer 1 must be in the range [150,300] //ITS->SetThicknessChip2(300.); // chip thickness on layer 2 must be in the range [150,300] //ITS->SetRails(1); // 1 --> rails in ; 0 --> rails out //ITS->SetCoolingFluid(1); // 1 --> water ; 0 --> freon // // // Coarse geometries (warning: no hits are produced with these coarse geometries and they unuseful // for reconstruction !): // // // //AliITSvPPRcoarseasymm *ITS = new AliITSvPPRcoarseasymm("ITS","New ITS coarse version with asymmetric services"); //ITS->SetRails(1); // 1 --> rails in ; 0 --> rails out //ITS->SetSupportMaterial(0); // 0 --> Copper ; 1 --> Aluminum ; 2 --> Carbon // //AliITS *ITS = new AliITSvPPRcoarsesymm("ITS","New ITS coarse version with symmetric services"); //ITS->SetRails(1); // 1 --> rails in ; 0 --> rails out //ITS->SetSupportMaterial(0); // 0 --> Copper ; 1 --> Aluminum ; 2 --> Carbon // // // // Geant3 <-> EUCLID conversion // ============================ // // SetEUCLID is a flag to output (=1) or not to output (=0) both geometry and // media to two ASCII files (called by default ITSgeometry.euc and // ITSgeometry.tme) in a format understandable to the CAD system EUCLID. // The default (=0) means that you dont want to use this facility. // ITS->SetEUCLID(0); } if(iTPC) { //============================ TPC parameters ================================ // --- This allows the user to specify sectors for the SLOW (TPC geometry 2) // --- Simulator. SecAL (SecAU) <0 means that ALL lower (upper) // --- sectors are specified, any value other than that requires at least one // --- sector (lower or upper)to be specified! // --- Reminder: sectors 1-24 are lower sectors (1-12 -> z>0, 13-24 -> z<0) // --- sectors 25-72 are the upper ones (25-48 -> z>0, 49-72 -> z<0) // --- SecLows - number of lower sectors specified (up to 6) // --- SecUps - number of upper sectors specified (up to 12) // --- Sens - sensitive strips for the Slow Simulator !!! // --- This does NOT work if all S or L-sectors are specified, i.e. // --- if SecAL or SecAU < 0 // // //----------------------------------------------------------------------------- // gROOT->LoadMacro("SetTPCParam.C"); // AliTPCParam *param = SetTPCParam(); AliTPC *TPC = new AliTPCv2("TPC","Default"); // All sectors included TPC->SetSecAL(-1); TPC->SetSecAU(-1); } if(iTOF) { //=================== TOF parameters ============================ AliTOF *TOF = new AliTOFv2("TOF","normal TOF"); } if(iRICH) { //=================== RICH parameters =========================== AliRICH *RICH = new AliRICHv1("RICH","normal RICH"); } if(iZDC) { //=================== ZDC parameters ============================ AliZDC *ZDC = new AliZDCv1("ZDC","normal ZDC"); } if(iCASTOR) { //=================== CASTOR parameters ============================ AliCASTOR *CASTOR = new AliCASTORv1("CASTOR","normal CASTOR"); } if(iTRD) { //=================== TRD parameters ============================ AliTRD *TRD = new AliTRDv1("TRD","TRD slow simulator"); // Select the gas mixture (0: 97% Xe + 3% isobutane, 1: 90% Xe + 10% CO2) TRD->SetGasMix(1); // With hole in front of PHOS TRD->SetPHOShole(); // With hole in front of RICH TRD->SetRICHhole(); // Switch on TR AliTRDsim *TRDsim = TRD->CreateTR(); } if(iFMD) { //=================== FMD parameters ============================ AliFMD *FMD = new AliFMDv0("FMD","normal FMD"); } if(iMUON) { //=================== MUON parameters =========================== AliMUON *MUON = new AliMUONv1("MUON","default"); } //=================== PHOS parameters =========================== if(iPHOS) { AliPHOS *PHOS = new AliPHOSv1("PHOS","GPS2"); } if(iPMD) { //=================== PMD parameters ============================ AliPMD *PMD = new AliPMDv1("PMD","normal PMD"); PMD->SetPAR(1., 1., 0.8, 0.02); PMD->SetIN(6., 18., -580., 27., 27.); PMD->SetGEO(0.0, 0.2, 4.); PMD->SetPadSize(0.8, 1.0, 1.0, 1.5); } if(iSTART) { //=================== START parameters ============================ AliSTART *START = new AliSTARTv1("START","START Detector"); } } // end (!isSetInteractively) } <commit_msg>added setting PPCUTM, TOFMAX cuts<commit_after>void Config() { // ============================= // Root file // ============================= // Create the output file TFile *rootfile = new TFile("galice.root","recreate"); rootfile->SetCompressionLevel(2); // Set External decayer AliDecayer* decayer = new AliDecayerPythia(); decayer->SetForceDecay(kAll); decayer->Init(); gMC->SetExternalDecayer(decayer); // ============================= // Geant4 // ============================= // load Geant4 and AliRoot steer libraries if (!gInterpreter->IsLoaded("g4libs.C")) gROOT->LoadMacro("g4libs.C"); gInterpreter->ProcessLine("g4libs()"); gInterpreter->ProcessLine("steerlibs()"); // Create Geant4 if (!gInterpreter->IsLoaded("g4menu.C")) gROOT->LoadMacro("g4menu.C"); gInterpreter->ProcessLine("CreateGeant4()"); // Physics process control // (in development) gMC ->SetProcess("DCAY",1); gMC ->SetProcess("PAIR",1); gMC ->SetProcess("COMP",1); gMC ->SetProcess("PHOT",1); gMC ->SetProcess("PFIS",0); gMC ->SetProcess("DRAY",0); gMC ->SetProcess("ANNI",1); gMC ->SetProcess("BREM",1); gMC ->SetProcess("MUNU",1); //xx gMC ->SetProcess("CKOV",1); gMC ->SetProcess("HADR",1); //Select pure GEANH (HADR 1) or GEANH/NUCRIN (HADR 3) gMC ->SetProcess("LOSS",2); gMC ->SetProcess("MULS",1); //xx gMC ->SetProcess("RAYL",1); // Energy cuts // (in development) Float_t cut = 1.e-3; // 1MeV cut by default Float_t tofmax = 1.e10; gMC ->SetCut("CUTGAM",cut); gMC ->SetCut("CUTELE",cut); gMC ->SetCut("CUTNEU",cut); gMC ->SetCut("CUTHAD",cut); gMC ->SetCut("CUTMUO",cut); gMC ->SetCut("BCUTE",cut); gMC ->SetCut("BCUTM",cut); gMC ->SetCut("DCUTE",cut); gMC ->SetCut("DCUTM",cut); gMC ->SetCut("PPCUTM",cut); gMC ->SetCut("TOFMAX",tofmax); // ============================= // Event generator // ============================= // --- Specify event type to be tracked through the ALICE setup // --- All positions are in cm, angles in degrees, and P and E in GeV int nParticles; if (gSystem->Getenv("CONFIG_NPARTICLES")) nParticles = atoi(gSystem->Getenv("CONFIG_NPARTICLES")); else nParticles = 500; AliGenHIJINGpara *gener = new AliGenHIJINGpara(nParticles); gener->SetMomentumRange(0,999); gener->SetPhiRange(0,360); gener->SetThetaRange(0.,180.); gener->SetOrigin(0,0,0); //vertex position gener->SetSigma(0,0,0); //Sigma in (X,Y,Z) (cm) on IP position gener->Init(); // Activate this line if you want the vertex smearing to happen // track by track //gener->SetVertexSmear(perTrack); // ============================= // Magnetic field // ============================= //?? gAlice->SetField(-999,2); //Specify maximum magnetic field in Tesla (neg. ==> default field) // ============================= // Alice modules // ============================= //Bool_t isSetInteractively = false; Bool_t isSetInteractively = true; if (!isSetInteractively) { // Load modules libraries gInterpreter->ProcessLine("detlibs()"); // Select modules Int_t iABSO=1; Int_t iCASTOR=1; Int_t iDIPO=1; Int_t iFMD=1; Int_t iFRAME=1; Int_t iHALL=1; Int_t iITS=1; Int_t iMAG=1; Int_t iMUON=1; Int_t iPHOS=1; Int_t iPIPE=1; Int_t iPMD=1; Int_t iRICH=1; Int_t iSHIL=1; Int_t iSTART=1; Int_t iTOF=1; Int_t iTPC=1; Int_t iTRD=1; Int_t iZDC=1; // Exclude detectors that do not work with Geant4 iCASTOR=0; // Detectors with temporary problem iZDC=0; // From G3 Config.C // Without any modification //=================== Alice BODY parameters ============================= AliBODY *BODY = new AliBODY("BODY","Alice envelop"); if(iMAG) { //=================== MAG parameters ============================ // --- Start with Magnet since detector layouts may be depending --- // --- on the selected Magnet dimensions --- AliMAG *MAG = new AliMAG("MAG","Magnet"); } if(iABSO) { //=================== ABSO parameters ============================ AliABSO *ABSO = new AliABSOv0("ABSO","Muon Absorber"); } if(iDIPO) { //=================== DIPO parameters ============================ AliDIPO *DIPO = new AliDIPOv2("DIPO","Dipole version 2"); } if(iHALL) { //=================== HALL parameters ============================ AliHALL *HALL = new AliHALL("HALL","Alice Hall"); } if(iFRAME) { //=================== FRAME parameters ============================ AliFRAME *FRAME = new AliFRAMEv1("FRAME","Space Frame"); } if(iSHIL) { //=================== SHIL parameters ============================ AliSHIL *SHIL = new AliSHILv0("SHIL","Shielding"); } if(iPIPE) { //=================== PIPE parameters ============================ AliPIPE *PIPE = new AliPIPEv0("PIPE","Beam Pipe"); } if(iITS) { //=================== ITS parameters ============================ // // As the innermost detector in ALICE, the Inner Tracking System "impacts" on // almost all other detectors. This involves the fact that the ITS geometry // still has several options to be followed in parallel in order to determine // the best set-up which minimizes the induced background. All the geometries // available to date are described in the following. Read carefully the comments // and use the default version (the only one uncommented) unless you are making // comparisons and you know what you are doing. In this case just uncomment the // ITS geometry you want to use and run Aliroot. // // Detailed geometries: // // // //AliITS *ITS = new AliITSv5symm("ITS","Updated ITS TDR detailed version with symmetric services"); // AliITS *ITS = new AliITSv5asymm("ITS","Updates ITS TDR detailed version with asymmetric services"); // //AliITSvPPRasymm *ITS = new AliITSvPPRasymm("ITS","New ITS PPR detailed version with asymmetric services"); //ITS->SetMinorVersion(2); //ITS->SetReadDet(kFALSE); //ITS->SetWriteDet("$ALICE_ROOT/ITS/ITSgeometry_vPPRasymm2.det"); //ITS->SetThicknessDet1(300.); // detector thickness on layer 1 must be in the range [100,300] //ITS->SetThicknessDet2(300.); // detector thickness on layer 2 must be in the range [100,300] //ITS->SetThicknessChip1(300.); // chip thickness on layer 1 must be in the range [150,300] //ITS->SetThicknessChip2(300.); // chip thickness on layer 2 must be in the range [150,300] //ITS->SetRails(1); // 1 --> rails in ; 0 --> rails out //ITS->SetCoolingFluid(1); // 1 --> water ; 0 --> freon // //AliITSvPPRsymm *ITS = new AliITSvPPRsymm("ITS","New ITS PPR detailed version with symmetric services"); //ITS->SetMinorVersion(2); //ITS->SetReadDet(kFALSE); //ITS->SetWriteDet("$ALICE_ROOT/ITS/ITSgeometry_vPPRsymm2.det"); //ITS->SetThicknessDet1(300.); // detector thickness on layer 1 must be in the range [100,300] //ITS->SetThicknessDet2(300.); // detector thickness on layer 2 must be in the range [100,300] //ITS->SetThicknessChip1(300.); // chip thickness on layer 1 must be in the range [150,300] //ITS->SetThicknessChip2(300.); // chip thickness on layer 2 must be in the range [150,300] //ITS->SetRails(1); // 1 --> rails in ; 0 --> rails out //ITS->SetCoolingFluid(1); // 1 --> water ; 0 --> freon // // // Coarse geometries (warning: no hits are produced with these coarse geometries and they unuseful // for reconstruction !): // // // //AliITSvPPRcoarseasymm *ITS = new AliITSvPPRcoarseasymm("ITS","New ITS coarse version with asymmetric services"); //ITS->SetRails(1); // 1 --> rails in ; 0 --> rails out //ITS->SetSupportMaterial(0); // 0 --> Copper ; 1 --> Aluminum ; 2 --> Carbon // //AliITS *ITS = new AliITSvPPRcoarsesymm("ITS","New ITS coarse version with symmetric services"); //ITS->SetRails(1); // 1 --> rails in ; 0 --> rails out //ITS->SetSupportMaterial(0); // 0 --> Copper ; 1 --> Aluminum ; 2 --> Carbon // // // // Geant3 <-> EUCLID conversion // ============================ // // SetEUCLID is a flag to output (=1) or not to output (=0) both geometry and // media to two ASCII files (called by default ITSgeometry.euc and // ITSgeometry.tme) in a format understandable to the CAD system EUCLID. // The default (=0) means that you dont want to use this facility. // ITS->SetEUCLID(0); } if(iTPC) { //============================ TPC parameters ================================ // --- This allows the user to specify sectors for the SLOW (TPC geometry 2) // --- Simulator. SecAL (SecAU) <0 means that ALL lower (upper) // --- sectors are specified, any value other than that requires at least one // --- sector (lower or upper)to be specified! // --- Reminder: sectors 1-24 are lower sectors (1-12 -> z>0, 13-24 -> z<0) // --- sectors 25-72 are the upper ones (25-48 -> z>0, 49-72 -> z<0) // --- SecLows - number of lower sectors specified (up to 6) // --- SecUps - number of upper sectors specified (up to 12) // --- Sens - sensitive strips for the Slow Simulator !!! // --- This does NOT work if all S or L-sectors are specified, i.e. // --- if SecAL or SecAU < 0 // // //----------------------------------------------------------------------------- // gROOT->LoadMacro("SetTPCParam.C"); // AliTPCParam *param = SetTPCParam(); AliTPC *TPC = new AliTPCv2("TPC","Default"); // All sectors included TPC->SetSecAL(-1); TPC->SetSecAU(-1); } if(iTOF) { //=================== TOF parameters ============================ AliTOF *TOF = new AliTOFv2("TOF","normal TOF"); } if(iRICH) { //=================== RICH parameters =========================== AliRICH *RICH = new AliRICHv1("RICH","normal RICH"); } if(iZDC) { //=================== ZDC parameters ============================ AliZDC *ZDC = new AliZDCv1("ZDC","normal ZDC"); } if(iCASTOR) { //=================== CASTOR parameters ============================ AliCASTOR *CASTOR = new AliCASTORv1("CASTOR","normal CASTOR"); } if(iTRD) { //=================== TRD parameters ============================ AliTRD *TRD = new AliTRDv1("TRD","TRD slow simulator"); // Select the gas mixture (0: 97% Xe + 3% isobutane, 1: 90% Xe + 10% CO2) TRD->SetGasMix(1); // With hole in front of PHOS TRD->SetPHOShole(); // With hole in front of RICH TRD->SetRICHhole(); // Switch on TR AliTRDsim *TRDsim = TRD->CreateTR(); } if(iFMD) { //=================== FMD parameters ============================ AliFMD *FMD = new AliFMDv0("FMD","normal FMD"); } if(iMUON) { //=================== MUON parameters =========================== AliMUON *MUON = new AliMUONv1("MUON","default"); } //=================== PHOS parameters =========================== if(iPHOS) { AliPHOS *PHOS = new AliPHOSv1("PHOS","GPS2"); } if(iPMD) { //=================== PMD parameters ============================ AliPMD *PMD = new AliPMDv1("PMD","normal PMD"); PMD->SetPAR(1., 1., 0.8, 0.02); PMD->SetIN(6., 18., -580., 27., 27.); PMD->SetGEO(0.0, 0.2, 4.); PMD->SetPadSize(0.8, 1.0, 1.0, 1.5); } if(iSTART) { //=================== START parameters ============================ AliSTART *START = new AliSTARTv1("START","START Detector"); } } // end (!isSetInteractively) } <|endoftext|>
<commit_before>#include "AssetSubCommandLoadAsset.h" #include <maya/MFileObject.h> #include <maya/MGlobal.h> #include <maya/MPlug.h> #include <maya/MPxCommand.h> #include "AssetNode.h" #include "AssetSubCommandSync.h" #include "util.h" AssetSubCommandLoadAsset::AssetSubCommandLoadAsset( const MString &otlFilePath, const MString &assetName ) : myOTLFilePath(otlFilePath), myAssetName(assetName), myAssetSubCommandSync(NULL) { } AssetSubCommandLoadAsset::~AssetSubCommandLoadAsset() { } MStatus AssetSubCommandLoadAsset::doIt() { MStatus status; // create houdiniAsset node MObject assetNode = myDagModifier.createNode(AssetNode::typeId, MObject::kNullObj, &status); CHECK_MSTATUS_AND_RETURN_IT(status); // rename houdiniAsset node { int slashPosition = myAssetName.index('/'); MString nodeName; if(slashPosition >= 0) { const char* tempName = myAssetName.asChar(); // keep the part that's before the node table name // i.e. namespace for(int i = slashPosition; i-- > 0;) { if(!(('A' <= tempName[i] && tempName[i] <= 'Z') || ('a' <= tempName[i] && tempName[i] <= 'z'))) { nodeName += myAssetName.substring(0, i); break; } } // keep everything that's after the slash nodeName += myAssetName.substring( slashPosition + 1, myAssetName.length() - 1 ) + "1"; } else { // this is probably an invalid node type name nodeName = myAssetName; } nodeName = Util::sanitizeStringForNodeName(nodeName); status = myDagModifier.renameNode(assetNode, nodeName); CHECK_MSTATUS_AND_RETURN_IT(status); } // set otl file attribute { MPlug plug(assetNode, AssetNode::otlFilePath); status = myDagModifier.newPlugValueString(plug, myOTLFilePath); CHECK_MSTATUS_AND_RETURN_IT(status); } // set asset name attribute { MPlug plug(assetNode, AssetNode::assetName); status = myDagModifier.newPlugValueString(plug, myAssetName); CHECK_MSTATUS_AND_RETURN_IT(status); } // time1.outTime -> houdiniAsset.inTime { MObject srcNode = Util::findNodeByName("time1"); MPlug srcPlug = MFnDependencyNode(srcNode).findPlug("outTime"); MPlug dstPlug(assetNode, AssetNode::inTime); status = myDagModifier.connect(srcPlug, dstPlug); CHECK_MSTATUS_AND_RETURN_IT(status); } // cannot simply call redoIt, because when we use AssetSubCommandSync, we // need to distinguish between doIt and redoIt status = myDagModifier.doIt(); CHECK_MSTATUS_AND_RETURN_IT(status); MFnDependencyNode assetNodeFn(assetNode); // select the node MGlobal::select(assetNode); // set result MPxCommand::setResult(assetNodeFn.name()); // The asset should have been instantiated by now. If we couldn't // instantiate the asset, then don't operate on the asset any further. This // avoids generating repeated errors. { AssetNode* assetNode = dynamic_cast<AssetNode*>(assetNodeFn.userNode()); if(!assetNode->getAsset()) { // If we couldn't instantiate the asset, then an error message // should have displayed already. No need to display error here. return MStatus::kFailure; } } myAssetSubCommandSync = new AssetSubCommandSync(assetNode); myAssetSubCommandSync->doIt(); return MStatus::kSuccess; } MStatus AssetSubCommandLoadAsset::redoIt() { MStatus status; status = myDagModifier.doIt(); CHECK_MSTATUS_AND_RETURN_IT(status); status = myAssetSubCommandSync->redoIt(); CHECK_MSTATUS_AND_RETURN_IT(status); return MStatus::kSuccess; } MStatus AssetSubCommandLoadAsset::undoIt() { MStatus status; status = myAssetSubCommandSync->undoIt(); CHECK_MSTATUS_AND_RETURN_IT(status); status = myDagModifier.undoIt(); CHECK_MSTATUS_AND_RETURN_IT(status); return MStatus::kSuccess; } bool AssetSubCommandLoadAsset::isUndoable() const { return true; } <commit_msg>"houdiniAsset -loadAsset" should call setResult() at the end<commit_after>#include "AssetSubCommandLoadAsset.h" #include <maya/MFileObject.h> #include <maya/MGlobal.h> #include <maya/MPlug.h> #include <maya/MPxCommand.h> #include "AssetNode.h" #include "AssetSubCommandSync.h" #include "util.h" AssetSubCommandLoadAsset::AssetSubCommandLoadAsset( const MString &otlFilePath, const MString &assetName ) : myOTLFilePath(otlFilePath), myAssetName(assetName), myAssetSubCommandSync(NULL) { } AssetSubCommandLoadAsset::~AssetSubCommandLoadAsset() { } MStatus AssetSubCommandLoadAsset::doIt() { MStatus status; // create houdiniAsset node MObject assetNode = myDagModifier.createNode(AssetNode::typeId, MObject::kNullObj, &status); CHECK_MSTATUS_AND_RETURN_IT(status); // rename houdiniAsset node { int slashPosition = myAssetName.index('/'); MString nodeName; if(slashPosition >= 0) { const char* tempName = myAssetName.asChar(); // keep the part that's before the node table name // i.e. namespace for(int i = slashPosition; i-- > 0;) { if(!(('A' <= tempName[i] && tempName[i] <= 'Z') || ('a' <= tempName[i] && tempName[i] <= 'z'))) { nodeName += myAssetName.substring(0, i); break; } } // keep everything that's after the slash nodeName += myAssetName.substring( slashPosition + 1, myAssetName.length() - 1 ) + "1"; } else { // this is probably an invalid node type name nodeName = myAssetName; } nodeName = Util::sanitizeStringForNodeName(nodeName); status = myDagModifier.renameNode(assetNode, nodeName); CHECK_MSTATUS_AND_RETURN_IT(status); } // set otl file attribute { MPlug plug(assetNode, AssetNode::otlFilePath); status = myDagModifier.newPlugValueString(plug, myOTLFilePath); CHECK_MSTATUS_AND_RETURN_IT(status); } // set asset name attribute { MPlug plug(assetNode, AssetNode::assetName); status = myDagModifier.newPlugValueString(plug, myAssetName); CHECK_MSTATUS_AND_RETURN_IT(status); } // time1.outTime -> houdiniAsset.inTime { MObject srcNode = Util::findNodeByName("time1"); MPlug srcPlug = MFnDependencyNode(srcNode).findPlug("outTime"); MPlug dstPlug(assetNode, AssetNode::inTime); status = myDagModifier.connect(srcPlug, dstPlug); CHECK_MSTATUS_AND_RETURN_IT(status); } // cannot simply call redoIt, because when we use AssetSubCommandSync, we // need to distinguish between doIt and redoIt status = myDagModifier.doIt(); CHECK_MSTATUS_AND_RETURN_IT(status); MFnDependencyNode assetNodeFn(assetNode); // The asset should have been instantiated by now. If we couldn't // instantiate the asset, then don't operate on the asset any further. This // avoids generating repeated errors. { AssetNode* assetNode = dynamic_cast<AssetNode*>(assetNodeFn.userNode()); if(!assetNode->getAsset()) { // If we couldn't instantiate the asset, then an error message // should have displayed already. No need to display error here. status = MStatus::kFailure; } } // Only attempt to sync if the node is valid if(!MFAIL(status)) { myAssetSubCommandSync = new AssetSubCommandSync(assetNode); myAssetSubCommandSync->doIt(); } // select the node MGlobal::select(assetNode); // set result MPxCommand::setResult(assetNodeFn.name()); return MStatus::kSuccess; } MStatus AssetSubCommandLoadAsset::redoIt() { MStatus status; status = myDagModifier.doIt(); CHECK_MSTATUS_AND_RETURN_IT(status); status = myAssetSubCommandSync->redoIt(); CHECK_MSTATUS_AND_RETURN_IT(status); return MStatus::kSuccess; } MStatus AssetSubCommandLoadAsset::undoIt() { MStatus status; status = myAssetSubCommandSync->undoIt(); CHECK_MSTATUS_AND_RETURN_IT(status); status = myDagModifier.undoIt(); CHECK_MSTATUS_AND_RETURN_IT(status); return MStatus::kSuccess; } bool AssetSubCommandLoadAsset::isUndoable() const { return true; } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2020 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= // Note: This example currently does not run on GPU since it consumes too much // memory // This should be retested with the new inmemory generator that should help #define ETL_COUNTERS #define ETL_GPU_POOL #include "dll/rbm/conv_rbm.hpp" #include "dll/rbm/rbm.hpp" #include "dll/network.hpp" #include "dll/datasets.hpp" int main(int /*argc*/, char* /*argv*/ []) { // Load the dataset auto ae_dataset = dll::make_mnist_ae_dataset(dll::batch_size<300>{}, dll::binarize_pre<30>{}); auto dataset = dll::make_mnist_dataset(dll::batch_size<300>{}, dll::binarize_pre<30>{}); // Build the network using network_t = dll::network_desc< dll::network_layers< dll::conv_rbm_square_desc<1, 28, 8, 9, dll::momentum, dll::batch_size<300>>::layer_t, dll::conv_rbm_square_desc<8, 20, 8, 5, dll::momentum, dll::batch_size<300>>::layer_t, dll::rbm<8 * 16 * 16, 1000, dll::batch_size<300>, dll::momentum>, dll::rbm<1000, 1000, dll::batch_size<300>, dll::momentum>, dll::rbm<1000, 10, dll::batch_size<300>, dll::hidden<dll::unit_type::SOFTMAX>> > , dll::updater<dll::updater_type::NADAM> // Nesterov Adam (NADAM) , dll::batch_size<300> // The mini-batch size , dll::shuffle // Shuffle before each epoch , dll::no_batch_display // Disable pretty print of each every batch , dll::no_epoch_error // Disable computation of the error at each epoch >::network_t; auto net = std::make_unique<network_t>(); // Display the network and dataset net->display_pretty(); dataset.display_pretty(); { // Use an extra timer for normalization dll::auto_timer timer("full_train"); // Pretrain the network with contrastive divergence net->pretrain(ae_dataset.train(), 10); // Train the network for performance sake net->fine_tune(dataset.train(), 10); // Test the network on test set net->evaluate(dataset.test()); } // Show where the time was spent dll::dump_timers_pretty(); // Show ETL performance counters etl::dump_counters_pretty(); return 0; } <commit_msg>Fix example cdbn_perf<commit_after>//======================================================================= // Copyright (c) 2014-2020 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #define ETL_COUNTERS // Note: This example uses too much memory for pretraining and as such // cannot use the the GPU Pool //#define ETL_GPU_POOL #include "dll/rbm/conv_rbm.hpp" #include "dll/rbm/rbm.hpp" #include "dll/network.hpp" #include "dll/datasets.hpp" int main(int /*argc*/, char* /*argv*/ []) { // Load the dataset auto ae_dataset = dll::make_mnist_ae_dataset(dll::batch_size<300>{}, dll::binarize_pre<30>{}); auto dataset = dll::make_mnist_dataset(dll::batch_size<300>{}, dll::binarize_pre<30>{}); // Build the network using network_t = dll::network_desc< dll::network_layers< dll::conv_rbm_square_desc<1, 28, 8, 9, dll::momentum, dll::batch_size<300>>::layer_t, dll::conv_rbm_square_desc<8, 20, 8, 5, dll::momentum, dll::batch_size<300>>::layer_t, dll::rbm<8 * 16 * 16, 1000, dll::batch_size<300>, dll::momentum>, dll::rbm<1000, 1000, dll::batch_size<300>, dll::momentum>, dll::rbm<1000, 10, dll::batch_size<300>, dll::hidden<dll::unit_type::SOFTMAX>> > , dll::updater<dll::updater_type::NADAM> // Nesterov Adam (NADAM) , dll::batch_size<300> // The mini-batch size , dll::shuffle // Shuffle before each epoch , dll::no_batch_display // Disable pretty print of each every batch , dll::no_epoch_error // Disable computation of the error at each epoch >::network_t; auto net = std::make_unique<network_t>(); // Display the network and dataset net->display_pretty(); dataset.display_pretty(); { // Use an extra timer for normalization dll::auto_timer timer("full_train"); // Pretrain the network with contrastive divergence net->pretrain(ae_dataset.train(), 10); // Train the network for performance sake net->fine_tune(dataset.train(), 10); // Test the network on test set net->evaluate(dataset.test()); } // Show where the time was spent dll::dump_timers_pretty(); // Show ETL performance counters etl::dump_counters_pretty(); return 0; } <|endoftext|>
<commit_before>//===--- SILFunction.cpp - Defines the SILFunction data structure ---------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/SIL/Function.h" #include "swift/SIL/SILBuilder.h" #include "swift/SIL/SILModule.h" #include "swift/SIL/SILConstant.h" #include "swift/AST/ASTContext.h" #include "swift/AST/Decl.h" #include "swift/AST/Expr.h" #include "swift/AST/Pattern.h" #include "swift/AST/Types.h" using namespace swift; Function::~Function() { } static SILType toplevelFunctionType(ASTContext &C) { auto t = FunctionType::get(TupleType::getEmpty(C), TupleType::getEmpty(C), C); return SILType::getPreLoweredType(t, /*isAddress=*/ false, /*isLoadable=*/ true, /*uncurryLevel=*/ 0); } SILModule::SILModule(ASTContext &Context, bool hasTopLevel) : Context(Context), toplevel(nullptr) { if (hasTopLevel) toplevel = new (*this) Function(*this, toplevelFunctionType(Context)); } SILModule::~SILModule() { } static unsigned getNaturalUncurryLevel(CapturingExpr *func) { assert(func->getParamPatterns().size() >= 1 && "no arguments for func?!"); unsigned level = func->getParamPatterns().size() - 1; // Functions with captures have an extra uncurry level for the capture // context. if (!func->getCaptures().empty()) level += 1; return level; } SILConstant::SILConstant(ValueDecl *vd, SILConstant::Kind kind, unsigned atUncurryLevel) : loc(vd), kind(kind) { unsigned naturalUncurryLevel; if (auto *func = dyn_cast<FuncDecl>(vd)) { assert(!func->isGetterOrSetter() && "cannot create a Func SILConstant for a property accessor"); assert(kind == Kind::Func && "can only create a Func SILConstant for a func decl"); naturalUncurryLevel = getNaturalUncurryLevel(func->getBody()); } else if (isa<ConstructorDecl>(vd)) { assert((kind == Kind::Allocator || kind == Kind::Initializer) && "can only create Allocator or Initializer SILConstant for ctor"); naturalUncurryLevel = 1; } else if (isa<ClassDecl>(vd)) { assert(kind == Kind::Destructor && "can only create Destructor SILConstant for class"); naturalUncurryLevel = 0; } else if (isa<VarDecl>(vd)) { assert((kind == Kind::Getter || kind == Kind::Setter || kind == Kind::GlobalAccessor) && "can only create Getter, Setter, or GlobalAccessor SILConstant " "for var"); naturalUncurryLevel = this->isProperty() ? (vd->isInstanceMember() ? 1 : 0) : 0; } else if (isa<SubscriptDecl>(vd)) { assert((kind == Kind::Getter || kind == Kind::Setter) && "can only create Getter or Setter SILConstant for subscript"); // T -> Index -> () -> U naturalUncurryLevel = 2; } assert((atUncurryLevel == ConstructAtNaturalUncurryLevel || atUncurryLevel <= naturalUncurryLevel) && "can't emit SILConstant below natural uncurry level"); uncurryLevel = atUncurryLevel == ConstructAtNaturalUncurryLevel ? naturalUncurryLevel : atUncurryLevel; } SILConstant::SILConstant(SILConstant::Loc baseLoc, unsigned atUncurryLevel) { unsigned naturalUncurryLevel; if (ValueDecl *vd = baseLoc.dyn_cast<ValueDecl*>()) { if (FuncDecl *fd = dyn_cast<FuncDecl>(vd)) { // Map getter or setter FuncDecls to Getter or Setter SILConstants of the // property. if (fd->isGetterOrSetter()) { ValueDecl *property = cast<ValueDecl>(fd->getGetterOrSetterDecl()); loc = property; if (fd->getGetterDecl()) { kind = Kind::Getter; } else if (fd->getSetterDecl()) { kind = Kind::Setter; } else { llvm_unreachable("no getter or setter decl?!"); } } // Map other FuncDecls directly to Func SILConstants. else { loc = fd; kind = Kind::Func; } naturalUncurryLevel = getNaturalUncurryLevel(fd->getBody()); } // Map DestructorDecls to Destructor SILConstants of the ClassDecl. else if (DestructorDecl *dd = dyn_cast<DestructorDecl>(vd)) { ClassDecl *cd = cast<ClassDecl>(dd->getParent()); loc = cd; kind = Kind::Destructor; naturalUncurryLevel = 0; } // Map ConstructorDecls to the Allocator SILConstant of the constructor. else if (ConstructorDecl *cd = dyn_cast<ConstructorDecl>(vd)) { loc = cd; kind = Kind::Allocator; naturalUncurryLevel = 1; } // Map global VarDecls to their GlobalAccessor SILConstant. else if (VarDecl *vard = dyn_cast<VarDecl>(vd)) { loc = vard; kind = Kind::GlobalAccessor; naturalUncurryLevel = 0; } else { llvm_unreachable("invalid loc decl for SILConstant!"); } } else { auto *expr = baseLoc.get<CapturingExpr*>(); loc = expr; kind = Kind::Func; assert(expr->getParamPatterns().size() >= 1 && "no param patterns for function?!"); naturalUncurryLevel = getNaturalUncurryLevel(expr); } // Set the uncurry level. assert((atUncurryLevel == ConstructAtNaturalUncurryLevel || atUncurryLevel <= naturalUncurryLevel) && "can't emit SILConstant below natural uncurry level"); uncurryLevel = atUncurryLevel == ConstructAtNaturalUncurryLevel ? naturalUncurryLevel : atUncurryLevel; } SILType SILType::getObjectPointerType(ASTContext &C) { return SILType(CanType(C.TheObjectPointerType), /*isAddress=*/ false, /*isLoadable=*/ true, /*uncurryLevel=*/ 0); } SILType SILType::getRawPointerType(ASTContext &C) { return SILType(CanType(C.TheRawPointerType), /*isAddress=*/false, /*isLoadable=*/true, /*uncurryLevel=*/ 0); } SILType SILType::getOpaquePointerType(ASTContext &C) { return SILType(CanType(C.TheOpaquePointerType), /*isAddress=*/false, /*isLoadable=*/true, /*uncurryLevel=*/ 0); } SILType SILType::getEmptyTupleType(ASTContext &C) { return SILType(CanType(TupleType::getEmpty(C)), /*isAddress=*/false, /*isLoadable=*/true, /*uncurryLevel=*/ 0); } SILType SILType::getBuiltinIntegerType(unsigned bitWidth, ASTContext &C) { return SILType(CanType(BuiltinIntegerType::get(bitWidth, C)), /*isAddress=*/false, /*isLoadable=*/true, /*uncurryLevel=*/ 0); } TupleInst *SILBuilder::createEmptyTuple(SILLocation Loc) { return createTuple(Loc, SILType::getEmptyTupleType(F.getContext()), ArrayRef<Value>()); } <commit_msg>SIL: Fix uncurry level of local capturing props.<commit_after>//===--- SILFunction.cpp - Defines the SILFunction data structure ---------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/SIL/Function.h" #include "swift/SIL/SILBuilder.h" #include "swift/SIL/SILModule.h" #include "swift/SIL/SILConstant.h" #include "swift/AST/ASTContext.h" #include "swift/AST/Decl.h" #include "swift/AST/Expr.h" #include "swift/AST/Pattern.h" #include "swift/AST/Types.h" using namespace swift; Function::~Function() { } static SILType toplevelFunctionType(ASTContext &C) { auto t = FunctionType::get(TupleType::getEmpty(C), TupleType::getEmpty(C), C); return SILType::getPreLoweredType(t, /*isAddress=*/ false, /*isLoadable=*/ true, /*uncurryLevel=*/ 0); } SILModule::SILModule(ASTContext &Context, bool hasTopLevel) : Context(Context), toplevel(nullptr) { if (hasTopLevel) toplevel = new (*this) Function(*this, toplevelFunctionType(Context)); } SILModule::~SILModule() { } static unsigned getNaturalUncurryLevel(CapturingExpr *func) { assert(func->getParamPatterns().size() >= 1 && "no arguments for func?!"); unsigned level = func->getParamPatterns().size() - 1; // Functions with captures have an extra uncurry level for the capture // context. if (!func->getCaptures().empty()) level += 1; return level; } SILConstant::SILConstant(ValueDecl *vd, SILConstant::Kind kind, unsigned atUncurryLevel) : loc(vd), kind(kind) { unsigned naturalUncurryLevel; if (auto *func = dyn_cast<FuncDecl>(vd)) { assert(!func->isGetterOrSetter() && "cannot create a Func SILConstant for a property accessor"); assert(kind == Kind::Func && "can only create a Func SILConstant for a func decl"); naturalUncurryLevel = getNaturalUncurryLevel(func->getBody()); } else if (isa<ConstructorDecl>(vd)) { assert((kind == Kind::Allocator || kind == Kind::Initializer) && "can only create Allocator or Initializer SILConstant for ctor"); naturalUncurryLevel = 1; } else if (isa<ClassDecl>(vd)) { assert(kind == Kind::Destructor && "can only create Destructor SILConstant for class"); naturalUncurryLevel = 0; } else if (auto *var = dyn_cast<VarDecl>(vd)) { assert((kind == Kind::Getter || kind == Kind::Setter || kind == Kind::GlobalAccessor) && "can only create Getter, Setter, or GlobalAccessor SILConstant " "for var"); assert(((kind == Kind::GlobalAccessor) ^ var->isProperty()) && "can't reference global accessor of property"); assert(!(kind == Kind::GlobalAccessor && var->getDeclContext()->isLocalContext()) && "can't reference global accessor of local var"); if (kind == Kind::GlobalAccessor) { naturalUncurryLevel = 0; } else { // Instance properties have a 'this' curry. if (var->isInstanceMember()) naturalUncurryLevel = 1; // Local properties may have captures that affect the natural uncurry // level. else if (kind == Kind::Getter && var->getGetter()) naturalUncurryLevel = getNaturalUncurryLevel(var->getGetter()->getBody()); else if (kind == Kind::Setter && var->getSetter()) naturalUncurryLevel = getNaturalUncurryLevel(var->getSetter()->getBody()); // A property accessor for a non-instance variable without getters and // setters must be a resilient property, so it can't have context. else naturalUncurryLevel = 0; } } else if (isa<SubscriptDecl>(vd)) { assert((kind == Kind::Getter || kind == Kind::Setter) && "can only create Getter or Setter SILConstant for subscript"); // Subscript accessors have // getter type (T)(Index)() -> U and // setter type (T)(Index)(U) -> () naturalUncurryLevel = 2; } assert((atUncurryLevel == ConstructAtNaturalUncurryLevel || atUncurryLevel <= naturalUncurryLevel) && "can't emit SILConstant below natural uncurry level"); uncurryLevel = atUncurryLevel == ConstructAtNaturalUncurryLevel ? naturalUncurryLevel : atUncurryLevel; } SILConstant::SILConstant(SILConstant::Loc baseLoc, unsigned atUncurryLevel) { unsigned naturalUncurryLevel; if (ValueDecl *vd = baseLoc.dyn_cast<ValueDecl*>()) { if (FuncDecl *fd = dyn_cast<FuncDecl>(vd)) { // Map getter or setter FuncDecls to Getter or Setter SILConstants of the // property. if (fd->isGetterOrSetter()) { ValueDecl *property = cast<ValueDecl>(fd->getGetterOrSetterDecl()); loc = property; if (fd->getGetterDecl()) { kind = Kind::Getter; } else if (fd->getSetterDecl()) { kind = Kind::Setter; } else { llvm_unreachable("no getter or setter decl?!"); } } // Map other FuncDecls directly to Func SILConstants. else { loc = fd; kind = Kind::Func; } naturalUncurryLevel = getNaturalUncurryLevel(fd->getBody()); } // Map DestructorDecls to Destructor SILConstants of the ClassDecl. else if (DestructorDecl *dd = dyn_cast<DestructorDecl>(vd)) { ClassDecl *cd = cast<ClassDecl>(dd->getParent()); loc = cd; kind = Kind::Destructor; naturalUncurryLevel = 0; } // Map ConstructorDecls to the Allocator SILConstant of the constructor. else if (ConstructorDecl *cd = dyn_cast<ConstructorDecl>(vd)) { loc = cd; kind = Kind::Allocator; naturalUncurryLevel = 1; } // Map global VarDecls to their GlobalAccessor SILConstant. else if (VarDecl *vard = dyn_cast<VarDecl>(vd)) { assert(!vard->isProperty() && "can't reference global accessor of property"); assert(!vard->getDeclContext()->isLocalContext() && "can't reference global accessor of local var"); loc = vard; kind = Kind::GlobalAccessor; naturalUncurryLevel = 0; } else { llvm_unreachable("invalid loc decl for SILConstant!"); } } else { auto *expr = baseLoc.get<CapturingExpr*>(); loc = expr; kind = Kind::Func; assert(expr->getParamPatterns().size() >= 1 && "no param patterns for function?!"); naturalUncurryLevel = getNaturalUncurryLevel(expr); } // Set the uncurry level. assert((atUncurryLevel == ConstructAtNaturalUncurryLevel || atUncurryLevel <= naturalUncurryLevel) && "can't emit SILConstant below natural uncurry level"); uncurryLevel = atUncurryLevel == ConstructAtNaturalUncurryLevel ? naturalUncurryLevel : atUncurryLevel; } SILType SILType::getObjectPointerType(ASTContext &C) { return SILType(CanType(C.TheObjectPointerType), /*isAddress=*/ false, /*isLoadable=*/ true, /*uncurryLevel=*/ 0); } SILType SILType::getRawPointerType(ASTContext &C) { return SILType(CanType(C.TheRawPointerType), /*isAddress=*/false, /*isLoadable=*/true, /*uncurryLevel=*/ 0); } SILType SILType::getOpaquePointerType(ASTContext &C) { return SILType(CanType(C.TheOpaquePointerType), /*isAddress=*/false, /*isLoadable=*/true, /*uncurryLevel=*/ 0); } SILType SILType::getEmptyTupleType(ASTContext &C) { return SILType(CanType(TupleType::getEmpty(C)), /*isAddress=*/false, /*isLoadable=*/true, /*uncurryLevel=*/ 0); } SILType SILType::getBuiltinIntegerType(unsigned bitWidth, ASTContext &C) { return SILType(CanType(BuiltinIntegerType::get(bitWidth, C)), /*isAddress=*/false, /*isLoadable=*/true, /*uncurryLevel=*/ 0); } TupleInst *SILBuilder::createEmptyTuple(SILLocation Loc) { return createTuple(Loc, SILType::getEmptyTupleType(F.getContext()), ArrayRef<Value>()); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: volume3d.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2007-06-27 18:07:20 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #ifndef _VOLUME3D_HXX #include <svx/volume3d.hxx> #endif #ifndef _BGFX_POLYGON_B3DPOLYGON_HXX #include <basegfx/polygon/b3dpolygon.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif /************************************************************************* |* |* Konstruktor 1: | |* rPos: Zentrum oder minimale Koordinate links, unten, hinten |__ |* (abhaengig von bPosIsCenter) / |* \************************************************************************/ Volume3D::Volume3D(const basegfx::B3DPoint& rPos, const basegfx::B3DPoint& r3DSize, bool bPosIsCenter) : basegfx::B3DRange() { if(bPosIsCenter) { expand(rPos - r3DSize / 2.0); } else { expand(rPos); } expand(getMinimum() + r3DSize); } Volume3D::Volume3D(const basegfx::B3DRange& rVol) : basegfx::B3DRange(rVol) { } /************************************************************************* |* |* Konstruktor 2 - leeres Volumen, Werte als ungueltig markieren |* \************************************************************************/ Volume3D::Volume3D() : basegfx::B3DRange() { } /************************************************************************* |* |* Transformation des Volumens berechnen und als neues Volumen |* zurueckgeben |* \************************************************************************/ Volume3D Volume3D::GetTransformVolume(const basegfx::B3DHomMatrix& rTfMatrix) const { Volume3D aTfVol; if(!isEmpty()) { basegfx::B3DPoint aTfVec; Vol3DPointIterator aIter(*this, &rTfMatrix); while(aIter.Next(aTfVec)) { aTfVol.expand(aTfVec); } } return aTfVol; } /************************************************************************* |* |* Drahtgitter-Linien fuer das Volumen berechnen und in rPoly3D ablegen |* \************************************************************************/ void Volume3D::CreateWireframe(basegfx::B3DPolygon& rPoly3D, const basegfx::B3DHomMatrix* pTf) const { if(isEmpty()) return; basegfx::B3DVector aDiff(getRange()); basegfx::B3DPolygon aVolPnts; sal_uInt32 nZeroCnt(0L); // Alle Punkte holen Vol3DPointIterator aIter(*this, pTf); basegfx::B3DPoint aTfVec; while(aIter.Next(aTfVec)) { aVolPnts.append(aTfVec); } // 0-Ausmasse des BoundVolumes zaehlen if(0.0 == aDiff.getX()) nZeroCnt++; if(0.0 == aDiff.getY()) nZeroCnt++; if(0.0 == aDiff.getZ()) nZeroCnt++; // Die drei Ecksegemente des Volumens mit je drei Linien ausgeben; // falls Koordinatenanteile 0 sind, nicht alle Segmente verwenden, // um das gegenseitige Ausloeschen bei XOR-Ausgabe zu verhindern // 4 // | Dieses Segment immer // | // 0---1 // / // 3 // Die Liniensegmente eines Segments werden immer in der Reihenfolge // X-, Y- und dann Z-Richtung ausgegeben (gilt natuerlich nur fuer // untransformierte Koordinaten) rPoly3D.append(aVolPnts.getB3DPoint(0)); if(nZeroCnt < 3L) { // wenn keine Ausdehnung, dann nur den ersten Punkt einfuegen rPoly3D.append(aVolPnts.getB3DPoint(1L)); rPoly3D.append(aVolPnts.getB3DPoint(0L)); rPoly3D.append(aVolPnts.getB3DPoint(4L)); rPoly3D.append(aVolPnts.getB3DPoint(0L)); rPoly3D.append(aVolPnts.getB3DPoint(3L)); } if(nZeroCnt < 2L) { if(nZeroCnt == 0L || aDiff.getX() == 0.0) { // 4 // / // 7---6 // | // | // 3 rPoly3D.append(aVolPnts.getB3DPoint(7L)); rPoly3D.append(aVolPnts.getB3DPoint(6L)); rPoly3D.append(aVolPnts.getB3DPoint(7L)); rPoly3D.append(aVolPnts.getB3DPoint(3L)); rPoly3D.append(aVolPnts.getB3DPoint(7L)); rPoly3D.append(aVolPnts.getB3DPoint(4L)); } if(nZeroCnt == 0L || (aDiff.getY() == 0.0)) { // 6 // | 1 // |/ // 3---2 rPoly3D.append(aVolPnts.getB3DPoint(2L)); rPoly3D.append(aVolPnts.getB3DPoint(3L)); rPoly3D.append(aVolPnts.getB3DPoint(2L)); rPoly3D.append(aVolPnts.getB3DPoint(6L)); rPoly3D.append(aVolPnts.getB3DPoint(2L)); rPoly3D.append(aVolPnts.getB3DPoint(1L)); } if(nZeroCnt == 0L || (aDiff.getZ() == 0.0)) { // 4---5 // /| // 6 | // 1 rPoly3D.append(aVolPnts.getB3DPoint(5L)); rPoly3D.append(aVolPnts.getB3DPoint(4L)); rPoly3D.append(aVolPnts.getB3DPoint(5L)); rPoly3D.append(aVolPnts.getB3DPoint(1L)); rPoly3D.append(aVolPnts.getB3DPoint(5L)); rPoly3D.append(aVolPnts.getB3DPoint(6L)); } } } /************************************************************************* |* |* Konstruktor des Point-Iterators |* \************************************************************************/ Vol3DPointIterator::Vol3DPointIterator(const basegfx::B3DRange& rVol, const basegfx::B3DHomMatrix* pTf) : rVolume(rVol), pTransform(pTf), nIndex(0) { DBG_ASSERT(!rVol.isEmpty(), "Vol3DPointIterator-Aufruf mit ungueltigem Volume3D!"); a3DExtent = rVolume.getMaximum() - rVolume.getMinimum(); } /************************************************************************* |* |* Gibt die einzelnen Punkte des (ggf. transformierten) Volumens zurueck |* |* 4---5 -> Reihenfolge der Punktausgabe (untransformiert) |* /| /| |* 7---6 | |* | 0-|-1 |* |/ |/ |* 3---2 |* \************************************************************************/ bool Vol3DPointIterator::Next(basegfx::B3DPoint& rVec) { if(nIndex > 7) { return false; } else { rVec = rVolume.getMinimum(); if(nIndex >= 4) { rVec.setY(rVec.getY() + a3DExtent.getY()); } switch(nIndex) { case 6: case 2: rVec.setZ(rVec.getZ() + a3DExtent.getZ()); case 5: case 1: rVec.setX(rVec.getX() + a3DExtent.getX()); break; case 7: case 3: rVec.setZ(rVec.getZ() + a3DExtent.getZ()); break; } nIndex++; if(pTransform) { rVec *= *pTransform; } return true; } } // eof <commit_msg>INTEGRATION: CWS aw051 (1.4.220); FILE MERGED 2007/06/22 08:31:52 aw 1.4.220.1: #i72532# removed assert when empty Vol3DPointIterator is created, this does no harm.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: volume3d.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2007-07-18 10:53:35 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #ifndef _VOLUME3D_HXX #include <svx/volume3d.hxx> #endif #ifndef _BGFX_POLYGON_B3DPOLYGON_HXX #include <basegfx/polygon/b3dpolygon.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif /************************************************************************* |* |* Konstruktor 1: | |* rPos: Zentrum oder minimale Koordinate links, unten, hinten |__ |* (abhaengig von bPosIsCenter) / |* \************************************************************************/ Volume3D::Volume3D(const basegfx::B3DPoint& rPos, const basegfx::B3DPoint& r3DSize, bool bPosIsCenter) : basegfx::B3DRange() { if(bPosIsCenter) { expand(rPos - r3DSize / 2.0); } else { expand(rPos); } expand(getMinimum() + r3DSize); } Volume3D::Volume3D(const basegfx::B3DRange& rVol) : basegfx::B3DRange(rVol) { } /************************************************************************* |* |* Konstruktor 2 - leeres Volumen, Werte als ungueltig markieren |* \************************************************************************/ Volume3D::Volume3D() : basegfx::B3DRange() { } /************************************************************************* |* |* Transformation des Volumens berechnen und als neues Volumen |* zurueckgeben |* \************************************************************************/ Volume3D Volume3D::GetTransformVolume(const basegfx::B3DHomMatrix& rTfMatrix) const { Volume3D aTfVol; if(!isEmpty()) { basegfx::B3DPoint aTfVec; Vol3DPointIterator aIter(*this, &rTfMatrix); while(aIter.Next(aTfVec)) { aTfVol.expand(aTfVec); } } return aTfVol; } /************************************************************************* |* |* Drahtgitter-Linien fuer das Volumen berechnen und in rPoly3D ablegen |* \************************************************************************/ void Volume3D::CreateWireframe(basegfx::B3DPolygon& rPoly3D, const basegfx::B3DHomMatrix* pTf) const { if(isEmpty()) return; basegfx::B3DVector aDiff(getRange()); basegfx::B3DPolygon aVolPnts; sal_uInt32 nZeroCnt(0L); // Alle Punkte holen Vol3DPointIterator aIter(*this, pTf); basegfx::B3DPoint aTfVec; while(aIter.Next(aTfVec)) { aVolPnts.append(aTfVec); } // 0-Ausmasse des BoundVolumes zaehlen if(0.0 == aDiff.getX()) nZeroCnt++; if(0.0 == aDiff.getY()) nZeroCnt++; if(0.0 == aDiff.getZ()) nZeroCnt++; // Die drei Ecksegemente des Volumens mit je drei Linien ausgeben; // falls Koordinatenanteile 0 sind, nicht alle Segmente verwenden, // um das gegenseitige Ausloeschen bei XOR-Ausgabe zu verhindern // 4 // | Dieses Segment immer // | // 0---1 // / // 3 // Die Liniensegmente eines Segments werden immer in der Reihenfolge // X-, Y- und dann Z-Richtung ausgegeben (gilt natuerlich nur fuer // untransformierte Koordinaten) rPoly3D.append(aVolPnts.getB3DPoint(0)); if(nZeroCnt < 3L) { // wenn keine Ausdehnung, dann nur den ersten Punkt einfuegen rPoly3D.append(aVolPnts.getB3DPoint(1L)); rPoly3D.append(aVolPnts.getB3DPoint(0L)); rPoly3D.append(aVolPnts.getB3DPoint(4L)); rPoly3D.append(aVolPnts.getB3DPoint(0L)); rPoly3D.append(aVolPnts.getB3DPoint(3L)); } if(nZeroCnt < 2L) { if(nZeroCnt == 0L || aDiff.getX() == 0.0) { // 4 // / // 7---6 // | // | // 3 rPoly3D.append(aVolPnts.getB3DPoint(7L)); rPoly3D.append(aVolPnts.getB3DPoint(6L)); rPoly3D.append(aVolPnts.getB3DPoint(7L)); rPoly3D.append(aVolPnts.getB3DPoint(3L)); rPoly3D.append(aVolPnts.getB3DPoint(7L)); rPoly3D.append(aVolPnts.getB3DPoint(4L)); } if(nZeroCnt == 0L || (aDiff.getY() == 0.0)) { // 6 // | 1 // |/ // 3---2 rPoly3D.append(aVolPnts.getB3DPoint(2L)); rPoly3D.append(aVolPnts.getB3DPoint(3L)); rPoly3D.append(aVolPnts.getB3DPoint(2L)); rPoly3D.append(aVolPnts.getB3DPoint(6L)); rPoly3D.append(aVolPnts.getB3DPoint(2L)); rPoly3D.append(aVolPnts.getB3DPoint(1L)); } if(nZeroCnt == 0L || (aDiff.getZ() == 0.0)) { // 4---5 // /| // 6 | // 1 rPoly3D.append(aVolPnts.getB3DPoint(5L)); rPoly3D.append(aVolPnts.getB3DPoint(4L)); rPoly3D.append(aVolPnts.getB3DPoint(5L)); rPoly3D.append(aVolPnts.getB3DPoint(1L)); rPoly3D.append(aVolPnts.getB3DPoint(5L)); rPoly3D.append(aVolPnts.getB3DPoint(6L)); } } } /************************************************************************* |* |* Konstruktor des Point-Iterators |* \************************************************************************/ Vol3DPointIterator::Vol3DPointIterator(const basegfx::B3DRange& rVol, const basegfx::B3DHomMatrix* pTf) : rVolume(rVol), pTransform(pTf), nIndex(0) { // #i72532# Assert not needed, nothing bad happens when the volume is empty. // DBG_ASSERT(!rVol.isEmpty(), "Vol3DPointIterator-Aufruf mit ungueltigem Volume3D!"); a3DExtent = rVolume.getMaximum() - rVolume.getMinimum(); } /************************************************************************* |* |* Gibt die einzelnen Punkte des (ggf. transformierten) Volumens zurueck |* |* 4---5 -> Reihenfolge der Punktausgabe (untransformiert) |* /| /| |* 7---6 | |* | 0-|-1 |* |/ |/ |* 3---2 |* \************************************************************************/ bool Vol3DPointIterator::Next(basegfx::B3DPoint& rVec) { if(nIndex > 7) { return false; } else { rVec = rVolume.getMinimum(); if(nIndex >= 4) { rVec.setY(rVec.getY() + a3DExtent.getY()); } switch(nIndex) { case 6: case 2: rVec.setZ(rVec.getZ() + a3DExtent.getZ()); case 5: case 1: rVec.setX(rVec.getX() + a3DExtent.getX()); break; case 7: case 3: rVec.setZ(rVec.getZ() + a3DExtent.getZ()); break; } nIndex++; if(pTransform) { rVec *= *pTransform; } return true; } } // eof <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ /// \ingroup macros /// \file MUONStatusMap.C /// \brief Macro to check/test pad status and pad status map makers /// /// \author Laurent Aphecetche #if !defined(__CINT__) || defined(__MAKECINT__) #include "AliCDBManager.h" #include "AliMUONCalibrationData.h" #include "AliMUONLogger.h" #include "AliMUONPadStatusMaker.h" #include "AliMUONPadStatusMapMaker.h" #include "AliMUONRecoParam.h" #include "AliMUONVCalibParam.h" #include "AliMUONVStore.h" #include "AliMpCDB.h" #include "AliMpConstants.h" #include "AliMpDDLStore.h" #include "AliMpDetElement.h" #include "AliMpManuIterator.h" #include "Riostream.h" #endif //AliMUONVStore* MUONStatusMap(const TString& cdbStorage = "alien://folder=/alice/data/2009/OCDB", AliMUONVStore* MUONStatusMap(const TString& cdbStorage = "local://$ALICE_ROOT/OCDB", Int_t runNumber=67138, Bool_t statusOnly=kTRUE) { AliMUONRecoParam* recoParam = AliMUONRecoParam::GetCosmicParam(); AliMpCDB::LoadAll2(); AliCDBManager* man = AliCDBManager::Instance(); man->SetDefaultStorage(cdbStorage.Data()); // man->SetSpecificStorage("MUON/Calib/OccupancyMap","local://$ALICE_ROOT/OCDB"); // man->SetSpecificStorage("MUON/Calib/OccupancyMap","alien://folder=/alice/cern.ch/user/l/laphecet/OCDB"); // man->SetSpecificStorage("MUON/Calib/RejectList","alien://folder=/alice/cern.ch/user/l/laphecet/OCDB"); // man->SetSpecificStorage("MUON/Align/Data","alien://folder=/alice/cern.ch/user/l/laphecet/OCDB"); // man->SetRun(runNumber); AliMUONCalibrationData cd(runNumber); AliMUONPadStatusMaker statusMaker(cd); statusMaker.SetLimits(*recoParam); delete recoParam; UInt_t mask = recoParam->PadGoodnessMask(); statusMaker.Report(mask); if ( statusOnly ) return statusMaker.StatusStore(); const Bool_t deferredInitialization = kFALSE; AliMUONPadStatusMapMaker statusMapMaker(cd,mask,deferredInitialization); return statusMapMaker.StatusMap(); } <commit_msg>Updated macro<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ /// \ingroup macros /// \file MUONStatusMap.C /// \brief Macro to check/test pad status and pad status map makers /// /// \author Laurent Aphecetche #if !defined(__CINT__) || defined(__MAKECINT__) #include "AliCDBManager.h" #include "AliMUONCalibrationData.h" #include "AliMUONLogger.h" #include "AliMUONPadStatusMaker.h" #include "AliMUONPadStatusMapMaker.h" #include "AliMUONRecoParam.h" #include "AliMUONVCalibParam.h" #include "AliMUONVStore.h" #include "AliMUONCDB.h" #include "AliMpConstants.h" #include "AliMpDDLStore.h" #include "AliMpDetElement.h" #include "AliMpManuIterator.h" #include "Riostream.h" #endif //AliMUONVStore* MUONStatusMap(const TString& cdbStorage = "alien://folder=/alice/data/2009/OCDB", AliMUONVStore* MUONStatusMap(const TString& cdbStorage = "alien://folder=/alice/data/2011/OCDB", Int_t runNumber=145000, Bool_t statusOnly=kTRUE) { AliCDBManager::Instance()->SetDefaultStorage(cdbStorage); AliCDBManager::Instance()->SetRun(runNumber); AliMUONCDB::LoadMapping(); AliMUONRecoParam* recoParam = AliMUONCDB::LoadRecoParam(); AliCDBManager* man = AliCDBManager::Instance(); man->SetDefaultStorage(cdbStorage.Data()); // man->SetSpecificStorage("MUON/Calib/OccupancyMap","local://$ALICE_ROOT/OCDB"); // man->SetSpecificStorage("MUON/Calib/OccupancyMap","alien://folder=/alice/cern.ch/user/l/laphecet/OCDB"); // man->SetSpecificStorage("MUON/Calib/RejectList","alien://folder=/alice/cern.ch/user/l/laphecet/OCDB"); // man->SetSpecificStorage("MUON/Align/Data","alien://folder=/alice/cern.ch/user/l/laphecet/OCDB"); AliMUONCalibrationData cd(runNumber); AliMUONPadStatusMaker statusMaker(cd); statusMaker.SetLimits(*recoParam); UInt_t mask = recoParam->PadGoodnessMask(); // delete recoParam; statusMaker.Report(mask); if ( statusOnly ) return statusMaker.StatusStore(); const Bool_t deferredInitialization = kFALSE; AliMUONPadStatusMapMaker statusMapMaker(cd,mask,deferredInitialization); return statusMapMaker.StatusMap(); } <|endoftext|>
<commit_before>/** * \file * \brief ThreadControlBlock class header * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2014-07-31 */ #ifndef INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_ #define INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_ #include "distortos/architecture/Stack.hpp" #include <cstdint> namespace distortos { namespace scheduler { /// ThreadControlBlock class is a simple description of a Thread class ThreadControlBlock { public: /// state of the thread enum class State : uint8_t { /// state in which thread is created, before being added to Scheduler New, /// thread is runnable Runnable, }; /** * \brief ThreadControlBlock constructor. * * \param [in] buffer is a pointer to stack's buffer * \param [in] size is the size of stack's buffer, bytes * \param [in] function is a reference to thread's function * \param [in] arguments is an argument for function * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest */ ThreadControlBlock(void *buffer, size_t size, void * (&function)(void *), void *arguments, uint8_t priority); /// \return reference to internal Stack object architecture::Stack & getStack() { return stack_; } /// \return const reference to internal Stack object const architecture::Stack & getStack() const { return stack_; } /// \return priority of ThreadControlBlock uint8_t getPriority() const { return priority_; } /// \return tick count value for waking the thread from sleeping state uint64_t getSleepUntil() const { return sleepUntil_; } /// \return current state of object State getState() const { return state_; } /// \param [in] sleep_until is the tick count value for waking the thread from sleeping state void setSleepUntil(const uint64_t sleep_until) { sleepUntil_ = sleep_until; } /// \param [in] state is the new state of object void setState(const State state) { state_ = state; } private: /// internal stack object architecture::Stack stack_; /// tick count value for waking the thread from sleeping state uint64_t sleepUntil_; /// thread's priority, 0 - lowest, UINT8_MAX - highest uint8_t priority_; /// current state of object State state_; }; } // namespace scheduler } // namespace distortos #endif // INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_ <commit_msg>thread control block: add new State - Sleeping<commit_after>/** * \file * \brief ThreadControlBlock class header * * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2014-07-31 */ #ifndef INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_ #define INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_ #include "distortos/architecture/Stack.hpp" #include <cstdint> namespace distortos { namespace scheduler { /// ThreadControlBlock class is a simple description of a Thread class ThreadControlBlock { public: /// state of the thread enum class State : uint8_t { /// state in which thread is created, before being added to Scheduler New, /// thread is runnable Runnable, /// thread is sleeping Sleeping, }; /** * \brief ThreadControlBlock constructor. * * \param [in] buffer is a pointer to stack's buffer * \param [in] size is the size of stack's buffer, bytes * \param [in] function is a reference to thread's function * \param [in] arguments is an argument for function * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest */ ThreadControlBlock(void *buffer, size_t size, void * (&function)(void *), void *arguments, uint8_t priority); /// \return reference to internal Stack object architecture::Stack & getStack() { return stack_; } /// \return const reference to internal Stack object const architecture::Stack & getStack() const { return stack_; } /// \return priority of ThreadControlBlock uint8_t getPriority() const { return priority_; } /// \return tick count value for waking the thread from sleeping state uint64_t getSleepUntil() const { return sleepUntil_; } /// \return current state of object State getState() const { return state_; } /// \param [in] sleep_until is the tick count value for waking the thread from sleeping state void setSleepUntil(const uint64_t sleep_until) { sleepUntil_ = sleep_until; } /// \param [in] state is the new state of object void setState(const State state) { state_ = state; } private: /// internal stack object architecture::Stack stack_; /// tick count value for waking the thread from sleeping state uint64_t sleepUntil_; /// thread's priority, 0 - lowest, UINT8_MAX - highest uint8_t priority_; /// current state of object State state_; }; } // namespace scheduler } // namespace distortos #endif // INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_ <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/kind.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file dimm.H /// @brief Encapsulation for dimms of all types /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Craig Hamilton <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: HB:FSP #ifndef _MSS_DIMM_H_ #define _MSS_DIMM_H_ #include <fapi2.H> #include <mss_attribute_accessors.H> #include "../utils/c_str.H" namespace mss { namespace dimm { /// /// @class mss::dimm::kind /// @brief A class containing information about a dimm like ranks, density, configuration - what kind of dimm is it? /// class kind { public: kind(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target): iv_target(i_target) { FAPI_TRY( mss::eff_dram_gen(i_target, iv_dram_generation) ); FAPI_TRY( mss::eff_dimm_type(i_target, iv_dimm_type) ); FAPI_TRY( mss::eff_dram_density(i_target, iv_dram_density) ); FAPI_TRY( mss::eff_dram_width(i_target, iv_dram_width) ); FAPI_TRY( mss::eff_num_master_ranks_per_dimm(i_target, iv_master_ranks) ); FAPI_TRY( mss::eff_dram_row_bits(i_target, iv_rows) ); FAPI_TRY( mss::eff_dimm_size(i_target, iv_size) ); // TK: Attribute for slave ranks. iv_slave_ranks = 0; fapi_try_exit: // Not 100% sure what to do here ... FAPI_ERR("error initializing DIMM structure: %s 0x%016lx", mss::c_str(i_target), uint64_t(fapi2::current_err)); } const fapi2::Target<fapi2::TARGET_TYPE_DIMM> iv_target; uint8_t iv_master_ranks; uint8_t iv_slave_ranks; uint8_t iv_dram_density; uint8_t iv_dram_width; uint8_t iv_dram_generation; uint8_t iv_dimm_type; uint8_t iv_rows; uint8_t iv_size; }; } } #endif <commit_msg>Change DIMM_SIZE from 8 bits to 32 bits<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/kind.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file dimm.H /// @brief Encapsulation for dimms of all types /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Craig Hamilton <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: HB:FSP #ifndef _MSS_DIMM_H_ #define _MSS_DIMM_H_ #include <fapi2.H> #include <mss_attribute_accessors.H> #include "../utils/c_str.H" namespace mss { namespace dimm { /// /// @class mss::dimm::kind /// @brief A class containing information about a dimm like ranks, density, configuration - what kind of dimm is it? /// class kind { public: kind(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target): iv_target(i_target) { FAPI_TRY( mss::eff_dram_gen(i_target, iv_dram_generation) ); FAPI_TRY( mss::eff_dimm_type(i_target, iv_dimm_type) ); FAPI_TRY( mss::eff_dram_density(i_target, iv_dram_density) ); FAPI_TRY( mss::eff_dram_width(i_target, iv_dram_width) ); FAPI_TRY( mss::eff_num_master_ranks_per_dimm(i_target, iv_master_ranks) ); FAPI_TRY( mss::eff_dram_row_bits(i_target, iv_rows) ); FAPI_TRY( mss::eff_dimm_size(i_target, iv_size) ); // TK: Attribute for slave ranks. iv_slave_ranks = 0; fapi_try_exit: // Not 100% sure what to do here ... FAPI_ERR("error initializing DIMM structure: %s 0x%016lx", mss::c_str(i_target), uint64_t(fapi2::current_err)); } const fapi2::Target<fapi2::TARGET_TYPE_DIMM> iv_target; uint8_t iv_master_ranks; uint8_t iv_slave_ranks; uint8_t iv_dram_density; uint8_t iv_dram_width; uint8_t iv_dram_generation; uint8_t iv_dimm_type; uint8_t iv_rows; uint32_t iv_size; }; } } #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: eschesdo.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2004-04-02 14:08:26 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _ESCHESDO_HXX #define _ESCHESDO_HXX #ifndef _SVX_ESCHEREX_HXX #include "escherex.hxx" #endif #ifndef _SVX_UNOWPAGE_HXX //autogen wg. SvxDrawPage #include "unopage.hxx" #endif #ifndef _SV_MAPMOD_HXX //autogen wg. MapMode #include <vcl/mapmod.hxx> #endif // =================================================================== // fractions of Draw PPTWriter etc. enum ImplEESdrPageType { NORMAL = 0, MASTER = 1, NOTICE = 2, UNDEFINED = 3 }; class ImplEESdrWriter; class ImplEscherExSdr; class ImplEESdrObject { ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > mXShape; // XTextRef mXText; // TextRef des globalen Text ::com::sun::star::uno::Any mAny; Rectangle maRect; String mType; UINT32 mnShapeId; UINT32 mnTextSize; INT32 mnAngle; BOOL mbValid : 1; BOOL mbPresObj : 1; BOOL mbEmptyPresObj : 1; void Init( ImplEESdrWriter& rEx ); public: ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > mXPropSet; ImplEESdrObject( ImplEscherExSdr& rEx, const SdrObject& rObj ); ImplEESdrObject( ImplEESdrWriter& rEx, const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >& rShape ); ~ImplEESdrObject(); BOOL ImplGetPropertyValue( const sal_Unicode* pString ); INT32 ImplGetInt32PropertyValue( const sal_Unicode* pStr, UINT32 nDef = 0 ) { return ImplGetPropertyValue( pStr ) ? *(INT32*)mAny.getValue() : nDef; } const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >& GetShapeRef() const { return mXShape; } const ::com::sun::star::uno::Any& GetUsrAny() const { return mAny; } const String& GetType() const { return mType; } void SetType( const String& rS ) { mType = rS; } const Rectangle& GetRect() const { return maRect; } void SetRect( const Point& rPos, const Size& rSz ); void SetRect( const Rectangle& rRect ) { maRect = rRect; } INT32 GetAngle() const { return mnAngle; } void SetAngle( INT32 nVal ) { mnAngle = nVal; } UINT32 GetTextSize() const { return mnTextSize; } BOOL IsValid() const { return mbValid; } BOOL IsPresObj() const { return mbPresObj; } BOOL IsEmptyPresObj() const { return mbEmptyPresObj; } UINT32 GetShapeId() const { return mnShapeId; } void SetShapeId( UINT32 nVal ) { mnShapeId = nVal; } const SdrObject* GetSdrObject() const; UINT32 ImplGetText(); BOOL ImplHasText() const; }; // ------------------------------------------------------------------- // fractions of the Draw PPTWriter class EscherEx; namespace com { namespace sun { namespace star { namespace drawing { class XDrawPage; class XShape; } namespace task { class XStatusIndicator; } }}} class EscherExHostAppData; class Polygon; class ImplEESdrWriter { protected: EscherEx* mpEscherEx; BOOL mbStatus; UINT32 mnStatMaxValue; MapMode maMapModeSrc; MapMode maMapModeDest; ::com::sun::star::uno::Reference< ::com::sun::star::task::XStatusIndicator > mXStatusIndicator; ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage > mXDrawPage; ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > mXShapes; BOOL mbStatusIndicator; UINT32 mnPagesWritten; UINT32 mnShapeMasterTitle; UINT32 mnShapeMasterBody; SvStream* mpPicStrm; // own extensions EscherExHostAppData* mpHostAppData; // per page values UINT32 mnIndices; UINT32 mnOutlinerCount; UINT32 mnPrevTextStyle; UINT16 mnEffectCount; BOOL mbIsTitlePossible; ImplEESdrWriter( EscherEx& rEx ); BOOL ImplInitPageValues(); void ImplWritePage( EscherSolverContainer& rSolver, ImplEESdrPageType ePageType, BOOL bBackGround = FALSE ); UINT32 ImplWriteShape( ImplEESdrObject& rObj, EscherSolverContainer& rSolver, ImplEESdrPageType ePageType ); // returns ShapeID void ImplFlipBoundingBox( ImplEESdrObject& rObj, EscherPropertyContainer& rPropOpt, const Point& rRefPoint ); BOOL ImplGetText( ImplEESdrObject& rObj ); void ImplWriteAdditionalText( ImplEESdrObject& rObj, const Point& rTextRefPoint ); UINT32 ImplEnterAdditionalTextGroup( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >& rShape, const Rectangle* pBoundRect = NULL ); public: Point ImplMapPoint( const Point& rPoint ); Size ImplMapSize( const Size& rSize ); EscherExHostAppData* ImplGetHostData() { return mpHostAppData; } void MapRect(ImplEESdrObject& rObj); }; // =================================================================== class SdrObject; class SdrPage; class ImplEscherExSdr : public ImplEESdrWriter { private: const SdrPage* mpSdrPage; EscherSolverContainer* mpSolverContainer; public: ImplEscherExSdr( EscherEx& rEx ); virtual ~ImplEscherExSdr(); SvxDrawPage* ImplInitPage( const SdrPage& rPage ); void ImplWriteCurrentPage(); UINT32 ImplWriteTheShape( ImplEESdrObject& rObj ); void ImplExitPage(); void ImplFlushSolverContainer(); }; #endif // _ESCHESDO_HXX <commit_msg>INTEGRATION: CWS sj15 (1.8.552); FILE MERGED 2005/02/03 14:28:12 sj 1.8.552.1: #109646# refpoint property is no longer available<commit_after>/************************************************************************* * * $RCSfile: eschesdo.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: vg $ $Date: 2005-02-21 16:20:05 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _ESCHESDO_HXX #define _ESCHESDO_HXX #ifndef _SVX_ESCHEREX_HXX #include "escherex.hxx" #endif #ifndef _SVX_UNOWPAGE_HXX //autogen wg. SvxDrawPage #include "unopage.hxx" #endif #ifndef _SV_MAPMOD_HXX //autogen wg. MapMode #include <vcl/mapmod.hxx> #endif // =================================================================== // fractions of Draw PPTWriter etc. enum ImplEESdrPageType { NORMAL = 0, MASTER = 1, NOTICE = 2, UNDEFINED = 3 }; class ImplEESdrWriter; class ImplEscherExSdr; class ImplEESdrObject { ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape > mXShape; // XTextRef mXText; // TextRef des globalen Text ::com::sun::star::uno::Any mAny; Rectangle maRect; String mType; UINT32 mnShapeId; UINT32 mnTextSize; INT32 mnAngle; BOOL mbValid : 1; BOOL mbPresObj : 1; BOOL mbEmptyPresObj : 1; void Init( ImplEESdrWriter& rEx ); public: ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > mXPropSet; ImplEESdrObject( ImplEscherExSdr& rEx, const SdrObject& rObj ); ImplEESdrObject( ImplEESdrWriter& rEx, const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >& rShape ); ~ImplEESdrObject(); BOOL ImplGetPropertyValue( const sal_Unicode* pString ); INT32 ImplGetInt32PropertyValue( const sal_Unicode* pStr, UINT32 nDef = 0 ) { return ImplGetPropertyValue( pStr ) ? *(INT32*)mAny.getValue() : nDef; } const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >& GetShapeRef() const { return mXShape; } const ::com::sun::star::uno::Any& GetUsrAny() const { return mAny; } const String& GetType() const { return mType; } void SetType( const String& rS ) { mType = rS; } const Rectangle& GetRect() const { return maRect; } void SetRect( const Point& rPos, const Size& rSz ); void SetRect( const Rectangle& rRect ) { maRect = rRect; } INT32 GetAngle() const { return mnAngle; } void SetAngle( INT32 nVal ) { mnAngle = nVal; } UINT32 GetTextSize() const { return mnTextSize; } BOOL IsValid() const { return mbValid; } BOOL IsPresObj() const { return mbPresObj; } BOOL IsEmptyPresObj() const { return mbEmptyPresObj; } UINT32 GetShapeId() const { return mnShapeId; } void SetShapeId( UINT32 nVal ) { mnShapeId = nVal; } const SdrObject* GetSdrObject() const; UINT32 ImplGetText(); BOOL ImplHasText() const; }; // ------------------------------------------------------------------- // fractions of the Draw PPTWriter class EscherEx; namespace com { namespace sun { namespace star { namespace drawing { class XDrawPage; class XShape; } namespace task { class XStatusIndicator; } }}} class EscherExHostAppData; class Polygon; class ImplEESdrWriter { protected: EscherEx* mpEscherEx; BOOL mbStatus; UINT32 mnStatMaxValue; MapMode maMapModeSrc; MapMode maMapModeDest; ::com::sun::star::uno::Reference< ::com::sun::star::task::XStatusIndicator > mXStatusIndicator; ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XDrawPage > mXDrawPage; ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > mXShapes; BOOL mbStatusIndicator; UINT32 mnPagesWritten; UINT32 mnShapeMasterTitle; UINT32 mnShapeMasterBody; SvStream* mpPicStrm; // own extensions EscherExHostAppData* mpHostAppData; // per page values UINT32 mnIndices; UINT32 mnOutlinerCount; UINT32 mnPrevTextStyle; UINT16 mnEffectCount; BOOL mbIsTitlePossible; ImplEESdrWriter( EscherEx& rEx ); BOOL ImplInitPageValues(); void ImplWritePage( EscherSolverContainer& rSolver, ImplEESdrPageType ePageType, BOOL bBackGround = FALSE ); UINT32 ImplWriteShape( ImplEESdrObject& rObj, EscherSolverContainer& rSolver, ImplEESdrPageType ePageType ); // returns ShapeID void ImplFlipBoundingBox( ImplEESdrObject& rObj, EscherPropertyContainer& rPropOpt ); BOOL ImplGetText( ImplEESdrObject& rObj ); void ImplWriteAdditionalText( ImplEESdrObject& rObj, const Point& rTextRefPoint ); UINT32 ImplEnterAdditionalTextGroup( const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape >& rShape, const Rectangle* pBoundRect = NULL ); public: Point ImplMapPoint( const Point& rPoint ); Size ImplMapSize( const Size& rSize ); EscherExHostAppData* ImplGetHostData() { return mpHostAppData; } void MapRect(ImplEESdrObject& rObj); }; // =================================================================== class SdrObject; class SdrPage; class ImplEscherExSdr : public ImplEESdrWriter { private: const SdrPage* mpSdrPage; EscherSolverContainer* mpSolverContainer; public: ImplEscherExSdr( EscherEx& rEx ); virtual ~ImplEscherExSdr(); SvxDrawPage* ImplInitPage( const SdrPage& rPage ); void ImplWriteCurrentPage(); UINT32 ImplWriteTheShape( ImplEESdrObject& rObj ); void ImplExitPage(); void ImplFlushSolverContainer(); }; #endif // _ESCHESDO_HXX <|endoftext|>
<commit_before>#ifndef _VOLTAGE_TABLE_ #define _VOLTAGE_TABLE_ #include <cmath> #include <vector> using std::vector; // The base class for a voltage table corresponding to a processor model class VoltageTable { public: VoltageTable(const vector<double> &, double nominalVol); virtual ~VoltageTable() {} virtual double VoltageCurrentRelation(double targetVol, double nominalCur) const; virtual double VoltageFrequencyRelation(double targetVol, double nominalLen) const; const vector<double> &getVoltageTable() const { return m_voltageTable; } double GetNominalVoltage() const { return m_nominalVol; } private: vector<double> m_voltageTable; double m_nominalVol; }; class TaskVoltageTable { public: TaskVoltageTable(const VoltageTable &vt, double nomCur, double nomLen); double getVoltage(size_t level) const { return m_VCLTable[level].v; } double getNominalVoltage() const { return m_nominalVoltage; } double getCurrent(size_t level) const { return m_VCLTable[level].c; } double getCurrent(double voltage) const; int getScaledCeilLength(size_t level, int scale) const { return ceil(scale*m_VCLTable[level].l); } int getScaledCeilLength(double voltage, int scale) const; private: size_t getVoltageLevel(double v) const; private: struct VolCurLenEntry { double v; double c; double l; }; vector<VolCurLenEntry> m_VCLTable; vector<double> m_voltageTable; double m_nominalCurrent; double m_nominalLength; double m_nominalVoltage; }; const size_t syntheticVoltageLevel = 5; const double syntheticVoltageTable[syntheticVoltageLevel] = {0.8, 0.9, 1.0, 1.1, 1.2}; extern const VoltageTable syntheticCPUVoltageTable; extern const TaskVoltageTable idleTaskVoltageTable; #endif <commit_msg>Added one more interface in TaskVoltageTable class<commit_after>#ifndef _VOLTAGE_TABLE_ #define _VOLTAGE_TABLE_ #include <cmath> #include <vector> using std::vector; // The base class for a voltage table corresponding to a processor model class VoltageTable { public: VoltageTable(const vector<double> &, double nominalVol); virtual ~VoltageTable() {} virtual double VoltageCurrentRelation(double targetVol, double nominalCur) const; virtual double VoltageFrequencyRelation(double targetVol, double nominalLen) const; const vector<double> &getVoltageTable() const { return m_voltageTable; } double GetNominalVoltage() const { return m_nominalVol; } private: vector<double> m_voltageTable; double m_nominalVol; }; class TaskVoltageTable { public: TaskVoltageTable(const VoltageTable &vt, double nomCur, double nomLen); double getVoltage(size_t level) const { return m_VCLTable[level].v; } double getNominalVoltage() const { return m_nominalVoltage; } double getCurrent(size_t level) const { return m_VCLTable[level].c; } double getCurrent(double voltage) const; int getScaledCeilLength(size_t level, int scale) const { return ceil(scale*m_VCLTable[level].l); } int getScaledCeilLength(double voltage, int scale) const; const vector<double> &getVoltageTable() const { return m_voltageTable; } private: size_t getVoltageLevel(double v) const; private: struct VolCurLenEntry { double v; double c; double l; }; vector<VolCurLenEntry> m_VCLTable; vector<double> m_voltageTable; double m_nominalCurrent; double m_nominalLength; double m_nominalVoltage; }; const size_t syntheticVoltageLevel = 5; const double syntheticVoltageTable[syntheticVoltageLevel] = {0.8, 0.9, 1.0, 1.1, 1.2}; extern const VoltageTable syntheticCPUVoltageTable; extern const TaskVoltageTable idleTaskVoltageTable; #endif <|endoftext|>
<commit_before>#include <time.h> #include <cassert> #include <openssl/sha.h> #include <openssl/hmac.h> #include <opkele/data.h> #include <opkele/basic_op.h> #include <opkele/exception.h> #include <opkele/util.h> #include <opkele/uris.h> namespace opkele { void basic_OP::reset_vars() { assoc.reset(); return_to.clear(); realm.clear(); claimed_id.clear(); identity.clear(); invalidate_handle.clear(); } bool basic_OP::has_return_to() const { return !return_to.empty(); } const string& basic_OP::get_return_to() const { if(return_to.empty()) throw no_return_to(OPKELE_CP_ "No return_to URL provided with request"); return return_to; } const string& basic_OP::get_realm() const { assert(!realm.empty()); return realm; } bool basic_OP::has_identity() const { return !identity.empty(); } const string& basic_OP::get_claimed_id() const { if(claimed_id.empty()) throw non_identity(OPKELE_CP_ "attempting to retrieve claimed_id of non-identity related request"); assert(!identity.empty()); return claimed_id; } const string& basic_OP::get_identity() const { if(identity.empty()) throw non_identity(OPKELE_CP_ "attempting to retrieve identity of non-identity related request"); assert(!claimed_id.empty()); return identity; } bool basic_OP::is_id_select() const { return identity==IDURI_SELECT20; } void basic_OP::select_identity(const string& c,const string& i) { claimed_id = c; identity = i; } void basic_OP::set_claimed_id(const string& c) { claimed_id = c; } basic_openid_message& basic_OP::associate( basic_openid_message& oum, const basic_openid_message& inm) try { assert(inm.get_field("mode")=="associate"); util::dh_t dh; util::bignum_t c_pub; unsigned char key_digest[SHA256_DIGEST_LENGTH]; size_t d_len = 0; string sts = inm.get_field("session_type"); string ats = inm.get_field("assoc_type"); if(sts=="DH-SHA1" || sts=="DH-SHA256") { if(!(dh = DH_new())) throw exception_openssl(OPKELE_CP_ "failed to DH_new()"); c_pub = util::base64_to_bignum(inm.get_field("dh_consumer_public")); try { dh->p = util::base64_to_bignum(inm.get_field("dh_modulus")); }catch(failed_lookup&) { dh->p = util::dec_to_bignum(data::_default_p); } try { dh->g = util::base64_to_bignum(inm.get_field("dh_gen")); }catch(failed_lookup&) { dh->g = util::dec_to_bignum(data::_default_g); } if(!DH_generate_key(dh)) throw exception_openssl(OPKELE_CP_ "failed to DH_generate_key()"); vector<unsigned char> ck(DH_size(dh)+1); unsigned char *ckptr = &(ck.front())+1; int cklen = DH_compute_key(ckptr,c_pub,dh); if(cklen<0) throw exception_openssl(OPKELE_CP_ "failed to DH_compute_key()"); if(cklen && (*ckptr)&0x80) { (*(--ckptr)) = 0; ++cklen; } if(sts=="DH-SHA1") { SHA1(ckptr,cklen,key_digest); d_len = SHA_DIGEST_LENGTH; }else if(sts=="DH-SHA256") { SHA256(ckptr,cklen,key_digest); d_len = SHA256_DIGEST_LENGTH; }else throw internal_error(OPKELE_CP_ "I thought I knew the session type"); }else throw unsupported(OPKELE_CP_ "Unsupported session_type"); assoc_t a; if(ats=="HMAC-SHA1") a = alloc_assoc(ats,SHA_DIGEST_LENGTH,true); else if(ats=="HMAC-SHA256") a = alloc_assoc(ats,SHA256_DIGEST_LENGTH,true); else throw unsupported(OPKELE_CP_ "Unsupported assoc_type"); oum.reset_fields(); oum.set_field("ns",OIURI_OPENID20); oum.set_field("assoc_type",a->assoc_type()); oum.set_field("assoc_handle",a->handle()); oum.set_field("expires_in",util::long_to_string(assoc->expires_in())); secret_t secret = a->secret(); if(sts=="DH-SHA1" || sts=="DH-SHA256") { if(d_len != secret.size()) throw bad_input(OPKELE_CP_ "Association secret and session MAC are not of the same size"); oum.set_field("session_type",sts); oum.set_field("dh_server_public",util::bignum_to_base64(dh->pub_key)); string b64; secret.enxor_to_base64(key_digest,b64); oum.set_field("enc_mac_key",b64); }else /* TODO: support cleartext over encrypted connection */ throw unsupported(OPKELE_CP_ "Unsupported session type"); return oum; } catch(unsupported& u) { oum.reset_fields(); oum.set_field("ns",OIURI_OPENID20); oum.set_field("error",u.what()); oum.set_field("error_code","unsupported-type"); oum.set_field("session_type","DH-SHA256"); oum.set_field("assoc_type","HMAC-SHA256"); return oum; } void basic_OP::checkid_(const basic_openid_message& inm, extension_t *ext) { reset_vars(); string modestr = inm.get_field("mode"); if(modestr=="checkid_setup") mode = mode_checkid_setup; else if(modestr=="checkid_immediate") mode = mode_checkid_immediate; else throw bad_input(OPKELE_CP_ "Invalid checkid_* mode"); try { assoc = retrieve_assoc(invalidate_handle=inm.get_field("assoc_handle")); invalidate_handle.clear(); }catch(failed_lookup&) { } try { openid2 = (inm.get_field("ns")==OIURI_OPENID20); }catch(failed_lookup&) { openid2 = false; } try { return_to = inm.get_field("return_to"); }catch(failed_lookup&) { } if(openid2) { try { realm = inm.get_field("realm"); }catch(failed_lookup&) { try { realm = inm.get_field("trust_root"); }catch(failed_lookup&) { if(return_to.empty()) throw bad_input(OPKELE_CP_ "Both realm and return_to are unset"); realm = return_to; } } }else{ try { realm = inm.get_field("trust_root"); }catch(failed_lookup&) { if(return_to.empty()) throw bad_input(OPKELE_CP_ "Both realm and return_to are unset"); realm = return_to; } } try { identity = inm.get_field("identity"); try { claimed_id = inm.get_field("claimed_id"); }catch(failed_lookup&) { if(openid2) throw bad_input(OPKELE_CP_ "claimed_id and identity must be either both present or both absent"); claimed_id = identity; } }catch(failed_lookup&) { if(openid2 && inm.has_field("claimed_id")) throw bad_input(OPKELE_CP_ "claimed_id and identity must be either both present or both absent"); } verify_return_to(); if(ext) ext->op_checkid_hook(inm); } basic_openid_message& basic_OP::id_res(basic_openid_message& om, extension_t *ext) { assert(!return_to.empty()); assert(!is_id_select()); if(!assoc) { assoc = alloc_assoc("HMAC-SHA256",SHA256_DIGEST_LENGTH,true); } time_t now = time(0); struct tm gmt; gmtime_r(&now,&gmt); char w3timestr[24]; if(!strftime(w3timestr,sizeof(w3timestr),"%Y-%m-%dT%H:%M:%SZ",&gmt)) throw failed_conversion(OPKELE_CP_ "Failed to build time string for nonce" ); om.set_field("ns",OIURI_OPENID20); om.set_field("mode","id_res"); om.set_field("op_endpoint",get_op_endpoint()); string ats = "ns,mode,op_endpoint,return_to,response_nonce," "assoc_handle,signed"; if(!identity.empty()) { om.set_field("identity",identity); om.set_field("claimed_id",claimed_id); ats += ",identity,claimed_id"; } om.set_field("return_to",return_to); string nonce = w3timestr; om.set_field("response_nonce",alloc_nonce(nonce)); if(!invalidate_handle.empty()) { om.set_field("invalidate_handle",invalidate_handle); ats += ",invalidate_handle"; } om.set_field("assoc_handle",assoc->handle()); om.add_to_signed(ats); if(ext) ext->op_id_res_hook(om); om.set_field("sig",util::base64_signature(assoc,om)); return om; } basic_openid_message& basic_OP::cancel(basic_openid_message& om) { assert(!return_to.empty()); om.set_field("ns",OIURI_OPENID20); om.set_field("mode","cancel"); return om; } basic_openid_message& basic_OP::error(basic_openid_message& om, const string& err,const string& contact, const string& reference ) { assert(!return_to.empty()); om.set_field("ns",OIURI_OPENID20); om.set_field("mode","error"); om.set_field("error",err); if(!contact.empty()) om.set_field("contact",contact); if(!reference.empty()) om.set_field("reference",reference); return om; } basic_openid_message& basic_OP::setup_needed( basic_openid_message& oum,const basic_openid_message& inm) { assert(mode==mode_checkid_immediate); assert(!return_to.empty()); if(openid2) { oum.set_field("ns",OIURI_OPENID20); oum.set_field("mode","setup_needed"); }else{ oum.set_field("mode","id_res"); static const string setupmode = "checkid_setup"; oum.set_field("user_setup_url", util::change_mode_message_proxy(inm,setupmode) .append_query(get_op_endpoint())); } return oum; } basic_openid_message& basic_OP::check_authentication( basic_openid_message& oum, const basic_openid_message& inm) try { assert(inm.get_field("mode")=="check_authentication"); oum.reset_fields(); oum.set_field("ns",OIURI_OPENID20); bool o2; try { o2 = (inm.get_field("ns")==OIURI_OPENID20); }catch(failed_lookup&) { o2 = false; } string nonce; if(o2) { try { if(!check_nonce(nonce = inm.get_field("response_nonce"))) throw failed_check_authentication(OPKELE_CP_ "Invalid nonce"); }catch(failed_lookup&) { throw failed_check_authentication(OPKELE_CP_ "No nonce provided with check_authentication request"); } } try { assoc = retrieve_assoc(inm.get_field("assoc_handle")); if(!assoc->stateless()) throw failed_check_authentication(OPKELE_CP_ "Will not do check_authentication on a stateful handle"); }catch(failed_lookup&) { throw failed_check_authentication(OPKELE_CP_ "No assoc_handle or invalid assoc_handle specified with check_authentication request"); } static const string idresmode = "id_res"; try { if(util::base64_signature(assoc,util::change_mode_message_proxy(inm,idresmode))!=inm.get_field("sig")) throw failed_check_authentication(OPKELE_CP_ "Signature mismatch"); }catch(failed_lookup&) { throw failed_check_authentication(OPKELE_CP_ "failed to calculate signature"); } oum.set_field("is_valid","true"); try { string h = inm.get_field("invalidate_handle"); try { assoc_t ih = retrieve_assoc(h); }catch(invalid_handle& ih) { oum.set_field("invalidate_handle",h); }catch(failed_lookup& ih) { oum.set_field("invalidate_handle",h); } }catch(failed_lookup&) { } if(o2) { assert(!nonce.empty()); invalidate_nonce(nonce); } return oum; }catch(failed_check_authentication& ) { oum.set_field("is_valid","false"); return oum; } void basic_OP::verify_return_to() { if(realm.find('#')!=string::npos) throw opkele::bad_realm(OPKELE_CP_ "authentication realm contains URI fragment"); if(!util::uri_matches_realm(return_to,realm)) throw bad_return_to(OPKELE_CP_ "return_to URL doesn't match realm"); } } <commit_msg>OP fixes<commit_after>#include <time.h> #include <cassert> #include <openssl/sha.h> #include <openssl/hmac.h> #include <opkele/data.h> #include <opkele/basic_op.h> #include <opkele/exception.h> #include <opkele/util.h> #include <opkele/uris.h> namespace opkele { void basic_OP::reset_vars() { assoc.reset(); return_to.clear(); realm.clear(); claimed_id.clear(); identity.clear(); invalidate_handle.clear(); } bool basic_OP::has_return_to() const { return !return_to.empty(); } const string& basic_OP::get_return_to() const { if(return_to.empty()) throw no_return_to(OPKELE_CP_ "No return_to URL provided with request"); return return_to; } const string& basic_OP::get_realm() const { assert(!realm.empty()); return realm; } bool basic_OP::has_identity() const { return !identity.empty(); } const string& basic_OP::get_claimed_id() const { if(claimed_id.empty()) throw non_identity(OPKELE_CP_ "attempting to retrieve claimed_id of non-identity related request"); assert(!identity.empty()); return claimed_id; } const string& basic_OP::get_identity() const { if(identity.empty()) throw non_identity(OPKELE_CP_ "attempting to retrieve identity of non-identity related request"); assert(!claimed_id.empty()); return identity; } bool basic_OP::is_id_select() const { return identity==IDURI_SELECT20; } void basic_OP::select_identity(const string& c,const string& i) { claimed_id = c; identity = i; } void basic_OP::set_claimed_id(const string& c) { claimed_id = c; } basic_openid_message& basic_OP::associate( basic_openid_message& oum, const basic_openid_message& inm) try { assert(inm.get_field("mode")=="associate"); util::dh_t dh; util::bignum_t c_pub; unsigned char key_digest[SHA256_DIGEST_LENGTH]; size_t d_len = 0; string sts = inm.get_field("session_type"); string ats = inm.get_field("assoc_type"); if(sts=="DH-SHA1" || sts=="DH-SHA256") { if(!(dh = DH_new())) throw exception_openssl(OPKELE_CP_ "failed to DH_new()"); c_pub = util::base64_to_bignum(inm.get_field("dh_consumer_public")); try { dh->p = util::base64_to_bignum(inm.get_field("dh_modulus")); }catch(failed_lookup&) { dh->p = util::dec_to_bignum(data::_default_p); } try { dh->g = util::base64_to_bignum(inm.get_field("dh_gen")); }catch(failed_lookup&) { dh->g = util::dec_to_bignum(data::_default_g); } if(!DH_generate_key(dh)) throw exception_openssl(OPKELE_CP_ "failed to DH_generate_key()"); vector<unsigned char> ck(DH_size(dh)+1); unsigned char *ckptr = &(ck.front())+1; int cklen = DH_compute_key(ckptr,c_pub,dh); if(cklen<0) throw exception_openssl(OPKELE_CP_ "failed to DH_compute_key()"); if(cklen && (*ckptr)&0x80) { (*(--ckptr)) = 0; ++cklen; } if(sts=="DH-SHA1") { SHA1(ckptr,cklen,key_digest); d_len = SHA_DIGEST_LENGTH; }else if(sts=="DH-SHA256") { SHA256(ckptr,cklen,key_digest); d_len = SHA256_DIGEST_LENGTH; }else throw internal_error(OPKELE_CP_ "I thought I knew the session type"); }else throw unsupported(OPKELE_CP_ "Unsupported session_type"); assoc_t a; if(ats=="HMAC-SHA1") a = alloc_assoc(ats,SHA_DIGEST_LENGTH,false); else if(ats=="HMAC-SHA256") a = alloc_assoc(ats,SHA256_DIGEST_LENGTH,false); else throw unsupported(OPKELE_CP_ "Unsupported assoc_type"); oum.reset_fields(); oum.set_field("ns",OIURI_OPENID20); oum.set_field("assoc_type",a->assoc_type()); oum.set_field("assoc_handle",a->handle()); oum.set_field("expires_in",util::long_to_string(a->expires_in())); secret_t secret = a->secret(); if(sts=="DH-SHA1" || sts=="DH-SHA256") { if(d_len != secret.size()) throw bad_input(OPKELE_CP_ "Association secret and session MAC are not of the same size"); oum.set_field("session_type",sts); oum.set_field("dh_server_public",util::bignum_to_base64(dh->pub_key)); string b64; secret.enxor_to_base64(key_digest,b64); oum.set_field("enc_mac_key",b64); }else /* TODO: support cleartext over encrypted connection */ throw unsupported(OPKELE_CP_ "Unsupported session type"); return oum; } catch(unsupported& u) { oum.reset_fields(); oum.set_field("ns",OIURI_OPENID20); oum.set_field("error",u.what()); oum.set_field("error_code","unsupported-type"); oum.set_field("session_type","DH-SHA256"); oum.set_field("assoc_type","HMAC-SHA256"); return oum; } void basic_OP::checkid_(const basic_openid_message& inm, extension_t *ext) { reset_vars(); string modestr = inm.get_field("mode"); if(modestr=="checkid_setup") mode = mode_checkid_setup; else if(modestr=="checkid_immediate") mode = mode_checkid_immediate; else throw bad_input(OPKELE_CP_ "Invalid checkid_* mode"); try { assoc = retrieve_assoc(invalidate_handle=inm.get_field("assoc_handle")); invalidate_handle.clear(); }catch(failed_lookup&) { } try { openid2 = (inm.get_field("ns")==OIURI_OPENID20); }catch(failed_lookup&) { openid2 = false; } try { return_to = inm.get_field("return_to"); }catch(failed_lookup&) { } if(openid2) { try { realm = inm.get_field("realm"); }catch(failed_lookup&) { try { realm = inm.get_field("trust_root"); }catch(failed_lookup&) { if(return_to.empty()) throw bad_input(OPKELE_CP_ "Both realm and return_to are unset"); realm = return_to; } } }else{ try { realm = inm.get_field("trust_root"); }catch(failed_lookup&) { if(return_to.empty()) throw bad_input(OPKELE_CP_ "Both realm and return_to are unset"); realm = return_to; } } try { identity = inm.get_field("identity"); try { claimed_id = inm.get_field("claimed_id"); }catch(failed_lookup&) { if(openid2) throw bad_input(OPKELE_CP_ "claimed_id and identity must be either both present or both absent"); claimed_id = identity; } }catch(failed_lookup&) { if(openid2 && inm.has_field("claimed_id")) throw bad_input(OPKELE_CP_ "claimed_id and identity must be either both present or both absent"); } verify_return_to(); if(ext) ext->op_checkid_hook(inm); } basic_openid_message& basic_OP::id_res(basic_openid_message& om, extension_t *ext) { assert(!return_to.empty()); assert(!is_id_select()); if(!assoc) { assoc = alloc_assoc("HMAC-SHA256",SHA256_DIGEST_LENGTH,true); } time_t now = time(0); struct tm gmt; gmtime_r(&now,&gmt); char w3timestr[24]; if(!strftime(w3timestr,sizeof(w3timestr),"%Y-%m-%dT%H:%M:%SZ",&gmt)) throw failed_conversion(OPKELE_CP_ "Failed to build time string for nonce" ); om.set_field("ns",OIURI_OPENID20); om.set_field("mode","id_res"); om.set_field("op_endpoint",get_op_endpoint()); string ats = "ns,mode,op_endpoint,return_to,response_nonce," "assoc_handle,signed"; if(!identity.empty()) { om.set_field("identity",identity); om.set_field("claimed_id",claimed_id); ats += ",identity,claimed_id"; } om.set_field("return_to",return_to); string nonce = w3timestr; om.set_field("response_nonce",alloc_nonce(nonce)); if(!invalidate_handle.empty()) { om.set_field("invalidate_handle",invalidate_handle); ats += ",invalidate_handle"; } om.set_field("assoc_handle",assoc->handle()); om.add_to_signed(ats); if(ext) ext->op_id_res_hook(om); om.set_field("sig",util::base64_signature(assoc,om)); return om; } basic_openid_message& basic_OP::cancel(basic_openid_message& om) { assert(!return_to.empty()); om.set_field("ns",OIURI_OPENID20); om.set_field("mode","cancel"); return om; } basic_openid_message& basic_OP::error(basic_openid_message& om, const string& err,const string& contact, const string& reference ) { assert(!return_to.empty()); om.set_field("ns",OIURI_OPENID20); om.set_field("mode","error"); om.set_field("error",err); if(!contact.empty()) om.set_field("contact",contact); if(!reference.empty()) om.set_field("reference",reference); return om; } basic_openid_message& basic_OP::setup_needed( basic_openid_message& oum,const basic_openid_message& inm) { assert(mode==mode_checkid_immediate); assert(!return_to.empty()); if(openid2) { oum.set_field("ns",OIURI_OPENID20); oum.set_field("mode","setup_needed"); }else{ oum.set_field("mode","id_res"); static const string setupmode = "checkid_setup"; oum.set_field("user_setup_url", util::change_mode_message_proxy(inm,setupmode) .append_query(get_op_endpoint())); } return oum; } basic_openid_message& basic_OP::check_authentication( basic_openid_message& oum, const basic_openid_message& inm) try { assert(inm.get_field("mode")=="check_authentication"); oum.reset_fields(); oum.set_field("ns",OIURI_OPENID20); bool o2; try { o2 = (inm.get_field("ns")==OIURI_OPENID20); }catch(failed_lookup&) { o2 = false; } string nonce; if(o2) { try { if(!check_nonce(nonce = inm.get_field("response_nonce"))) throw failed_check_authentication(OPKELE_CP_ "Invalid nonce"); }catch(failed_lookup&) { throw failed_check_authentication(OPKELE_CP_ "No nonce provided with check_authentication request"); } } try { assoc = retrieve_assoc(inm.get_field("assoc_handle")); if(!assoc->stateless()) throw failed_check_authentication(OPKELE_CP_ "Will not do check_authentication on a stateful handle"); }catch(failed_lookup&) { throw failed_check_authentication(OPKELE_CP_ "No assoc_handle or invalid assoc_handle specified with check_authentication request"); } static const string idresmode = "id_res"; try { if(util::base64_signature(assoc,util::change_mode_message_proxy(inm,idresmode))!=inm.get_field("sig")) throw failed_check_authentication(OPKELE_CP_ "Signature mismatch"); }catch(failed_lookup&) { throw failed_check_authentication(OPKELE_CP_ "failed to calculate signature"); } oum.set_field("is_valid","true"); try { string h = inm.get_field("invalidate_handle"); try { assoc_t ih = retrieve_assoc(h); }catch(invalid_handle& ih) { oum.set_field("invalidate_handle",h); }catch(failed_lookup& ih) { oum.set_field("invalidate_handle",h); } }catch(failed_lookup&) { } if(o2) { assert(!nonce.empty()); invalidate_nonce(nonce); } return oum; }catch(failed_check_authentication& ) { oum.set_field("is_valid","false"); return oum; } void basic_OP::verify_return_to() { if(realm.find('#')!=string::npos) throw opkele::bad_realm(OPKELE_CP_ "authentication realm contains URI fragment"); if(!util::uri_matches_realm(return_to,realm)) throw bad_return_to(OPKELE_CP_ "return_to URL doesn't match realm"); } } <|endoftext|>
<commit_before>#ifndef _PREVIEWPAGES_HXX #define _PREVIEWPAGES_HXX // classes <Point>, <Size> and <Rectangle> #ifndef _GEN_HXX #include <tools/gen.hxx> #endif class SwPageFrm; /** data structure for a preview page in the current preview layout OD 12.12.2002 #103492# - struct <PrevwPage> @author OD */ struct PrevwPage { const SwPageFrm* pPage; bool bVisible; Size aPageSize; Point aPrevwWinPos; Point aLogicPos; Point aMapOffset; inline PrevwPage(); }; inline PrevwPage::PrevwPage() : pPage( 0 ), bVisible( false ), aPageSize( Size(0,0) ), aPrevwWinPos( Point(0,0) ), aLogicPos( Point(0,0) ), aMapOffset( Point(0,0) ) {}; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.2.2472); FILE MERGED 2008/04/01 15:57:11 thb 1.2.2472.1: #i85898# Stripping all external header guards<commit_after>#ifndef _PREVIEWPAGES_HXX #define _PREVIEWPAGES_HXX // classes <Point>, <Size> and <Rectangle> #include <tools/gen.hxx> class SwPageFrm; /** data structure for a preview page in the current preview layout OD 12.12.2002 #103492# - struct <PrevwPage> @author OD */ struct PrevwPage { const SwPageFrm* pPage; bool bVisible; Size aPageSize; Point aPrevwWinPos; Point aLogicPos; Point aMapOffset; inline PrevwPage(); }; inline PrevwPage::PrevwPage() : pPage( 0 ), bVisible( false ), aPageSize( Size(0,0) ), aPrevwWinPos( Point(0,0) ), aLogicPos( Point(0,0) ), aMapOffset( Point(0,0) ) {}; #endif <|endoftext|>
<commit_before>#include "itkCommandLineArgumentParser.h" #include "CommandLineArgumentHelper.h" #include <itksys/SystemTools.hxx> #include <sstream> #include "itkPCAImageToImageFilter.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" //------------------------------------------------------------------------------------- /** run: A macro to call a function. */ #define run(function,type,dim) \ if ( componentType == #type && Dimension == dim ) \ { \ typedef itk::Image< type, dim > OutputImageType; \ function< OutputImageType >( inputFileNames, outputDirectory, numberOfPCs ); \ supported = true; \ } //------------------------------------------------------------------------------------- /** Declare PerformPCA. */ template< class OutputImageType > void PerformPCA( const std::vector< std::string > & inputFileNames, const std::string & outputDirectory, unsigned int numberOfPCs ); /** Declare other functions. */ void PrintHelp( void ); //------------------------------------------------------------------------------------- int main( int argc, char **argv ) { /** Check arguments for help. */ if ( argc < 4 ) { PrintHelp(); return 1; } /** Create a command line argument parser. */ itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New(); parser->SetCommandLineArguments( argc, argv ); /** Get arguments. */ std::vector<std::string> inputFileNames( 0, "" ); bool retin = parser->GetCommandLineArgument( "-in", inputFileNames ); std::string base = itksys::SystemTools::GetFilenamePath( inputFileNames[ 0 ] ); if ( base != "" ) base = base + "/"; std::string outputDirectory = base; parser->GetCommandLineArgument( "-out", outputDirectory ); bool endslash = itksys::SystemTools::StringEndsWith( outputDirectory.c_str(), "/" ); if ( !endslash ) outputDirectory += "/"; unsigned int numberOfPCs = inputFileNames.size(); parser->GetCommandLineArgument( "-npc", numberOfPCs ); std::string componentType = ""; bool retpt = parser->GetCommandLineArgument( "-opct", componentType ); /** Check if the required arguments are given. */ if ( !retin ) { std::cerr << "ERROR: You should specify \"-in\"." << std::endl; return 1; } /** Check that numberOfOutputs <= numberOfInputs. */ if ( numberOfPCs > inputFileNames.size() ) { std::cerr << "ERROR: you should specify less than " << inputFileNames.size() << " output pc's." << std::endl; return 1; } /** Determine image properties. */ std::string ComponentTypeIn = "short"; std::string PixelType; //we don't use this unsigned int Dimension = 3; unsigned int NumberOfComponents = 1; std::vector<unsigned int> imagesize( Dimension, 0 ); int retgip = GetImageProperties( inputFileNames[ 0 ], PixelType, ComponentTypeIn, Dimension, NumberOfComponents, imagesize ); if ( retgip != 0 ) { return 1; } /** Check for vector images. */ if ( NumberOfComponents > 1 ) { std::cerr << "ERROR: The NumberOfComponents is larger than 1!" << std::endl; std::cerr << "Vector images are not supported." << std::endl; return 1; } /** The default output is equal to the input, but can be overridden by * specifying -pt in the command line. */ if ( !retpt ) componentType = ComponentTypeIn; /** Get rid of the possible "_" in ComponentType. */ ReplaceUnderscoreWithSpace( componentType ); /** Run the program. */ bool supported = false; try { run( PerformPCA, unsigned char, 2 ); run( PerformPCA, char, 2 ); run( PerformPCA, unsigned short, 2 ); run( PerformPCA, short, 2 ); run( PerformPCA, unsigned int, 2 ); run( PerformPCA, int, 2 ); run( PerformPCA, unsigned long, 2 ); run( PerformPCA, long, 2 ); run( PerformPCA, float, 2 ); run( PerformPCA, double, 2 ); run( PerformPCA, unsigned char, 3 ); run( PerformPCA, char, 3 ); run( PerformPCA, unsigned short, 3 ); run( PerformPCA, short, 3 ); run( PerformPCA, unsigned int, 3 ); run( PerformPCA, int, 3 ); run( PerformPCA, unsigned long, 3 ); run( PerformPCA, long, 3 ); run( PerformPCA, float, 3 ); run( PerformPCA, double, 3 ); } catch( itk::ExceptionObject &e ) { std::cerr << "Caught ITK exception: " << e << std::endl; return 1; } if ( !supported ) { std::cerr << "ERROR: this combination of pixeltype and dimension is not supported!" << std::endl; std::cerr << "pixel (component) type = " << ComponentTypeIn << " ; dimension = " << Dimension << std::endl; return 1; } /** End program. */ return 0; } // end main() /** * ******************* PerformPCA ******************* */ template< class OutputImageType > void PerformPCA( const std::vector< std::string > & inputFileNames, const std::string & outputDirectory, unsigned int numberOfPCs ) { const unsigned int Dimension = OutputImageType::ImageDimension; /** Typedefs. */ typedef itk::Image< double, Dimension > DoubleImageType; typedef itk::PCAImageToImageFilter< DoubleImageType, OutputImageType > PCAEstimatorType; typedef typename PCAEstimatorType::VectorOfDoubleType VectorOfDoubleType; typedef typename PCAEstimatorType::MatrixOfDoubleType MatrixOfDoubleType; typedef itk::ImageFileReader< DoubleImageType > ReaderType; typedef typename ReaderType::Pointer ReaderPointer; typedef itk::ImageFileWriter< OutputImageType > WriterType; typedef typename WriterType::Pointer WriterPointer; /** Get some sizes. */ unsigned int noInputs = inputFileNames.size(); /** Create the PCA estimator. */ typename PCAEstimatorType::Pointer pcaEstimator = PCAEstimatorType::New(); pcaEstimator->SetNumberOfFeatureImages( noInputs ); pcaEstimator->SetNumberOfPrincipalComponentsRequired( numberOfPCs ); /** For all inputs... */ std::vector<ReaderPointer> readers( noInputs ); for ( unsigned int i = 0; i < noInputs; ++i ) { /** Read in the input images. */ readers[ i ] = ReaderType::New(); readers[ i ]->SetFileName( inputFileNames[ i ] ); readers[ i ]->Update(); /** Setup PCA estimator. */ pcaEstimator->SetInput( i, readers[ i ]->GetOutput() ); } /** Do the PCA analysis. */ pcaEstimator->Update(); /** Get eigenvalues and vectors, and print it to screen. */ //pcaEstimator->Print( std::cout ); VectorOfDoubleType vec = pcaEstimator->GetEigenValues(); MatrixOfDoubleType mat = pcaEstimator->GetEigenVectors(); std::cout << "Eigenvalues: " << std::endl; for ( unsigned int i = 0; i < vec.size(); ++i ) { std::cout << vec[ i ] << " "; } std::cout << std::endl; std::cout << "Eigenvectors: " << std::endl; for ( unsigned int i = 0; i < vec.size(); ++i ) { std::cout << mat.get_row( i ) << std::endl; } /** Setup and process the pipeline. */ unsigned int noo = pcaEstimator->GetNumberOfOutputs(); std::vector<WriterPointer> writers( noo ); for ( unsigned int i = 0; i < noo; ++i ) { /** Create output filename. */ std::ostringstream makeFileName( "" ); makeFileName << outputDirectory << "pc" << i << ".mhd"; /** Write principal components. */ writers[ i ] = WriterType::New(); writers[ i ]->SetFileName( makeFileName.str().c_str() ); writers[ i ]->SetInput( pcaEstimator->GetOutput( i ) ); writers[ i ]->Update(); } } // end PerformPCA() /** * ******************* PrintHelp ******************* */ void PrintHelp( void ) { std::cout << "Usage:" << std::endl << "pxpca" << std::endl; std::cout << " -in inputFilenames" << std::endl; std::cout << " [-out] outputDirectory, default equal to the inputFilename directory" << std::endl; std::cout << " [-opc] the number of principal components that you want to output, default all" << std::endl; std::cout << " [-opct] output pixel component type, default derived from the input image" << std::endl; std::cout << "Supported: 2D, 3D, (unsigned) char, (unsigned) short, (unsigned) int, (unsigned) long, float, double." << std::endl; } // end PrintHelp() <commit_msg>New style arguments for pca<commit_after>#include "itkCommandLineArgumentParser.h" #include "CommandLineArgumentHelper.h" #include <itksys/SystemTools.hxx> #include <sstream> #include "itkPCAImageToImageFilter.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" //------------------------------------------------------------------------------------- /** run: A macro to call a function. */ #define run(function,type,dim) \ if ( componentType == #type && Dimension == dim ) \ { \ typedef itk::Image< type, dim > OutputImageType; \ function< OutputImageType >( inputFileNames, outputDirectory, numberOfPCs ); \ supported = true; \ } //------------------------------------------------------------------------------------- /** Declare PerformPCA. */ template< class OutputImageType > void PerformPCA( const std::vector< std::string > & inputFileNames, const std::string & outputDirectory, unsigned int numberOfPCs ); /** Declare other functions. */ std::string PrintHelp( void ); //------------------------------------------------------------------------------------- int main( int argc, char **argv ) { /** Create a command line argument parser. */ itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New(); parser->SetCommandLineArguments( argc, argv ); parser->SetProgramHelpText(PrintHelp()); parser->MarkArgumentAsRequired( "-in", "The input filename." ); bool validateArguments = parser->CheckForRequiredArguments(); if(!validateArguments) { return EXIT_FAILURE; } /** Get arguments. */ std::vector<std::string> inputFileNames( 0, "" ); parser->GetCommandLineArgument( "-in", inputFileNames ); std::string base = itksys::SystemTools::GetFilenamePath( inputFileNames[ 0 ] ); if ( base != "" ) base = base + "/"; std::string outputDirectory = base; parser->GetCommandLineArgument( "-out", outputDirectory ); bool endslash = itksys::SystemTools::StringEndsWith( outputDirectory.c_str(), "/" ); if ( !endslash ) outputDirectory += "/"; unsigned int numberOfPCs = inputFileNames.size(); parser->GetCommandLineArgument( "-npc", numberOfPCs ); std::string componentType = ""; bool retpt = parser->GetCommandLineArgument( "-opct", componentType ); /** Check that numberOfOutputs <= numberOfInputs. */ if ( numberOfPCs > inputFileNames.size() ) { std::cerr << "ERROR: you should specify less than " << inputFileNames.size() << " output pc's." << std::endl; return 1; } /** Determine image properties. */ std::string ComponentTypeIn = "short"; std::string PixelType; //we don't use this unsigned int Dimension = 3; unsigned int NumberOfComponents = 1; std::vector<unsigned int> imagesize( Dimension, 0 ); int retgip = GetImageProperties( inputFileNames[ 0 ], PixelType, ComponentTypeIn, Dimension, NumberOfComponents, imagesize ); if ( retgip != 0 ) { return 1; } /** Check for vector images. */ if ( NumberOfComponents > 1 ) { std::cerr << "ERROR: The NumberOfComponents is larger than 1!" << std::endl; std::cerr << "Vector images are not supported." << std::endl; return 1; } /** The default output is equal to the input, but can be overridden by * specifying -pt in the command line. */ if ( !retpt ) componentType = ComponentTypeIn; /** Get rid of the possible "_" in ComponentType. */ ReplaceUnderscoreWithSpace( componentType ); /** Run the program. */ bool supported = false; try { run( PerformPCA, unsigned char, 2 ); run( PerformPCA, char, 2 ); run( PerformPCA, unsigned short, 2 ); run( PerformPCA, short, 2 ); run( PerformPCA, unsigned int, 2 ); run( PerformPCA, int, 2 ); run( PerformPCA, unsigned long, 2 ); run( PerformPCA, long, 2 ); run( PerformPCA, float, 2 ); run( PerformPCA, double, 2 ); run( PerformPCA, unsigned char, 3 ); run( PerformPCA, char, 3 ); run( PerformPCA, unsigned short, 3 ); run( PerformPCA, short, 3 ); run( PerformPCA, unsigned int, 3 ); run( PerformPCA, int, 3 ); run( PerformPCA, unsigned long, 3 ); run( PerformPCA, long, 3 ); run( PerformPCA, float, 3 ); run( PerformPCA, double, 3 ); } catch( itk::ExceptionObject &e ) { std::cerr << "Caught ITK exception: " << e << std::endl; return 1; } if ( !supported ) { std::cerr << "ERROR: this combination of pixeltype and dimension is not supported!" << std::endl; std::cerr << "pixel (component) type = " << ComponentTypeIn << " ; dimension = " << Dimension << std::endl; return 1; } /** End program. */ return 0; } // end main() /** * ******************* PerformPCA ******************* */ template< class OutputImageType > void PerformPCA( const std::vector< std::string > & inputFileNames, const std::string & outputDirectory, unsigned int numberOfPCs ) { const unsigned int Dimension = OutputImageType::ImageDimension; /** Typedefs. */ typedef itk::Image< double, Dimension > DoubleImageType; typedef itk::PCAImageToImageFilter< DoubleImageType, OutputImageType > PCAEstimatorType; typedef typename PCAEstimatorType::VectorOfDoubleType VectorOfDoubleType; typedef typename PCAEstimatorType::MatrixOfDoubleType MatrixOfDoubleType; typedef itk::ImageFileReader< DoubleImageType > ReaderType; typedef typename ReaderType::Pointer ReaderPointer; typedef itk::ImageFileWriter< OutputImageType > WriterType; typedef typename WriterType::Pointer WriterPointer; /** Get some sizes. */ unsigned int noInputs = inputFileNames.size(); /** Create the PCA estimator. */ typename PCAEstimatorType::Pointer pcaEstimator = PCAEstimatorType::New(); pcaEstimator->SetNumberOfFeatureImages( noInputs ); pcaEstimator->SetNumberOfPrincipalComponentsRequired( numberOfPCs ); /** For all inputs... */ std::vector<ReaderPointer> readers( noInputs ); for ( unsigned int i = 0; i < noInputs; ++i ) { /** Read in the input images. */ readers[ i ] = ReaderType::New(); readers[ i ]->SetFileName( inputFileNames[ i ] ); readers[ i ]->Update(); /** Setup PCA estimator. */ pcaEstimator->SetInput( i, readers[ i ]->GetOutput() ); } /** Do the PCA analysis. */ pcaEstimator->Update(); /** Get eigenvalues and vectors, and print it to screen. */ //pcaEstimator->Print( std::cout ); VectorOfDoubleType vec = pcaEstimator->GetEigenValues(); MatrixOfDoubleType mat = pcaEstimator->GetEigenVectors(); std::cout << "Eigenvalues: " << std::endl; for ( unsigned int i = 0; i < vec.size(); ++i ) { std::cout << vec[ i ] << " "; } std::cout << std::endl; std::cout << "Eigenvectors: " << std::endl; for ( unsigned int i = 0; i < vec.size(); ++i ) { std::cout << mat.get_row( i ) << std::endl; } /** Setup and process the pipeline. */ unsigned int noo = pcaEstimator->GetNumberOfOutputs(); std::vector<WriterPointer> writers( noo ); for ( unsigned int i = 0; i < noo; ++i ) { /** Create output filename. */ std::ostringstream makeFileName( "" ); makeFileName << outputDirectory << "pc" << i << ".mhd"; /** Write principal components. */ writers[ i ] = WriterType::New(); writers[ i ]->SetFileName( makeFileName.str().c_str() ); writers[ i ]->SetInput( pcaEstimator->GetOutput( i ) ); writers[ i ]->Update(); } } // end PerformPCA() /** * ******************* PrintHelp ******************* */ std::string PrintHelp( void ) { std::string helpText = "Usage: \ pxpca \ -in inputFilenames \ [-out] outputDirectory, default equal to the inputFilename directory \ [-opc] the number of principal components that you want to output, default all \ [-opct] output pixel component type, default derived from the input image \ Supported: 2D, 3D, (unsigned) char, (unsigned) short, (unsigned) int, (unsigned) long, float, double."; return helpText; } // end PrintHelp() <|endoftext|>
<commit_before>#include <babylon/engines/webgl/webgl2_shader_processor.h> #include <babylon/babylon_stl_util.h> #include <babylon/misc/string_tools.h> namespace BABYLON { WebGL2ShaderProcessor::WebGL2ShaderProcessor() { attributeProcessor = [this](const std::string& attribute, const std::unordered_map<std::string, std::string>& /*preProcessors*/, const ShaderProcessingContextPtr& /*processingContext*/) -> std::string { return _attributeProcessor(attribute); }; varyingProcessor = [this](const std::string& varying, bool isFragment, const std::unordered_map<std::string, std::string>& /*preProcessors*/, const ShaderProcessingContextPtr& /*processingContext*/) -> std::string { return _varyingProcessor(varying, isFragment); }; postProcessor = [this](const std::string& code, const std::vector<std::string>& defines, bool isFragment, const ShaderProcessingContextPtr& processingContext, ThinEngine* engine) -> std::string { return _postProcessor(code, defines, isFragment, processingContext, engine); }; } std::string WebGL2ShaderProcessor::_attributeProcessor(const std::string& attribute) { return StringTools::replace(attribute, "attribute", "in"); } std::string WebGL2ShaderProcessor::_varyingProcessor(const std::string& varying, bool isFragment) { return StringTools::replace(varying, "varying", isFragment ? "in" : "out"); } std::string WebGL2ShaderProcessor::_postProcessor( std::string code, const std::vector<std::string>& defines, bool isFragment, const ShaderProcessingContextPtr& /*processingContext*/, ThinEngine* /*engine*/) { const auto hasDrawBuffersExtension = StringTools::contains(code, "#extension.+GL_EXT_draw_buffers.+require"); // Remove extensions const std::string regex( "#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_" "frag_depth|GL_EXT_draw_buffers).+(enable|require)"); code = StringTools::regexReplace(code, regex, ""); // Replace instructions code = StringTools::regexReplace(code, "texture2D\\s*\\(", "texture("); if (isFragment) { code = StringTools::regexReplace(code, "texture2DLodEXT\\s*\\(", "textureLod("); code = StringTools::regexReplace(code, "textureCubeLodEXT\\s*\\(", "textureLod("); code = StringTools::regexReplace(code, "textureCube\\s*\\(", "texture("); code = StringTools::regexReplace(code, "gl_FragDepthEXT", "gl_FragDepth"); code = StringTools::regexReplace(code, "gl_FragColor", "glFragColor"); code = StringTools::regexReplace(code, "gl_FragData", "glFragData"); code = StringTools::regexReplace( code, R"(void\s+?main\s*\()", StringTools::printf("%s%s", (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n"), "void main(")); } else { const auto hasMultiviewExtension = stl_util::contains(defines, "#define MULTIVIEW"); if (hasMultiviewExtension) { return StringTools::printf( "#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n%s", code.c_str()); } } return code; } } // end of namespace BABYLON <commit_msg>Setting shader language<commit_after>#include <babylon/engines/webgl/webgl2_shader_processor.h> #include <babylon/babylon_stl_util.h> #include <babylon/misc/string_tools.h> namespace BABYLON { WebGL2ShaderProcessor::WebGL2ShaderProcessor() { shaderLanguage = ShaderLanguage::GLSL; attributeProcessor = [this](const std::string& attribute, const std::unordered_map<std::string, std::string>& /*preProcessors*/, const ShaderProcessingContextPtr& /*processingContext*/) -> std::string { return _attributeProcessor(attribute); }; varyingProcessor = [this](const std::string& varying, bool isFragment, const std::unordered_map<std::string, std::string>& /*preProcessors*/, const ShaderProcessingContextPtr& /*processingContext*/) -> std::string { return _varyingProcessor(varying, isFragment); }; postProcessor = [this](const std::string& code, const std::vector<std::string>& defines, bool isFragment, const ShaderProcessingContextPtr& processingContext, ThinEngine* engine) -> std::string { return _postProcessor(code, defines, isFragment, processingContext, engine); }; } std::string WebGL2ShaderProcessor::_attributeProcessor(const std::string& attribute) { return StringTools::replace(attribute, "attribute", "in"); } std::string WebGL2ShaderProcessor::_varyingProcessor(const std::string& varying, bool isFragment) { return StringTools::replace(varying, "varying", isFragment ? "in" : "out"); } std::string WebGL2ShaderProcessor::_postProcessor( std::string code, const std::vector<std::string>& defines, bool isFragment, const ShaderProcessingContextPtr& /*processingContext*/, ThinEngine* /*engine*/) { const auto hasDrawBuffersExtension = StringTools::contains(code, "#extension.+GL_EXT_draw_buffers.+require"); // Remove extensions const std::string regex( "#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_" "frag_depth|GL_EXT_draw_buffers).+(enable|require)"); code = StringTools::regexReplace(code, regex, ""); // Replace instructions code = StringTools::regexReplace(code, "texture2D\\s*\\(", "texture("); if (isFragment) { code = StringTools::regexReplace(code, "texture2DLodEXT\\s*\\(", "textureLod("); code = StringTools::regexReplace(code, "textureCubeLodEXT\\s*\\(", "textureLod("); code = StringTools::regexReplace(code, "textureCube\\s*\\(", "texture("); code = StringTools::regexReplace(code, "gl_FragDepthEXT", "gl_FragDepth"); code = StringTools::regexReplace(code, "gl_FragColor", "glFragColor"); code = StringTools::regexReplace(code, "gl_FragData", "glFragData"); code = StringTools::regexReplace( code, R"(void\s+?main\s*\()", StringTools::printf("%s%s", (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n"), "void main(")); } else { const auto hasMultiviewExtension = stl_util::contains(defines, "#define MULTIVIEW"); if (hasMultiviewExtension) { return StringTools::printf( "#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n%s", code.c_str()); } } return code; } } // end of namespace BABYLON <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dbconfig.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: os $ $Date: 2002-11-29 12:10:02 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PRECOMPILED #include "ui_pch.hxx" #endif #pragma hdrstop #ifndef _DBCONFIG_HXX #include <dbconfig.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _SWDBDATA_HXX #include <swdbdata.hxx> #endif using namespace utl; using namespace rtl; using namespace com::sun::star::uno; #define C2U(cChar) OUString::createFromAscii(cChar) /*-------------------------------------------------------------------- Beschreibung: Ctor --------------------------------------------------------------------*/ const Sequence<OUString>& SwDBConfig::GetPropertyNames() { static Sequence<OUString> aNames; if(!aNames.getLength()) { static const char* aPropNames[] = { "AddressBook/DataSourceName", // 0 "AddressBook/Command", // 1 "AddressBook/CommandType", // 2 "Bibliography/CurrentDataSource/DataSourceName", // 4 "Bibliography/CurrentDataSource/Command", // 5 "Bibliography/CurrentDataSource/CommandType" // 6 }; const int nCount = sizeof(aPropNames)/sizeof(const char*); aNames.realloc(nCount); OUString* pNames = aNames.getArray(); for(int i = 0; i < nCount; i++) pNames[i] = OUString::createFromAscii(aPropNames[i]); } return aNames; } /* -----------------------------06.09.00 16:44-------------------------------- ---------------------------------------------------------------------------*/ SwDBConfig::SwDBConfig() : ConfigItem(C2U("Office.DataAccess"), CONFIG_MODE_DELAYED_UPDATE|CONFIG_MODE_RELEASE_TREE), pAdrImpl(0), pBibImpl(0) { }; /* -----------------------------06.09.00 16:50-------------------------------- ---------------------------------------------------------------------------*/ SwDBConfig::~SwDBConfig() { delete pAdrImpl; delete pBibImpl; } /* -----------------------------20.02.01 12:32-------------------------------- ---------------------------------------------------------------------------*/ void SwDBConfig::Load() { const Sequence<OUString>& rNames = GetPropertyNames(); if(!pAdrImpl) { pAdrImpl = new SwDBData; pAdrImpl->nCommandType = 0; pBibImpl = new SwDBData; pBibImpl->nCommandType = 0; } Sequence<Any> aValues = GetProperties(rNames); const Any* pValues = aValues.getConstArray(); DBG_ASSERT(aValues.getLength() == rNames.getLength(), "GetProperties failed") if(aValues.getLength() == rNames.getLength()) { for(int nProp = 0; nProp < rNames.getLength(); nProp++) { switch(nProp) { case 0: pValues[nProp] >>= pAdrImpl->sDataSource; break; case 1: pValues[nProp] >>= pAdrImpl->sCommand; break; case 2: pValues[nProp] >>= pAdrImpl->nCommandType; break; case 3: pValues[nProp] >>= pBibImpl->sDataSource; break; case 4: pValues[nProp] >>= pBibImpl->sCommand; break; case 5: pValues[nProp] >>= pBibImpl->nCommandType; break; } } } } /* -----------------------------20.02.01 12:36-------------------------------- ---------------------------------------------------------------------------*/ const SwDBData& SwDBConfig::GetAddressSource() { if(!pAdrImpl) Load(); return *pAdrImpl; } /* -----------------29.11.2002 11:43----------------- * * --------------------------------------------------*/ const SwDBData& SwDBConfig::GetBibliographySource() { if(!pBibImpl) Load(); return *pBibImpl; } <commit_msg>INTEGRATION: CWS os8 (1.3.138); FILE MERGED 2003/04/03 07:13:44 os 1.3.138.1: #108583# precompiled headers removed<commit_after>/************************************************************************* * * $RCSfile: dbconfig.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2003-04-17 15:17:30 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #ifndef _DBCONFIG_HXX #include <dbconfig.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _SWDBDATA_HXX #include <swdbdata.hxx> #endif using namespace utl; using namespace rtl; using namespace com::sun::star::uno; #define C2U(cChar) OUString::createFromAscii(cChar) /*-------------------------------------------------------------------- Beschreibung: Ctor --------------------------------------------------------------------*/ const Sequence<OUString>& SwDBConfig::GetPropertyNames() { static Sequence<OUString> aNames; if(!aNames.getLength()) { static const char* aPropNames[] = { "AddressBook/DataSourceName", // 0 "AddressBook/Command", // 1 "AddressBook/CommandType", // 2 "Bibliography/CurrentDataSource/DataSourceName", // 4 "Bibliography/CurrentDataSource/Command", // 5 "Bibliography/CurrentDataSource/CommandType" // 6 }; const int nCount = sizeof(aPropNames)/sizeof(const char*); aNames.realloc(nCount); OUString* pNames = aNames.getArray(); for(int i = 0; i < nCount; i++) pNames[i] = OUString::createFromAscii(aPropNames[i]); } return aNames; } /* -----------------------------06.09.00 16:44-------------------------------- ---------------------------------------------------------------------------*/ SwDBConfig::SwDBConfig() : ConfigItem(C2U("Office.DataAccess"), CONFIG_MODE_DELAYED_UPDATE|CONFIG_MODE_RELEASE_TREE), pAdrImpl(0), pBibImpl(0) { }; /* -----------------------------06.09.00 16:50-------------------------------- ---------------------------------------------------------------------------*/ SwDBConfig::~SwDBConfig() { delete pAdrImpl; delete pBibImpl; } /* -----------------------------20.02.01 12:32-------------------------------- ---------------------------------------------------------------------------*/ void SwDBConfig::Load() { const Sequence<OUString>& rNames = GetPropertyNames(); if(!pAdrImpl) { pAdrImpl = new SwDBData; pAdrImpl->nCommandType = 0; pBibImpl = new SwDBData; pBibImpl->nCommandType = 0; } Sequence<Any> aValues = GetProperties(rNames); const Any* pValues = aValues.getConstArray(); DBG_ASSERT(aValues.getLength() == rNames.getLength(), "GetProperties failed") if(aValues.getLength() == rNames.getLength()) { for(int nProp = 0; nProp < rNames.getLength(); nProp++) { switch(nProp) { case 0: pValues[nProp] >>= pAdrImpl->sDataSource; break; case 1: pValues[nProp] >>= pAdrImpl->sCommand; break; case 2: pValues[nProp] >>= pAdrImpl->nCommandType; break; case 3: pValues[nProp] >>= pBibImpl->sDataSource; break; case 4: pValues[nProp] >>= pBibImpl->sCommand; break; case 5: pValues[nProp] >>= pBibImpl->nCommandType; break; } } } } /* -----------------------------20.02.01 12:36-------------------------------- ---------------------------------------------------------------------------*/ const SwDBData& SwDBConfig::GetAddressSource() { if(!pAdrImpl) Load(); return *pAdrImpl; } /* -----------------29.11.2002 11:43----------------- * * --------------------------------------------------*/ const SwDBData& SwDBConfig::GetBibliographySource() { if(!pBibImpl) Load(); return *pBibImpl; } <|endoftext|>
<commit_before>// Source : https://leetcode.com/problems/h_index/ // Author : Calinescu Valentin // Date : 2015-10-22 /*************************************************************************************** * * Given an array of citations (each citation is a non-negative integer) of a * researcher, write a function to compute the researcher's h-index. * * According to the definition of h-index on Wikipedia: "A scientist has index h if h of * his/her N papers have at least h citations each, and the other N − h papers have no * more than h citations each." * * For example, given citations = [3, 0, 6, 1, 5], which means the researcher has 5 * papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. * Since the researcher has 3 papers with at least 3 citations each and the remaining * two with no more than 3 citations each, his h-index is 3. * * Note: If there are several possible values for h, the maximum one is taken as the * h-index. * ***************************************************************************************/ /* * Solutions * ========= * * A simple solution would be to sort the vector and then run through it starting with * the last element. At every step we need to check whether this element is not less than * the remaining number of elements bigger than it(including itself) and all the values of * the other elements smaller than it are not more than that number. The h_index is this * number of elements bigger than it(including itself). * * Time Complexity: O(N log N) * Space Complexity: O(1) * */ #include <algorithm> class Solution { public: int hIndex(vector<int>& citations) { sort(citations.begin(), citations.end()); int h_index = 0; for(int i = citations.size() - 1; i >= 0; i--) if(citations[i] >= citations.size() - i && (i - 1 < 0 || citations[i - 1] <= citations.size() - i)) h_index = citations.size() - i; return h_index; } }; <commit_msg>add a bit more clear implementation<commit_after>// Source : https://leetcode.com/problems/h_index/ // Author : Calinescu Valentin, Hao Chen // Date : 2015-10-22 /*************************************************************************************** * * Given an array of citations (each citation is a non-negative integer) of a * researcher, write a function to compute the researcher's h-index. * * According to the definition of h-index on Wikipedia: "A scientist has index h if h of * his/her N papers have at least h citations each, and the other N − h papers have no * more than h citations each." * * For example, given citations = [3, 0, 6, 1, 5], which means the researcher has 5 * papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. * Since the researcher has 3 papers with at least 3 citations each and the remaining * two with no more than 3 citations each, his h-index is 3. * * Note: If there are several possible values for h, the maximum one is taken as the * h-index. * ***************************************************************************************/ /* * Solutions * ========= * * A simple solution would be to sort the vector and then run through it starting with * the last element. At every step we need to check whether this element is not less than * the remaining number of elements bigger than it(including itself) and all the values of * the other elements smaller than it are not more than that number. The h_index is this * number of elements bigger than it(including itself). * * Time Complexity: O(N log N) * Space Complexity: O(1) * */ #include <algorithm> class Solution { public: int hIndex(vector<int>& citations) { return hIndex02(citations); return hIndex01(citations); } int hIndex01(vector<int>& citations) { sort(citations.begin(), citations.end()); int h_index = 0; for(int i = citations.size() - 1; i >= 0; i--) if(citations[i] >= citations.size() - i && (i - 1 < 0 || citations[i - 1] <= citations.size() - i)) h_index = citations.size() - i; return h_index; } // same solution but a bit different implemtation int hIndex02(vector<int>& citations) { sort(citations.begin(), citations.end()); int n = citations.size(); for (int i=0; i<n; i++){ if (citations[i] >= n-i){ return n-i; } } return 0; } }; <|endoftext|>
<commit_before>#ifndef AL_SIMULATOR_H #define AL_SIMULATOR_H #include "allocore/al_Allocore.hpp" #include "allocore/protocol/al_OSC.hpp" namespace al { class Simulator : public osc::PacketHandler, public Main::Handler { public: Simulator(const char* deviceServerAddress = "127.0.0.1", int port = 12001, int deviceServerPort = 12000); virtual ~Simulator(); virtual void start(); virtual void stop(); virtual void init() = 0; virtual void step(double dt) = 0; virtual void exit() = 0; virtual void onTick(); virtual void onExit(); const Nav& nav() const { return mNav; } Nav& nav() { return mNav; } virtual const char* name(); virtual const char* deviceServerConfig(); osc::Recv& oscRecv() { return mOSCRecv; } osc::Send& oscSend() { return mOSCSend; } virtual void onMessage(osc::Message& m); protected: bool started; double time, lastTime; osc::Recv mOSCRecv; osc::Send mOSCSend; Nav mNav; NavInputControl mNavControl; StandardWindowKeyControls mStdControls; double mNavSpeed, mNavTurnSpeed; }; inline void Simulator::onTick() { if (!started) { started = true; time = Main::get().realtime(); init(); } while (oscRecv().recv()) { } lastTime = time; time = Main::get().realtime(); nav().step(time - lastTime); step(time - lastTime); } inline void Simulator::onExit() { exit(); } inline void Simulator::onMessage(osc::Message& m) { float x; if (m.addressPattern() == "/mx") { m >> x; nav().moveR(-x * mNavSpeed); } else if (m.addressPattern() == "/my") { m >> x; nav().moveU(x * mNavSpeed); } else if (m.addressPattern() == "/mz") { m >> x; nav().moveF(x * mNavSpeed); } else if (m.addressPattern() == "/tx") { m >> x; nav().spinR(x * -mNavTurnSpeed); } else if (m.addressPattern() == "/ty") { m >> x; nav().spinU(x * mNavTurnSpeed); } else if (m.addressPattern() == "/tz") { m >> x; nav().spinF(x * -mNavTurnSpeed); } else if (m.addressPattern() == "/home") { nav().home(); } else if (m.addressPattern() == "/halt") { nav().halt(); } else { } // This allows the graphics renderer (or whatever) to overwrite navigation // data, so you can navigate from the graphics window when using a laptop. // if (m.addressPattern() == "/pose") { Pose pose; m >> pose.pos().x; m >> pose.pos().y; m >> pose.pos().z; m >> pose.quat().x; m >> pose.quat().y; m >> pose.quat().z; m >> pose.quat().w; //pose.print(); nav().set(pose); } } inline void Simulator::start() { if (oscSend().opened()) oscSend().send("/interface/applicationManager/createApplicationWithText", deviceServerConfig()); Main::get().interval(1 / 60.0).add(*this).start(); } inline void Simulator::stop() { Main::get().stop(); } inline Simulator::~Simulator() { oscSend().send("/interface/disconnectApplication", name()); } Simulator::Simulator(const char* deviceServerAddress, int port, int deviceServerPort) : mOSCRecv(port), mNavControl(mNav), mOSCSend(deviceServerPort, deviceServerAddress) { oscRecv().bufferSize(32000); oscRecv().handler(*this); mNavSpeed = 1; mNavTurnSpeed = 0.02; nav().smooth(0.8); } inline const char* Simulator::name() { return "default_no_name"; } inline const char* Simulator::deviceServerConfig() { return R"( app = { name : 'default_no_name', receivers :[ {type : 'OSC', port : 12001}, ], inputs: { mx: {min: 0, max: 0.1, }, my: {min: 0, max: 0.1, }, mz: {min: 0, max: 0.1, }, tx: {min: 0, max: 1, }, ty: {min: 0, max: 1, }, tz: {min: 0, max: 1, }, home: {min: 0, max: 1, }, halt: {min: 0, max: 1, }, }, mappings: [ { input: { io:'keypress', name:'`' }, output:{ io:'blob', name:'home' } }, { input: { io:'keypress', name:'w' }, output:{ io:'blob', name:'mx'}, }, ] } )"; } } // al:: #endif <commit_msg>add static methods to Simulator, usable to allow running in sphere without code change<commit_after>#ifndef AL_SIMULATOR_H #define AL_SIMULATOR_H #include "allocore/al_Allocore.hpp" #include "allocore/protocol/al_OSC.hpp" namespace al { class Simulator : public osc::PacketHandler, public Main::Handler { public: Simulator(const char* deviceServerAddress = "127.0.0.1", int port = 12001, int deviceServerPort = 12000); virtual ~Simulator(); virtual void start(); virtual void stop(); virtual void init() = 0; virtual void step(double dt) = 0; virtual void exit() = 0; virtual void onTick(); virtual void onExit(); const Nav& nav() const { return mNav; } Nav& nav() { return mNav; } virtual const char* name(); virtual const char* deviceServerConfig(); osc::Recv& oscRecv() { return mOSCRecv; } osc::Send& oscSend() { return mOSCSend; } virtual void onMessage(osc::Message& m); static bool gr01(){ char hostname[256]; gethostname(hostname, 256); return !strncmp(hostname,"gr01",256); } static const char* defaultBroadcastIP(){ if(gr01()) return "192.168.10.255"; else return "127.0.0.1"; } static const char* defaultInterfaceServerIP(){ if(gr01()) return "interface.local"; //mac mini hostname on 1g network else return "127.0.0.1"; } protected: bool started; double time, lastTime; osc::Recv mOSCRecv; osc::Send mOSCSend; Nav mNav; NavInputControl mNavControl; StandardWindowKeyControls mStdControls; double mNavSpeed, mNavTurnSpeed; }; inline void Simulator::onTick() { if (!started) { started = true; time = Main::get().realtime(); init(); } while (oscRecv().recv()) { } lastTime = time; time = Main::get().realtime(); nav().step(time - lastTime); step(time - lastTime); } inline void Simulator::onExit() { exit(); } inline void Simulator::onMessage(osc::Message& m) { float x; if (m.addressPattern() == "/mx") { m >> x; nav().moveR(-x * mNavSpeed); } else if (m.addressPattern() == "/my") { m >> x; nav().moveU(x * mNavSpeed); } else if (m.addressPattern() == "/mz") { m >> x; nav().moveF(x * mNavSpeed); } else if (m.addressPattern() == "/tx") { m >> x; nav().spinR(x * -mNavTurnSpeed); } else if (m.addressPattern() == "/ty") { m >> x; nav().spinU(x * mNavTurnSpeed); } else if (m.addressPattern() == "/tz") { m >> x; nav().spinF(x * -mNavTurnSpeed); } else if (m.addressPattern() == "/home") { nav().home(); } else if (m.addressPattern() == "/halt") { nav().halt(); } else { } // This allows the graphics renderer (or whatever) to overwrite navigation // data, so you can navigate from the graphics window when using a laptop. // if (m.addressPattern() == "/pose") { Pose pose; m >> pose.pos().x; m >> pose.pos().y; m >> pose.pos().z; m >> pose.quat().x; m >> pose.quat().y; m >> pose.quat().z; m >> pose.quat().w; //pose.print(); nav().set(pose); } } inline void Simulator::start() { if (oscSend().opened()) oscSend().send("/interface/applicationManager/createApplicationWithText", deviceServerConfig()); Main::get().interval(1 / 60.0).add(*this).start(); } inline void Simulator::stop() { Main::get().stop(); } inline Simulator::~Simulator() { oscSend().send("/interface/disconnectApplication", name()); } Simulator::Simulator(const char* deviceServerAddress, int port, int deviceServerPort) : mOSCRecv(port), mNavControl(mNav), mOSCSend(deviceServerPort, deviceServerAddress) { oscRecv().bufferSize(32000); oscRecv().handler(*this); mNavSpeed = 1; mNavTurnSpeed = 0.02; nav().smooth(0.8); } inline const char* Simulator::name() { return "default_no_name"; } inline const char* Simulator::deviceServerConfig() { return R"( app = { name : 'default_no_name', receivers :[ {type : 'OSC', port : 12001}, ], inputs: { mx: {min: 0, max: 0.1, }, my: {min: 0, max: 0.1, }, mz: {min: 0, max: 0.1, }, tx: {min: 0, max: 1, }, ty: {min: 0, max: 1, }, tz: {min: 0, max: 1, }, home: {min: 0, max: 1, }, halt: {min: 0, max: 1, }, }, mappings: [ { input: { io:'keypress', name:'`' }, output:{ io:'blob', name:'home' } }, { input: { io:'keypress', name:'w' }, output:{ io:'blob', name:'mx'}, }, ] } )"; } } // al:: #endif <|endoftext|>
<commit_before>#ifndef SILICIUM_NOEXCEPT_STRING_HPP #define SILICIUM_NOEXCEPT_STRING_HPP #ifdef _MSC_VER # include <string> #else # include <boost/container/string.hpp> #endif namespace Si { #ifdef _MSC_VER //boost string does not work at all on VC++ 2013 Update 3, so we use std::string instead typedef std::string noexcept_string; #else typedef boost::container::string noexcept_string; #endif } #endif <commit_msg>add utility function to_noexcept_string<commit_after>#ifndef SILICIUM_NOEXCEPT_STRING_HPP #define SILICIUM_NOEXCEPT_STRING_HPP #include <string> #include <boost/container/string.hpp> namespace Si { #ifdef _MSC_VER //boost string does not work at all on VC++ 2013 Update 3, so we use std::string instead typedef std::string noexcept_string; inline noexcept_string to_noexcept_string(boost::container::string const &str) { return noexcept_string(str.data(), str.size()); } inline noexcept_string &&to_noexcept_string(noexcept_string &&str) { return std::move(str); } inline noexcept_string to_noexcept_string(noexcept_string const &str) { return str; } #else typedef boost::container::string noexcept_string; inline noexcept_string to_noexcept_string(std::string const &str) { return noexcept_string(str.data(), str.size()); } inline noexcept_string &&to_noexcept_string(noexcept_string &&str) { return std::move(str); } inline noexcept_string to_noexcept_string(noexcept_string const &str) { return str; } #endif } #endif <|endoftext|>
<commit_before>// SGThread - Simple pthread class wrappers. // // Written by Bernie Bright, started April 2001. // // Copyright (C) 2001 Bernard Bright - [email protected] // Copyright (C) 2011 Mathias Froehlich // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // #ifdef HAVE_CONFIG_H # include <simgear_config.h> #endif #include <simgear/compiler.h> #include "SGThread.hxx" #ifdef _WIN32 ///////////////////////////////////////////////////////////////////////////// /// win32 threads ///////////////////////////////////////////////////////////////////////////// #include <list> #include <windows.h> struct SGThread::PrivateData { PrivateData() : _handle(INVALID_HANDLE_VALUE) { } ~PrivateData() { if (_handle == INVALID_HANDLE_VALUE) return; CloseHandle(_handle); _handle = INVALID_HANDLE_VALUE; } static DWORD WINAPI start_routine(LPVOID data) { SGThread* thread = reinterpret_cast<SGThread*>(data); thread->run(); return 0; } bool start(SGThread& thread) { if (_handle != INVALID_HANDLE_VALUE) return false; _handle = CreateThread(0, 0, start_routine, &thread, 0, 0); if (_handle == INVALID_HANDLE_VALUE) return false; return true; } void join() { if (_handle == INVALID_HANDLE_VALUE) return; DWORD ret = WaitForSingleObject(_handle, 0); if (ret != WAIT_OBJECT_0) return; CloseHandle(_handle); _handle = INVALID_HANDLE_VALUE; } HANDLE _handle; }; struct SGMutex::PrivateData { PrivateData() { InitializeCriticalSection((LPCRITICAL_SECTION)&_criticalSection); } ~PrivateData() { DeleteCriticalSection((LPCRITICAL_SECTION)&_criticalSection); } void lock(void) { EnterCriticalSection((LPCRITICAL_SECTION)&_criticalSection); } void unlock(void) { LeaveCriticalSection((LPCRITICAL_SECTION)&_criticalSection); } CRITICAL_SECTION _criticalSection; }; struct SGWaitCondition::PrivateData { ~PrivateData(void) { // The waiters list should be empty anyway _mutex.lock(); while (!_pool.empty()) { CloseHandle(_pool.front()); _pool.pop_front(); } _mutex.unlock(); } void signal(void) { _mutex.lock(); if (!_waiters.empty()) SetEvent(_waiters.back()); _mutex.unlock(); } void broadcast(void) { _mutex.lock(); for (std::list<HANDLE>::iterator i = _waiters.begin(); i != _waiters.end(); ++i) SetEvent(*i); _mutex.unlock(); } bool wait(SGMutex::PrivateData& externalMutex, DWORD msec) { _mutex.lock(); if (_pool.empty()) _waiters.push_front(CreateEvent(NULL, FALSE, FALSE, NULL)); else _waiters.splice(_waiters.begin(), _pool, _pool.begin()); std::list<HANDLE>::iterator i = _waiters.begin(); _mutex.unlock(); externalMutex.unlock(); DWORD result = WaitForSingleObject(*i, msec); externalMutex.lock(); _mutex.lock(); if (result != WAIT_OBJECT_0) result = WaitForSingleObject(*i, 0); _pool.splice(_pool.begin(), _waiters, i); _mutex.unlock(); return result == WAIT_OBJECT_0; } void wait(SGMutex::PrivateData& externalMutex) { wait(externalMutex, INFINITE); } // Protect the list of waiters SGMutex::PrivateData _mutex; std::list<HANDLE> _waiters; std::list<HANDLE> _pool; }; #else ///////////////////////////////////////////////////////////////////////////// /// posix threads ///////////////////////////////////////////////////////////////////////////// #include <pthread.h> #include <cassert> #include <cerrno> #include <sys/time.h> struct SGThread::PrivateData { PrivateData() : _started(false) { } ~PrivateData() { // If we are still having a started thread and nobody waited, // now detach ... if (!_started) return; pthread_detach(_thread); } static void *start_routine(void* data) { SGThread* thread = reinterpret_cast<SGThread*>(data); thread->run(); return 0; } bool start(SGThread& thread) { if (_started) return false; int ret = pthread_create(&_thread, 0, start_routine, &thread); if (0 != ret) return false; _started = true; return true; } void join() { if (!_started) return; pthread_join(_thread, 0); _started = false; } pthread_t _thread; bool _started; }; struct SGMutex::PrivateData { PrivateData() { int err = pthread_mutex_init(&_mutex, 0); assert(err == 0); (void)err; } ~PrivateData() { int err = pthread_mutex_destroy(&_mutex); assert(err == 0); (void)err; } void lock(void) { int err = pthread_mutex_lock(&_mutex); assert(err == 0); (void)err; } void unlock(void) { int err = pthread_mutex_unlock(&_mutex); assert(err == 0); (void)err; } pthread_mutex_t _mutex; }; struct SGWaitCondition::PrivateData { PrivateData(void) { int err = pthread_cond_init(&_condition, NULL); assert(err == 0); (void)err; } ~PrivateData(void) { int err = pthread_cond_destroy(&_condition); assert(err == 0); (void)err; } void signal(void) { int err = pthread_cond_signal(&_condition); assert(err == 0); (void)err; } void broadcast(void) { int err = pthread_cond_broadcast(&_condition); assert(err == 0); (void)err; } void wait(SGMutex::PrivateData& mutex) { int err = pthread_cond_wait(&_condition, &mutex._mutex); assert(err == 0); (void)err; } bool wait(SGMutex::PrivateData& mutex, unsigned msec) { struct timespec ts; #ifdef HAVE_CLOCK_GETTIME if (0 != clock_gettime(CLOCK_REALTIME, &ts)) return false; #else struct timeval tv; if (0 != gettimeofday(&tv, NULL)) return false; ts.tv_sec = tv.tv_sec; ts.tv_nsec = tv.tv_usec * 1000; #endif ts.tv_nsec += 1000000*(msec % 1000); if (1000000000 <= ts.tv_nsec) { ts.tv_nsec -= 1000000000; ts.tv_sec += 1; } ts.tv_sec += msec / 1000; int evalue = pthread_cond_timedwait(&_condition, &mutex._mutex, &ts); if (evalue == 0) return true; assert(evalue == ETIMEDOUT); return false; } pthread_cond_t _condition; }; #endif SGThread::SGThread() : _privateData(new PrivateData) { } SGThread::~SGThread() { delete _privateData; _privateData = 0; } bool SGThread::start() { return _privateData->start(*this); } void SGThread::join() { _privateData->join(); } SGMutex::SGMutex() : _privateData(new PrivateData) { } SGMutex::~SGMutex() { delete _privateData; _privateData = 0; } void SGMutex::lock() { _privateData->lock(); } void SGMutex::unlock() { _privateData->unlock(); } SGWaitCondition::SGWaitCondition() : _privateData(new PrivateData) { } SGWaitCondition::~SGWaitCondition() { delete _privateData; _privateData = 0; } void SGWaitCondition::wait(SGMutex& mutex) { _privateData->wait(*mutex._privateData); } bool SGWaitCondition::wait(SGMutex& mutex, unsigned msec) { return _privateData->wait(*mutex._privateData, msec); } void SGWaitCondition::signal() { _privateData->signal(); } void SGWaitCondition::broadcast() { _privateData->broadcast(); } <commit_msg>Fix win32 SGThread::join timeout.<commit_after>// SGThread - Simple pthread class wrappers. // // Written by Bernie Bright, started April 2001. // // Copyright (C) 2001 Bernard Bright - [email protected] // Copyright (C) 2011 Mathias Froehlich // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // #ifdef HAVE_CONFIG_H # include <simgear_config.h> #endif #include <simgear/compiler.h> #include "SGThread.hxx" #ifdef _WIN32 ///////////////////////////////////////////////////////////////////////////// /// win32 threads ///////////////////////////////////////////////////////////////////////////// #include <list> #include <windows.h> struct SGThread::PrivateData { PrivateData() : _handle(INVALID_HANDLE_VALUE) { } ~PrivateData() { if (_handle == INVALID_HANDLE_VALUE) return; CloseHandle(_handle); _handle = INVALID_HANDLE_VALUE; } static DWORD WINAPI start_routine(LPVOID data) { SGThread* thread = reinterpret_cast<SGThread*>(data); thread->run(); return 0; } bool start(SGThread& thread) { if (_handle != INVALID_HANDLE_VALUE) return false; _handle = CreateThread(0, 0, start_routine, &thread, 0, 0); if (_handle == INVALID_HANDLE_VALUE) return false; return true; } void join() { if (_handle == INVALID_HANDLE_VALUE) return; DWORD ret = WaitForSingleObject(_handle, INFINITE); if (ret != WAIT_OBJECT_0) return; CloseHandle(_handle); _handle = INVALID_HANDLE_VALUE; } HANDLE _handle; }; struct SGMutex::PrivateData { PrivateData() { InitializeCriticalSection((LPCRITICAL_SECTION)&_criticalSection); } ~PrivateData() { DeleteCriticalSection((LPCRITICAL_SECTION)&_criticalSection); } void lock(void) { EnterCriticalSection((LPCRITICAL_SECTION)&_criticalSection); } void unlock(void) { LeaveCriticalSection((LPCRITICAL_SECTION)&_criticalSection); } CRITICAL_SECTION _criticalSection; }; struct SGWaitCondition::PrivateData { ~PrivateData(void) { // The waiters list should be empty anyway _mutex.lock(); while (!_pool.empty()) { CloseHandle(_pool.front()); _pool.pop_front(); } _mutex.unlock(); } void signal(void) { _mutex.lock(); if (!_waiters.empty()) SetEvent(_waiters.back()); _mutex.unlock(); } void broadcast(void) { _mutex.lock(); for (std::list<HANDLE>::iterator i = _waiters.begin(); i != _waiters.end(); ++i) SetEvent(*i); _mutex.unlock(); } bool wait(SGMutex::PrivateData& externalMutex, DWORD msec) { _mutex.lock(); if (_pool.empty()) _waiters.push_front(CreateEvent(NULL, FALSE, FALSE, NULL)); else _waiters.splice(_waiters.begin(), _pool, _pool.begin()); std::list<HANDLE>::iterator i = _waiters.begin(); _mutex.unlock(); externalMutex.unlock(); DWORD result = WaitForSingleObject(*i, msec); externalMutex.lock(); _mutex.lock(); if (result != WAIT_OBJECT_0) result = WaitForSingleObject(*i, 0); _pool.splice(_pool.begin(), _waiters, i); _mutex.unlock(); return result == WAIT_OBJECT_0; } void wait(SGMutex::PrivateData& externalMutex) { wait(externalMutex, INFINITE); } // Protect the list of waiters SGMutex::PrivateData _mutex; std::list<HANDLE> _waiters; std::list<HANDLE> _pool; }; #else ///////////////////////////////////////////////////////////////////////////// /// posix threads ///////////////////////////////////////////////////////////////////////////// #include <pthread.h> #include <cassert> #include <cerrno> #include <sys/time.h> struct SGThread::PrivateData { PrivateData() : _started(false) { } ~PrivateData() { // If we are still having a started thread and nobody waited, // now detach ... if (!_started) return; pthread_detach(_thread); } static void *start_routine(void* data) { SGThread* thread = reinterpret_cast<SGThread*>(data); thread->run(); return 0; } bool start(SGThread& thread) { if (_started) return false; int ret = pthread_create(&_thread, 0, start_routine, &thread); if (0 != ret) return false; _started = true; return true; } void join() { if (!_started) return; pthread_join(_thread, 0); _started = false; } pthread_t _thread; bool _started; }; struct SGMutex::PrivateData { PrivateData() { int err = pthread_mutex_init(&_mutex, 0); assert(err == 0); (void)err; } ~PrivateData() { int err = pthread_mutex_destroy(&_mutex); assert(err == 0); (void)err; } void lock(void) { int err = pthread_mutex_lock(&_mutex); assert(err == 0); (void)err; } void unlock(void) { int err = pthread_mutex_unlock(&_mutex); assert(err == 0); (void)err; } pthread_mutex_t _mutex; }; struct SGWaitCondition::PrivateData { PrivateData(void) { int err = pthread_cond_init(&_condition, NULL); assert(err == 0); (void)err; } ~PrivateData(void) { int err = pthread_cond_destroy(&_condition); assert(err == 0); (void)err; } void signal(void) { int err = pthread_cond_signal(&_condition); assert(err == 0); (void)err; } void broadcast(void) { int err = pthread_cond_broadcast(&_condition); assert(err == 0); (void)err; } void wait(SGMutex::PrivateData& mutex) { int err = pthread_cond_wait(&_condition, &mutex._mutex); assert(err == 0); (void)err; } bool wait(SGMutex::PrivateData& mutex, unsigned msec) { struct timespec ts; #ifdef HAVE_CLOCK_GETTIME if (0 != clock_gettime(CLOCK_REALTIME, &ts)) return false; #else struct timeval tv; if (0 != gettimeofday(&tv, NULL)) return false; ts.tv_sec = tv.tv_sec; ts.tv_nsec = tv.tv_usec * 1000; #endif ts.tv_nsec += 1000000*(msec % 1000); if (1000000000 <= ts.tv_nsec) { ts.tv_nsec -= 1000000000; ts.tv_sec += 1; } ts.tv_sec += msec / 1000; int evalue = pthread_cond_timedwait(&_condition, &mutex._mutex, &ts); if (evalue == 0) return true; assert(evalue == ETIMEDOUT); return false; } pthread_cond_t _condition; }; #endif SGThread::SGThread() : _privateData(new PrivateData) { } SGThread::~SGThread() { delete _privateData; _privateData = 0; } bool SGThread::start() { return _privateData->start(*this); } void SGThread::join() { _privateData->join(); } SGMutex::SGMutex() : _privateData(new PrivateData) { } SGMutex::~SGMutex() { delete _privateData; _privateData = 0; } void SGMutex::lock() { _privateData->lock(); } void SGMutex::unlock() { _privateData->unlock(); } SGWaitCondition::SGWaitCondition() : _privateData(new PrivateData) { } SGWaitCondition::~SGWaitCondition() { delete _privateData; _privateData = 0; } void SGWaitCondition::wait(SGMutex& mutex) { _privateData->wait(*mutex._privateData); } bool SGWaitCondition::wait(SGMutex& mutex, unsigned msec) { return _privateData->wait(*mutex._privateData, msec); } void SGWaitCondition::signal() { _privateData->signal(); } void SGWaitCondition::broadcast() { _privateData->broadcast(); } <|endoftext|>
<commit_before>#include <mlopen/pooling.hpp> #include <cassert> #include <cmath> namespace mlopen { PoolingDescriptor::PoolingDescriptor() {} PoolingDescriptor::PoolingDescriptor(mlopenPoolingMode_t m, const int *plens, const int *ppads, const int *pstrides, int size) : lens(plens, plens+size), strides(pstrides, pstrides+size), pads(ppads, ppads+size), mode(m) {} mlopenPoolingMode_t PoolingDescriptor::GetMode() const { return(mode); } const std::vector<int>& PoolingDescriptor::GetLengths() const { return lens; } const std::vector<int>& PoolingDescriptor::GetStrides() const { return strides; } const std::vector<int>& PoolingDescriptor::GetPads() const { return pads; } mlopenPoolingMode_t PoolingDescriptor::GetMode() { return mode; } int PoolingDescriptor::GetSize() const { assert(lens.size() == strides.size() && lens.size() == pads.size()); return lens.size(); } std::tuple<int, int, int, int> PoolingDescriptor::GetForwardOutputDim( const TensorDescriptor &tensorDesc) const { assert(tensorDesc.GetLengths().size() == 4); int input_n; int input_c; int input_h; int input_w; std::tie(input_n, input_c, input_h, input_w) = mlopen::tie4(tensorDesc.GetLengths()); int u, v, pad_h, pad_w, window_h, window_w; std::tie(u, v) = mlopen::tie2(GetStrides()); std::tie(pad_h, pad_w) = mlopen::tie2(GetPads()); std::tie(window_h, window_w) = mlopen::tie2(GetLengths()); return std::make_tuple(input_n, input_c, ceil((input_h - window_h + 2*pad_h) / float(u)) + 1, ceil((input_w - window_w + 2*pad_w) / float(v)) + 1); } } // namespace mlopen <commit_msg>changed to static_cast<commit_after>#include <mlopen/pooling.hpp> #include <cassert> #include <cmath> namespace mlopen { PoolingDescriptor::PoolingDescriptor() {} PoolingDescriptor::PoolingDescriptor(mlopenPoolingMode_t m, const int *plens, const int *ppads, const int *pstrides, int size) : lens(plens, plens+size), strides(pstrides, pstrides+size), pads(ppads, ppads+size), mode(m) {} mlopenPoolingMode_t PoolingDescriptor::GetMode() const { return(mode); } const std::vector<int>& PoolingDescriptor::GetLengths() const { return lens; } const std::vector<int>& PoolingDescriptor::GetStrides() const { return strides; } const std::vector<int>& PoolingDescriptor::GetPads() const { return pads; } mlopenPoolingMode_t PoolingDescriptor::GetMode() { return mode; } int PoolingDescriptor::GetSize() const { assert(lens.size() == strides.size() && lens.size() == pads.size()); return lens.size(); } std::tuple<int, int, int, int> PoolingDescriptor::GetForwardOutputDim( const TensorDescriptor &tensorDesc) const { assert(tensorDesc.GetLengths().size() == 4); int input_n; int input_c; int input_h; int input_w; std::tie(input_n, input_c, input_h, input_w) = mlopen::tie4(tensorDesc.GetLengths()); int u, v, pad_h, pad_w, window_h, window_w; std::tie(u, v) = mlopen::tie2(GetStrides()); std::tie(pad_h, pad_w) = mlopen::tie2(GetPads()); std::tie(window_h, window_w) = mlopen::tie2(GetLengths()); return std::make_tuple(input_n, input_c, ceil((input_h - window_h + 2*pad_h) / static_cast<float>(u)) + 1, ceil((input_w - window_w + 2*pad_w) / static_cast<float>(v)) + 1); } } // namespace mlopen <|endoftext|>
<commit_before>#include "MainWindow.h" #include "IconView.h" #include <Application.h> #include <Bitmap.h> #include <Catalog.h> #include <ControlLook.h> #include <File.h> #include <FilePanel.h> #include <GridLayout.h> #include <GridLayoutBuilder.h> #include <GroupLayout.h> #include <GroupLayoutBuilder.h> #include <Locale.h> #include <Roster.h> #include <StorageKit.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> const uint32 MSG_RUN = 'mRUN'; const uint32 MSG_BROWSE = 'mBRO'; const uint32 MSG_CHANGED = 'mTXC'; const char *kTrackerSignature = "application/x-vnd.Be-TRAK"; const char *kTerminalSignature = "application/x-vnd.Haiku-Terminal"; //#define DEBUG(message) printf(message); //#define DEBUG(message) // #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "Run Window" void DEBUG(const char *message) { printf("%s\n", message); } MainWindow::MainWindow(void) : BWindow(BRect(100,100,500,200),B_TRANSLATE("Run"),B_TITLED_WINDOW_LOOK, B_NORMAL_WINDOW_FEEL, B_NOT_ZOOMABLE | B_CLOSE_ON_ESCAPE | B_NOT_MINIMIZABLE | B_NOT_RESIZABLE | B_ASYNCHRONOUS_CONTROLS), fTargetPanel(NULL) { BGroupLayout* layout = new BGroupLayout(B_VERTICAL, 0); SetLayout(layout); fRunButton = new BButton(B_TRANSLATE("Run"), new BMessage(MSG_RUN)); fBrowseButton = new BButton(B_TRANSLATE("Browse" B_UTF8_ELLIPSIS), new BMessage(MSG_BROWSE)); fTargetText = new AutoComplete(B_TRANSLATE("Command to run:"), NULL, new BMessage(MSG_CHANGED)); fTargetText->SetModificationMessage(new BMessage(MSG_CHANGED)); fIconView = new IconView(); BView* topView = layout->View(); const float spacing = be_control_look->DefaultItemSpacing(); topView->AddChild(BGroupLayoutBuilder(B_VERTICAL, spacing) .AddGroup(B_VERTICAL, spacing) .Add(BGridLayoutBuilder() .Add(fIconView, 0, 0) .Add(fTargetText, 1, 0, 6, 1) ) .AddGroup(B_HORIZONTAL, 5.0) .Add(fUseTerminal = new BCheckBox(NULL, B_TRANSLATE("Open in a terminal"), new BMessage(MSG_CHANGED))) .Add(fRunButton) .Add(fBrowseButton) .End() .End() .SetInsets(spacing, spacing, spacing, spacing) ); fTargetText->MakeFocus(true); fRunButton->MakeDefault(true); CenterOnScreen(); Show(); } MainWindow::~MainWindow() { delete fTargetPanel; } void MainWindow::MessageReceived(BMessage *msg) { switch (msg->what) { case MSG_CHANGED: { _ParseTarget(); break; } case MSG_BROWSE: { BEntry entry(fTargetText->Text(), true); entry_ref srcRef; if (entry.Exists() && entry.IsDirectory()) entry.GetRef(&srcRef); if (!fTargetPanel) { BMessenger messenger(this); fTargetPanel = new BFilePanel(B_OPEN_PANEL, &messenger, &srcRef, B_FILE_NODE, false); (fTargetPanel->Window())->SetTitle(B_TRANSLATE("Run: Open")); } else fTargetPanel->SetPanelDirectory(&srcRef); fTargetPanel->Show(); break; } case MSG_RUN: { if (_Launch() == B_OK) QuitRequested(); else { BAlert* alert = new BAlert(B_TRANSLATE("Can't Run That"), B_TRANSLATE("Sorry. We couldn't find the resource you're trying to run."), "Try Again", NULL, NULL, B_WIDTH_AS_USUAL, B_OFFSET_SPACING, B_WARNING_ALERT); alert->SetShortcut(0, B_ESCAPE); alert->Go(); } break; } case B_REFS_RECEIVED: { entry_ref entryRef; msg->FindRef("refs", &entryRef); BEntry entry(&entryRef); BPath path; if (entry.GetPath(&path) == B_OK) fTargetText->SetText(path.Path()); break; } default: { //msg->PrintToStream(); BWindow::MessageReceived(msg); break; } } } bool MainWindow::QuitRequested(void) { be_app->PostMessage(B_QUIT_REQUESTED); return true; } status_t MainWindow::_OpenFile(const char* openWith, BEntry &entry, int32 line = -1, int32 col = -1) { entry_ref ref; status_t status = entry.GetRef(&ref); if (status < B_OK) return status; BMessenger target(openWith ? openWith : kTrackerSignature); if (!target.IsValid()) return be_roster->Launch(&ref); BMessage message(B_REFS_RECEIVED); message.AddRef("refs", &ref); if (line > -1) message.AddInt32("be:line", line); if (col > -1) message.AddInt32("be:column", col); // tell the app to open the file return target.SendMessage(&message); } int MainWindow::_Launch() { int exitcode = EXIT_SUCCESS; const char *openWith = NULL; status_t status = B_OK; if (fUseTerminal->Value() == B_CONTROL_ON) { char* argv[] = {(char*)fTargetText->Text()}; status = be_roster->Launch(kTerminalSignature, 1, argv); } BEntry entry(fTargetText->Text()); if ((status = entry.InitCheck()) == B_OK && entry.Exists()) { status = _OpenFile(openWith, entry); } else if (!strncasecmp("application/", fTargetText->Text(), 12)) { // maybe it's an application-mimetype? // subsequent files are open with that app openWith = fTargetText->Text(); // in the case the app is already started, // don't start it twice if we have other args BList teams; be_roster->GetAppList(fTargetText->Text(), &teams); if (teams.IsEmpty()) status = be_roster->Launch(fTargetText->Text()); else status = B_OK; } else if (strchr(fTargetText->Text(), ':')) { // try to open it as an URI //BPrivate::Support::BUrl url(fTargetText->Text()); //if (url.OpenWithPreferredApplication() == B_OK) // return B_OK; // maybe it's "file:line" or "file:line:col" int line = 0, col = 0, i; status = B_ENTRY_NOT_FOUND; // remove gcc error's last : BString arg(fTargetText->Text()); if (arg[arg.Length() - 1] == ':') arg.Truncate(arg.Length() - 1); i = arg.FindLast(':'); if (i > 0) { line = atoi(arg.String() + i + 1); arg.Truncate(i); status = entry.SetTo(arg.String()); if (status == B_OK && entry.Exists()) { status = _OpenFile(openWith, entry, line); if (status == B_OK) return status; } // get the column col = line; i = arg.FindLast(':'); line = atoi(arg.String() + i + 1); arg.Truncate(i); status = entry.SetTo(arg.String()); if (status == B_OK && entry.Exists()) status = _OpenFile(openWith, entry, line, col); } } else { // scan through the path char * path = strtok(getenv("PATH"), ":"); while (path != NULL) { BString fullname(path); fullname.Append("/"); fullname.Append(fTargetText->Text()); entry = BEntry(fullname.String(), false); if ((status = entry.InitCheck()) == B_OK && entry.Exists()) { status = _OpenFile(openWith, entry); break; } path = strtok(NULL, ":"); } if (path == NULL) status = B_ENTRY_NOT_FOUND; } if (status != B_OK && status != B_ALREADY_RUNNING) { fprintf(stderr, "%s: \"%s\": %s\n", "Run", fTargetText->Text(), strerror(status)); // make sure the shell knows this exitcode = EXIT_FAILURE; } return exitcode; } char* _whereis(const char* target) { DEBUG("Scanning path for"); DEBUG(target); // scan through the path char *path = strdup(getenv("PATH")); DEBUG("The path is"); DEBUG(path); path = strtok(path, ":"); while (path != NULL) { BString fullname(path); fullname.Append("/"); fullname.Append(target); DEBUG("Looking for"); DEBUG(fullname.String()); BEntry entry(fullname.String(), false); if ((entry.InitCheck()) == B_OK && entry.Exists()) { //delete path; DEBUG("Located at"); DEBUG(fullname); return (char*) fullname.String(); } path = strtok(NULL, ":"); } return NULL; } bool MainWindow::_TestTarget(const char* target) { BEntry app, entry(target); entry_ref appRef, entryRef; DEBUG("Does it exist? "); if ((entry.InitCheck()) == B_OK && entry.Exists()) { DEBUG("Such a file exists. "); status_t status = entry.GetRef(&entryRef) && app.GetRef(&appRef); if (status == B_OK) { DEBUG("Got the refs "); if (be_roster->FindApp(&entryRef, &appRef) == B_OK) { DEBUG("Found app for "); app_info info; if (be_roster->GetAppInfo(&appRef, &info) == B_OK) { DEBUG("Do setting icon"); fIconView->SetIcon(&info); return true; } } } } return false; } void MainWindow::_ParseTarget() { DEBUG("Parsing target"); if (fUseTerminal->Value() == B_CONTROL_ON) { fIconView->SetIcon(kTerminalSignature); return; } if (_TestTarget(fTargetText->Text())) { return; } else if (!strchr(fTargetText->Text(), '/')) { if (_TestTarget(_whereis(fTargetText->Text()))) { return; } } fIconView->SetDefault(); } <commit_msg>Detects programs that need to be run in Terminal. TODO: Change the icon back to the default after erasing a Terminal-run program.<commit_after>#include "MainWindow.h" #include "IconView.h" #include <Application.h> #include <Bitmap.h> #include <Catalog.h> #include <ControlLook.h> #include <File.h> #include <FilePanel.h> #include <GridLayout.h> #include <GridLayoutBuilder.h> #include <GroupLayout.h> #include <GroupLayoutBuilder.h> #include <Locale.h> #include <Roster.h> #include <StorageKit.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> const uint32 MSG_RUN = 'mRUN'; const uint32 MSG_BROWSE = 'mBRO'; const uint32 MSG_CHANGED = 'mTXC'; const char *kTrackerSignature = "application/x-vnd.Be-TRAK"; const char *kTerminalSignature = "application/x-vnd.Haiku-Terminal"; //#define DEBUG(message) printf(message); //#define DEBUG(message) // #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "Run Window" void DEBUG(const char *message) { printf("%s\n", message); } MainWindow::MainWindow(void) : BWindow(BRect(100,100,500,200),B_TRANSLATE("Run"),B_TITLED_WINDOW_LOOK, B_NORMAL_WINDOW_FEEL, B_NOT_ZOOMABLE | B_CLOSE_ON_ESCAPE | B_NOT_MINIMIZABLE | B_NOT_RESIZABLE | B_ASYNCHRONOUS_CONTROLS), fTargetPanel(NULL) { BGroupLayout* layout = new BGroupLayout(B_VERTICAL, 0); SetLayout(layout); fRunButton = new BButton(B_TRANSLATE("Run"), new BMessage(MSG_RUN)); fBrowseButton = new BButton(B_TRANSLATE("Browse" B_UTF8_ELLIPSIS), new BMessage(MSG_BROWSE)); fTargetText = new AutoComplete(B_TRANSLATE("Command to run:"), NULL, new BMessage(MSG_CHANGED)); fTargetText->SetModificationMessage(new BMessage(MSG_CHANGED)); fIconView = new IconView(); BView* topView = layout->View(); const float spacing = be_control_look->DefaultItemSpacing(); topView->AddChild(BGroupLayoutBuilder(B_VERTICAL, spacing) .AddGroup(B_VERTICAL, spacing) .Add(BGridLayoutBuilder() .Add(fIconView, 0, 0) .Add(fTargetText, 1, 0, 6, 1) ) .AddGroup(B_HORIZONTAL, 5.0) .Add(fUseTerminal = new BCheckBox(NULL, B_TRANSLATE("Open in a terminal"), new BMessage(MSG_CHANGED))) .Add(fRunButton) .Add(fBrowseButton) .End() .End() .SetInsets(spacing, spacing, spacing, spacing) ); fTargetText->MakeFocus(true); fRunButton->MakeDefault(true); CenterOnScreen(); Show(); } MainWindow::~MainWindow() { delete fTargetPanel; } void MainWindow::MessageReceived(BMessage *msg) { switch (msg->what) { case MSG_CHANGED: { _ParseTarget(); break; } case MSG_BROWSE: { BEntry entry(fTargetText->Text(), true); entry_ref srcRef; if (entry.Exists() && entry.IsDirectory()) entry.GetRef(&srcRef); if (!fTargetPanel) { BMessenger messenger(this); fTargetPanel = new BFilePanel(B_OPEN_PANEL, &messenger, &srcRef, B_FILE_NODE, false); (fTargetPanel->Window())->SetTitle(B_TRANSLATE("Run: Open")); } else fTargetPanel->SetPanelDirectory(&srcRef); fTargetPanel->Show(); break; } case MSG_RUN: { if (_Launch() == B_OK) QuitRequested(); else { BAlert* alert = new BAlert(B_TRANSLATE("Can't Run That"), B_TRANSLATE("Sorry. We couldn't find the resource you're trying to run."), "Try Again", NULL, NULL, B_WIDTH_AS_USUAL, B_OFFSET_SPACING, B_WARNING_ALERT); alert->SetShortcut(0, B_ESCAPE); alert->Go(); } break; } case B_REFS_RECEIVED: { entry_ref entryRef; msg->FindRef("refs", &entryRef); BEntry entry(&entryRef); BPath path; if (entry.GetPath(&path) == B_OK) fTargetText->SetText(path.Path()); break; } default: { //msg->PrintToStream(); BWindow::MessageReceived(msg); break; } } } bool MainWindow::QuitRequested(void) { be_app->PostMessage(B_QUIT_REQUESTED); return true; } status_t MainWindow::_OpenFile(const char* openWith, BEntry &entry, int32 line = -1, int32 col = -1) { entry_ref ref; status_t status = entry.GetRef(&ref); if (status < B_OK) return status; BMessenger target(openWith ? openWith : kTrackerSignature); if (!target.IsValid()) return be_roster->Launch(&ref); BMessage message(B_REFS_RECEIVED); message.AddRef("refs", &ref); if (line > -1) message.AddInt32("be:line", line); if (col > -1) message.AddInt32("be:column", col); // tell the app to open the file return target.SendMessage(&message); } int MainWindow::_Launch() { int exitcode = EXIT_SUCCESS; const char *openWith = NULL; status_t status = B_OK; if (fUseTerminal->Value() == B_CONTROL_ON) { char* argv[] = {(char*)fTargetText->Text()}; status = be_roster->Launch(kTerminalSignature, 1, argv); } BEntry entry(fTargetText->Text()); if ((status = entry.InitCheck()) == B_OK && entry.Exists()) { status = _OpenFile(openWith, entry); } else if (!strncasecmp("application/", fTargetText->Text(), 12)) { // maybe it's an application-mimetype? // subsequent files are open with that app openWith = fTargetText->Text(); // in the case the app is already started, // don't start it twice if we have other args BList teams; be_roster->GetAppList(fTargetText->Text(), &teams); if (teams.IsEmpty()) status = be_roster->Launch(fTargetText->Text()); else status = B_OK; } else if (strchr(fTargetText->Text(), ':')) { // try to open it as an URI //BPrivate::Support::BUrl url(fTargetText->Text()); //if (url.OpenWithPreferredApplication() == B_OK) // return B_OK; // maybe it's "file:line" or "file:line:col" int line = 0, col = 0, i; status = B_ENTRY_NOT_FOUND; // remove gcc error's last : BString arg(fTargetText->Text()); if (arg[arg.Length() - 1] == ':') arg.Truncate(arg.Length() - 1); i = arg.FindLast(':'); if (i > 0) { line = atoi(arg.String() + i + 1); arg.Truncate(i); status = entry.SetTo(arg.String()); if (status == B_OK && entry.Exists()) { status = _OpenFile(openWith, entry, line); if (status == B_OK) return status; } // get the column col = line; i = arg.FindLast(':'); line = atoi(arg.String() + i + 1); arg.Truncate(i); status = entry.SetTo(arg.String()); if (status == B_OK && entry.Exists()) status = _OpenFile(openWith, entry, line, col); } } else { // scan through the path char * path = strtok(getenv("PATH"), ":"); while (path != NULL) { BString fullname(path); fullname.Append("/"); fullname.Append(fTargetText->Text()); entry = BEntry(fullname.String(), false); if ((status = entry.InitCheck()) == B_OK && entry.Exists()) { status = _OpenFile(openWith, entry); break; } path = strtok(NULL, ":"); } if (path == NULL) status = B_ENTRY_NOT_FOUND; } if (status != B_OK && status != B_ALREADY_RUNNING) { fprintf(stderr, "%s: \"%s\": %s\n", "Run", fTargetText->Text(), strerror(status)); // make sure the shell knows this exitcode = EXIT_FAILURE; } return exitcode; } char* _whereis(const char* target) { DEBUG("Scanning path for"); DEBUG(target); // scan through the path char *path = strdup(getenv("PATH")); DEBUG("The path is"); DEBUG(path); path = strtok(path, ":"); while (path != NULL) { BString fullname(path); fullname.Append("/"); fullname.Append(target); DEBUG("Looking for"); DEBUG(fullname.String()); BEntry entry(fullname.String(), false); if ((entry.InitCheck()) == B_OK && entry.Exists()) { //delete path; DEBUG("Located at"); DEBUG(fullname); return (char*) fullname.String(); } path = strtok(NULL, ":"); } return NULL; } bool MainWindow::_TestTarget(const char* target) { BEntry app, entry(target); entry_ref appRef, entryRef; DEBUG("Does it exist? "); if ((entry.InitCheck()) == B_OK && entry.Exists()) { DEBUG("Such a file exists. "); status_t status = entry.GetRef(&entryRef) && app.GetRef(&appRef); if (status == B_OK) { DEBUG("Got the refs "); if (be_roster->FindApp(&entryRef, &appRef) == B_OK) { DEBUG("Found app for "); app_info info; if (be_roster->GetAppInfo(&appRef, &info) == B_OK) { DEBUG("Do setting icon"); fIconView->SetIcon(&info); fUseTerminal->SetValue(B_CONTROL_OFF); return true; } else { fIconView->SetIcon(kTerminalSignature); fUseTerminal->SetValue(B_CONTROL_ON); return true; } } } } fIconView->SetDefault(); return false; } void MainWindow::_ParseTarget() { DEBUG("Parsing target"); if (fUseTerminal->Value() == B_CONTROL_ON) { fIconView->SetIcon(kTerminalSignature); return; } if (_TestTarget(fTargetText->Text())) { return; } else if (!strchr(fTargetText->Text(), '/')) { if (_TestTarget(_whereis(fTargetText->Text()))) { return; } } fIconView->SetDefault(); return; } <|endoftext|>
<commit_before>/* maestro.cpp - management of multiple trials for dubins_traffic * * SCL; 2016 */ #include <ros/ros.h> #include "std_srvs/Empty.h" #include "gazebo_msgs/ModelState.h" #include "geometry_msgs/Pose.h" #include "geometry_msgs/Twist.h" #include <Eigen/Dense> #include "integrator_chains_msgs/ProblemInstanceJSON.h" #include "dubins_traffic_msgs/MMode.h" #include "roadnet.hpp" #include "problem.hpp" using namespace dubins_traffic; class Maestro { public: Maestro( ros::NodeHandle &nh_, Problem &problem_ ); bool mode_request( dubins_traffic_msgs::MMode::Request &req, dubins_traffic_msgs::MMode::Response &res ); void perform_trial(); void main(); private: ros::NodeHandle &nh; Problem &problem; ros::Publisher problemJSONpub; ros::Publisher set_model_state; ros::ServiceClient gazebo_toggle; bool gazebo_paused; ros::ServiceServer mode_srv; enum MMode { ready, waiting, running, resetting }; MMode mmode; /* (copied from domains/integrator_chains/dynamaestro/src/main.cpp to avoid dependency.) */ bool parse_range_str( const std::string param_name, Eigen::Vector2i &range ); }; bool Maestro::parse_range_str( const std::string param_name, Eigen::Vector2i &range ) { std::string range_str; if (!nh.getParam( param_name, range_str )) return false; char *endptr; errno = 0; range(0) = strtol( range_str.data(), &endptr, 10 ); if (errno || endptr == range_str.data()) { std::cerr << "dubins_traffic_maestro: Malformed range string in \"" << param_name << "\"" << std::endl; return false; } char *prev_endptr = endptr; errno = 0; range(1) = strtol( prev_endptr, &endptr, 10 ); if (errno || endptr == prev_endptr) { std::cerr << "dubins_traffic_maestro: Malformed range string in \"" << param_name << "\"" << std::endl; return false; } return true; } Maestro::Maestro( ros::NodeHandle &nh_, Problem &problem_ ) : nh(nh_), problem(problem_), gazebo_paused( true ) { problemJSONpub = nh.advertise<integrator_chains_msgs::ProblemInstanceJSON>( "probleminstance_JSON", 1, true ); mode_srv = nh.advertiseService( "mode", &Maestro::mode_request, this ); set_model_state = nh.advertise<gazebo_msgs::ModelState>( "/gazebo/set_model_state", 1, true ); } bool Maestro::mode_request( dubins_traffic_msgs::MMode::Request &req, dubins_traffic_msgs::MMode::Response &res ) { switch (req.mode) { case dubins_traffic_msgs::MMode::Request::READY: if (!gazebo_paused) { gazebo_toggle = nh.serviceClient<std_srvs::Empty>( "/gazebo/pause_physics" ); std_srvs::Empty empty; if (gazebo_toggle.call( empty )) gazebo_paused = true; } if (mmode == ready && gazebo_paused) { res.result = true; } else { res.result = false; } break; case dubins_traffic_msgs::MMode::Request::START: if (mmode == ready) { mmode = waiting; res.result = true; } else { res.result = false; } break; case dubins_traffic_msgs::MMode::Request::RESET: mmode = resetting; ROS_INFO( "dubins_traffic_maestro: Stopping current trial and generating a new instance..." ); res.result = true; break; default: return false; } return true; } void Maestro::perform_trial() { ros::Rate polling_rate( 1000 ); Eigen::Vector2i duration_bounds; if (!parse_range_str( "duration_bounds", duration_bounds )) { duration_bounds << 30, 90; } ROS_INFO( "dubins_traffic_maestro: Using [%d, %d] as range of integers for sampling " "the trial duration.", duration_bounds(0), duration_bounds(1) ); int nominal_duration = duration_bounds(0); if (duration_bounds(0) == duration_bounds(1)) nominal_duration += std::rand() % (1+duration_bounds(1)-duration_bounds(1)); ros::Duration trial_duration; mmode = ready; while (mmode == ready) { if (!ros::ok()) return; ros::spinOnce(); polling_rate.sleep(); } assert( mmode == waiting ); integrator_chains_msgs::ProblemInstanceJSON probinstance_msg; probinstance_msg.stamp = ros::Time::now(); probinstance_msg.problemjson = problem.dumpJSON(); problemJSONpub.publish( probinstance_msg ); ros::Time startt( probinstance_msg.stamp.sec, probinstance_msg.stamp.nsec ); ros::spinOnce(); while (ros::ok() && mmode != resetting && (trial_duration = ros::Time::now() - startt).toSec() < nominal_duration) { if (mmode == waiting) { mmode = running; } ros::spinOnce(); polling_rate.sleep(); } mmode = resetting; // Handle special cases of trial termination: if (ros::ok() && trial_duration.toSec() >= nominal_duration) { // The trial end because the nominal (hidden) duration was reached ROS_INFO( "dubins_traffic_maestro: Trial ended after %f s (threshold is %d s).", trial_duration.toSec(), nominal_duration ); } } void Maestro::main() { int number_trials = 0; bool counting_trials = nh.getParam( "/number_trials", number_trials ); if (counting_trials) ROS_INFO( "dubins_traffic_maestro: Initiated with request for %d trials.", number_trials ); int trial_counter = 0; while ((!counting_trials || trial_counter < number_trials) && ros::ok()) { perform_trial(); if (counting_trials) trial_counter++; } if (counting_trials && ros::ok()) { ROS_INFO( "dubins_traffic_maestro: Completed %d trials.", trial_counter ); } } int main( int argc, char **argv ) { ros::init( argc, argv, "dubins_traffic_maestro" ); ros::NodeHandle nh( "~" ); std::string rndjson; while (!nh.getParam( "/dubins_traffic/rnd", rndjson )) { ROS_INFO( "dubins_traffic_maestro: RND JSON string not present; will try again soon..." ); sleep( 1 ); if (!ros::ok()) return 0; } RoadNetwork rnd( rndjson ); Problem problem( rnd ); Maestro maestro( nh, problem ); maestro.main(); ros::spin(); return 0; } <commit_msg>BUGFIX: nominal duration computation of dubins_traffic<commit_after>/* maestro.cpp - management of multiple trials for dubins_traffic * * SCL; 2016 */ #include <ros/ros.h> #include "std_srvs/Empty.h" #include "gazebo_msgs/ModelState.h" #include "geometry_msgs/Pose.h" #include "geometry_msgs/Twist.h" #include <Eigen/Dense> #include "integrator_chains_msgs/ProblemInstanceJSON.h" #include "dubins_traffic_msgs/MMode.h" #include "roadnet.hpp" #include "problem.hpp" using namespace dubins_traffic; class Maestro { public: Maestro( ros::NodeHandle &nh_, Problem &problem_ ); bool mode_request( dubins_traffic_msgs::MMode::Request &req, dubins_traffic_msgs::MMode::Response &res ); void perform_trial(); void main(); private: ros::NodeHandle &nh; Problem &problem; ros::Publisher problemJSONpub; ros::Publisher set_model_state; ros::ServiceClient gazebo_toggle; bool gazebo_paused; ros::ServiceServer mode_srv; enum MMode { ready, waiting, running, resetting }; MMode mmode; /* (copied from domains/integrator_chains/dynamaestro/src/main.cpp to avoid dependency.) */ bool parse_range_str( const std::string param_name, Eigen::Vector2i &range ); }; bool Maestro::parse_range_str( const std::string param_name, Eigen::Vector2i &range ) { std::string range_str; if (!nh.getParam( param_name, range_str )) return false; char *endptr; errno = 0; range(0) = strtol( range_str.data(), &endptr, 10 ); if (errno || endptr == range_str.data()) { std::cerr << "dubins_traffic_maestro: Malformed range string in \"" << param_name << "\"" << std::endl; return false; } char *prev_endptr = endptr; errno = 0; range(1) = strtol( prev_endptr, &endptr, 10 ); if (errno || endptr == prev_endptr) { std::cerr << "dubins_traffic_maestro: Malformed range string in \"" << param_name << "\"" << std::endl; return false; } return true; } Maestro::Maestro( ros::NodeHandle &nh_, Problem &problem_ ) : nh(nh_), problem(problem_), gazebo_paused( true ) { problemJSONpub = nh.advertise<integrator_chains_msgs::ProblemInstanceJSON>( "probleminstance_JSON", 1, true ); mode_srv = nh.advertiseService( "mode", &Maestro::mode_request, this ); set_model_state = nh.advertise<gazebo_msgs::ModelState>( "/gazebo/set_model_state", 1, true ); } bool Maestro::mode_request( dubins_traffic_msgs::MMode::Request &req, dubins_traffic_msgs::MMode::Response &res ) { switch (req.mode) { case dubins_traffic_msgs::MMode::Request::READY: if (!gazebo_paused) { gazebo_toggle = nh.serviceClient<std_srvs::Empty>( "/gazebo/pause_physics" ); std_srvs::Empty empty; if (gazebo_toggle.call( empty )) gazebo_paused = true; } if (mmode == ready && gazebo_paused) { res.result = true; } else { res.result = false; } break; case dubins_traffic_msgs::MMode::Request::START: if (mmode == ready) { mmode = waiting; res.result = true; } else { res.result = false; } break; case dubins_traffic_msgs::MMode::Request::RESET: mmode = resetting; ROS_INFO( "dubins_traffic_maestro: Stopping current trial and generating a new instance..." ); res.result = true; break; default: return false; } return true; } void Maestro::perform_trial() { ros::Rate polling_rate( 1000 ); Eigen::Vector2i duration_bounds; if (!parse_range_str( "duration_bounds", duration_bounds )) { duration_bounds << 30, 90; } ROS_INFO( "dubins_traffic_maestro: Using [%d, %d] as range of integers for sampling " "the trial duration.", duration_bounds(0), duration_bounds(1) ); int nominal_duration = duration_bounds(0); if (duration_bounds(0) != duration_bounds(1)) nominal_duration += std::rand() % (1+duration_bounds(1)-duration_bounds(0)); ros::Duration trial_duration; mmode = ready; while (mmode == ready) { if (!ros::ok()) return; ros::spinOnce(); polling_rate.sleep(); } assert( mmode == waiting ); integrator_chains_msgs::ProblemInstanceJSON probinstance_msg; probinstance_msg.stamp = ros::Time::now(); probinstance_msg.problemjson = problem.dumpJSON(); problemJSONpub.publish( probinstance_msg ); ros::Time startt( probinstance_msg.stamp.sec, probinstance_msg.stamp.nsec ); ros::spinOnce(); while (ros::ok() && mmode != resetting && (trial_duration = ros::Time::now() - startt).toSec() < nominal_duration) { if (mmode == waiting) { mmode = running; } ros::spinOnce(); polling_rate.sleep(); } mmode = resetting; // Handle special cases of trial termination: if (ros::ok() && trial_duration.toSec() >= nominal_duration) { // The trial end because the nominal (hidden) duration was reached ROS_INFO( "dubins_traffic_maestro: Trial ended after %f s (threshold is %d s).", trial_duration.toSec(), nominal_duration ); } } void Maestro::main() { int number_trials = 0; bool counting_trials = nh.getParam( "/number_trials", number_trials ); if (counting_trials) ROS_INFO( "dubins_traffic_maestro: Initiated with request for %d trials.", number_trials ); int trial_counter = 0; while ((!counting_trials || trial_counter < number_trials) && ros::ok()) { perform_trial(); if (counting_trials) trial_counter++; } if (counting_trials && ros::ok()) { ROS_INFO( "dubins_traffic_maestro: Completed %d trials.", trial_counter ); } } int main( int argc, char **argv ) { ros::init( argc, argv, "dubins_traffic_maestro" ); ros::NodeHandle nh( "~" ); std::string rndjson; while (!nh.getParam( "/dubins_traffic/rnd", rndjson )) { ROS_INFO( "dubins_traffic_maestro: RND JSON string not present; will try again soon..." ); sleep( 1 ); if (!ros::ok()) return 0; } RoadNetwork rnd( rndjson ); Problem problem( rnd ); Maestro maestro( nh, problem ); maestro.main(); ros::spin(); return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2013 Daniele Bartolini, Michele Rossi Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Matrix4x4.h" #include "Vector3.h" #include "LuaStack.h" #include "LuaEnvironment.h" #include "OS.h" namespace crown { //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4(lua_State* L) { LuaStack stack(L); float m0 = stack.get_float(1); float m1 = stack.get_float(2); float m2 = stack.get_float(3); float m3 = stack.get_float(4); float m4 = stack.get_float(5); float m5 = stack.get_float(6); float m6 = stack.get_float(7); float m7 = stack.get_float(8); float m8 = stack.get_float(9); float m9 = stack.get_float(10); float m10 = stack.get_float(11); float m11 = stack.get_float(12); float m12 = stack.get_float(13); float m13 = stack.get_float(14); float m14 = stack.get_float(15); float m15 = stack.get_float(16); stack.push_matrix4x4(Matrix4x4(m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15)); return 1; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_add(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); Matrix4x4& b = stack.get_matrix4x4(2); stack.push_matrix4x4(a + b); return 1; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_subtract(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); Matrix4x4& b = stack.get_matrix4x4(2); stack.push_matrix4x4(a - b); return 1; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_multiply(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); Matrix4x4& b = stack.get_matrix4x4(2); stack.push_matrix4x4(a * b); return 1; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_build_rotation_x(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); float k = stack.get_float(2); a.build_rotation_x(k); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_build_rotation_y(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); float k = stack.get_float(2); a.build_rotation_y(k); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_build_rotation_z(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); float k = stack.get_float(2); a.build_rotation_z(k); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_build_rotation(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); Vector3& d = stack.get_vector3(2); float k = stack.get_float(3); a.build_rotation(d, k); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_build_look_at_rh(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); Vector3& pos = stack.get_vector3(2); Vector3& target = stack.get_vector3(3); Vector3& up = stack.get_vector3(4); a.build_look_at_rh(pos, target, up); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_build_look_at_lh(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); Vector3& pos = stack.get_vector3(2); Vector3& target = stack.get_vector3(3); Vector3& up = stack.get_vector3(4); a.build_look_at_lh(pos, target, up); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_build_viewpoint_billboard(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); Vector3& pos = stack.get_vector3(2); Vector3& target = stack.get_vector3(3); Vector3& up = stack.get_vector3(4); a.build_viewpoint_billboard(pos, target, up); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_build_axis_billboard(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); Vector3& pos = stack.get_vector3(2); Vector3& target = stack.get_vector3(3); Vector3& up = stack.get_vector3(4); a.build_axis_billboard(pos, target, up); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_transpose(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); stack.push_matrix4x4(a.transpose()); return 1; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_determinant(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); stack.push_float(a.get_determinant()); return 1; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_invert(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); stack.push_matrix4x4(a.invert()); return 1; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_load_identity(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); a.load_identity(); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_x(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); stack.push_vector3(a.x()); return 1; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_y(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); stack.push_vector3(a.y()); return 1; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_z(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); stack.push_vector3(a.z()); return 1; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_set_x(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); Vector3& x = stack.get_vector3(2); a.set_x(x); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_set_y(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); Vector3& y = stack.get_vector3(2); a.set_y(y); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_set_z(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); Vector3& z = stack.get_vector3(2); a.set_z(z); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_translation(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); stack.push_vector3(a.translation()); return 1; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_set_translation(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); Vector3& trans = stack.get_vector3(2); a.set_translation(trans); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_get_scale(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); stack.push_vector3(a.get_scale()); return 1; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_set_scale(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); Vector3& scale = stack.get_vector3(2); a.set_scale(scale); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_print(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); os::printf("|%.1f|%.1f|%.1f|%.1f|\n", a.m[0], a.m[4], a.m[8], a.m[12]); os::printf("|%.1f|%.1f|%.1f|%.1f|\n", a.m[1], a.m[5], a.m[9], a.m[13]); os::printf("|%.1f|%.1f|%.1f|%.1f|\n", a.m[2], a.m[6], a.m[10], a.m[14]); os::printf("|%.1f|%.1f|%.1f|%.1f|\n", a.m[3], a.m[7], a.m[11], a.m[15]); return 0; } //----------------------------------------------------------------------------- void load_matrix4x4(LuaEnvironment& env) { env.load_module_function("Matrix4x4", "new", matrix4x4); env.load_module_function("Matrix4x4", "add", matrix4x4_add); env.load_module_function("Matrix4x4", "subtract", matrix4x4_subtract); env.load_module_function("Matrix4x4", "multiply", matrix4x4_multiply); env.load_module_function("Matrix4x4", "build_rotation_x", matrix4x4_build_rotation_x); env.load_module_function("Matrix4x4", "build_rotation_y", matrix4x4_build_rotation_y); env.load_module_function("Matrix4x4", "build_rotation_z", matrix4x4_build_rotation_z); env.load_module_function("Matrix4x4", "build_rotation", matrix4x4_build_rotation); env.load_module_function("Matrix4x4", "build_look_at_rh", matrix4x4_build_look_at_rh); env.load_module_function("Matrix4x4", "build_look_at_lh", matrix4x4_build_look_at_rh); env.load_module_function("Matrix4x4", "build_viewpoint_billboard", matrix4x4_build_viewpoint_billboard); env.load_module_function("Matrix4x4", "build_axis_billboard", matrix4x4_build_axis_billboard); env.load_module_function("Matrix4x4", "transpose", matrix4x4_transpose); env.load_module_function("Matrix4x4", "determinant", matrix4x4_determinant); env.load_module_function("Matrix4x4", "invert", matrix4x4_invert); env.load_module_function("Matrix4x4", "load_identity", matrix4x4_load_identity); env.load_module_function("Matrix4x4", "x", matrix4x4_x); env.load_module_function("Matrix4x4", "y", matrix4x4_y); env.load_module_function("Matrix4x4", "z", matrix4x4_z); env.load_module_function("Matrix4x4", "set_x", matrix4x4_set_x); env.load_module_function("Matrix4x4", "set_y", matrix4x4_set_y); env.load_module_function("Matrix4x4", "set_z", matrix4x4_set_z); env.load_module_function("Matrix4x4", "translation", matrix4x4_translation); env.load_module_function("Matrix4x4", "set_translation", matrix4x4_set_translation); env.load_module_function("Matrix4x4", "get_scale", matrix4x4_get_scale); env.load_module_function("Matrix4x4", "set_scale", matrix4x4_set_scale); env.load_module_function("Matrix4x4", "print", matrix4x4_print); } } //namespace crown <commit_msg>Update LuaMatrix4x4<commit_after>/* Copyright (c) 2013 Daniele Bartolini, Michele Rossi Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Matrix4x4.h" #include "Vector3.h" #include "LuaStack.h" #include "LuaEnvironment.h" #include "OS.h" namespace crown { //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4(lua_State* L) { LuaStack stack(L); float m0 = stack.get_float(1); float m1 = stack.get_float(2); float m2 = stack.get_float(3); float m3 = stack.get_float(4); float m4 = stack.get_float(5); float m5 = stack.get_float(6); float m6 = stack.get_float(7); float m7 = stack.get_float(8); float m8 = stack.get_float(9); float m9 = stack.get_float(10); float m10 = stack.get_float(11); float m11 = stack.get_float(12); float m12 = stack.get_float(13); float m13 = stack.get_float(14); float m14 = stack.get_float(15); float m15 = stack.get_float(16); stack.push_matrix4x4(Matrix4x4(m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15)); return 1; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_add(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); Matrix4x4& b = stack.get_matrix4x4(2); stack.push_matrix4x4(a + b); return 1; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_subtract(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); Matrix4x4& b = stack.get_matrix4x4(2); stack.push_matrix4x4(a - b); return 1; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_multiply(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); Matrix4x4& b = stack.get_matrix4x4(2); stack.push_matrix4x4(a * b); return 1; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_build_rotation_x(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); float k = stack.get_float(2); a.build_rotation_x(k); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_build_rotation_y(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); float k = stack.get_float(2); a.build_rotation_y(k); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_build_rotation_z(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); float k = stack.get_float(2); a.build_rotation_z(k); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_build_rotation(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); Vector3& d = stack.get_vector3(2); float k = stack.get_float(3); a.build_rotation(d, k); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_build_look_at_rh(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); Vector3& pos = stack.get_vector3(2); Vector3& target = stack.get_vector3(3); Vector3& up = stack.get_vector3(4); a.build_look_at_rh(pos, target, up); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_build_viewpoint_billboard(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); Vector3& pos = stack.get_vector3(2); Vector3& target = stack.get_vector3(3); Vector3& up = stack.get_vector3(4); a.build_viewpoint_billboard(pos, target, up); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_build_axis_billboard(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); Vector3& pos = stack.get_vector3(2); Vector3& target = stack.get_vector3(3); Vector3& up = stack.get_vector3(4); a.build_axis_billboard(pos, target, up); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_transpose(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); stack.push_matrix4x4(a.transpose()); return 1; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_determinant(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); stack.push_float(a.get_determinant()); return 1; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_invert(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); stack.push_matrix4x4(a.invert()); return 1; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_load_identity(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); a.load_identity(); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_x(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); stack.push_vector3(a.x()); return 1; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_y(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); stack.push_vector3(a.y()); return 1; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_z(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); stack.push_vector3(a.z()); return 1; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_set_x(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); Vector3& x = stack.get_vector3(2); a.set_x(x); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_set_y(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); Vector3& y = stack.get_vector3(2); a.set_y(y); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_set_z(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); Vector3& z = stack.get_vector3(2); a.set_z(z); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_translation(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); stack.push_vector3(a.translation()); return 1; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_set_translation(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); Vector3& trans = stack.get_vector3(2); a.set_translation(trans); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_get_scale(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); stack.push_vector3(a.get_scale()); return 1; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_set_scale(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); Vector3& scale = stack.get_vector3(2); a.set_scale(scale); return 0; } //----------------------------------------------------------------------------- CE_EXPORT int matrix4x4_print(lua_State* L) { LuaStack stack(L); Matrix4x4& a = stack.get_matrix4x4(1); os::printf("|%.1f|%.1f|%.1f|%.1f|\n", a.m[0], a.m[4], a.m[8], a.m[12]); os::printf("|%.1f|%.1f|%.1f|%.1f|\n", a.m[1], a.m[5], a.m[9], a.m[13]); os::printf("|%.1f|%.1f|%.1f|%.1f|\n", a.m[2], a.m[6], a.m[10], a.m[14]); os::printf("|%.1f|%.1f|%.1f|%.1f|\n", a.m[3], a.m[7], a.m[11], a.m[15]); return 0; } //----------------------------------------------------------------------------- void load_matrix4x4(LuaEnvironment& env) { env.load_module_function("Matrix4x4", "new", matrix4x4); env.load_module_function("Matrix4x4", "add", matrix4x4_add); env.load_module_function("Matrix4x4", "subtract", matrix4x4_subtract); env.load_module_function("Matrix4x4", "multiply", matrix4x4_multiply); env.load_module_function("Matrix4x4", "build_rotation_x", matrix4x4_build_rotation_x); env.load_module_function("Matrix4x4", "build_rotation_y", matrix4x4_build_rotation_y); env.load_module_function("Matrix4x4", "build_rotation_z", matrix4x4_build_rotation_z); env.load_module_function("Matrix4x4", "build_rotation", matrix4x4_build_rotation); env.load_module_function("Matrix4x4", "build_look_at_rh", matrix4x4_build_look_at_rh); env.load_module_function("Matrix4x4", "build_viewpoint_billboard", matrix4x4_build_viewpoint_billboard); env.load_module_function("Matrix4x4", "build_axis_billboard", matrix4x4_build_axis_billboard); env.load_module_function("Matrix4x4", "transpose", matrix4x4_transpose); env.load_module_function("Matrix4x4", "determinant", matrix4x4_determinant); env.load_module_function("Matrix4x4", "invert", matrix4x4_invert); env.load_module_function("Matrix4x4", "load_identity", matrix4x4_load_identity); env.load_module_function("Matrix4x4", "x", matrix4x4_x); env.load_module_function("Matrix4x4", "y", matrix4x4_y); env.load_module_function("Matrix4x4", "z", matrix4x4_z); env.load_module_function("Matrix4x4", "set_x", matrix4x4_set_x); env.load_module_function("Matrix4x4", "set_y", matrix4x4_set_y); env.load_module_function("Matrix4x4", "set_z", matrix4x4_set_z); env.load_module_function("Matrix4x4", "translation", matrix4x4_translation); env.load_module_function("Matrix4x4", "set_translation", matrix4x4_set_translation); env.load_module_function("Matrix4x4", "get_scale", matrix4x4_get_scale); env.load_module_function("Matrix4x4", "set_scale", matrix4x4_set_scale); env.load_module_function("Matrix4x4", "print", matrix4x4_print); } } //namespace crown <|endoftext|>
<commit_before>#include "stdafx.h" #include "FormModule.h" using namespace System::IO; namespace Ndapi { FormModule::FormModule(d2fob* form_module) : NdapiObject(form_module) { } FormModule::FormModule(String^ name) { Create(name, D2FFO_FORM_MODULE); } FormModule^ FormModule::Open(String^ file) { if (!File::Exists(file)) { throw gcnew FileNotFoundException("Module file not found", file); } NativeString<text> filename(file); d2ffmd* form_module; auto status = d2ffmdld_Load(NdapiContext::Context, &form_module, filename, FALSE); if (status != D2FS_SUCCESS) { throw gcnew NdapiException(String::Format("Error opening the form module. Path: {0}", file), status); } return gcnew FormModule(form_module); } void FormModule::Save() { Save(nullptr); } void FormModule::Save(String^ path) { Save(path, false); } void FormModule::Save(String^ path, bool saveInDatabase) { NativeString<text> module_path(path); auto status = d2ffmdsv_Save(NdapiContext::Context, _handler, module_path, saveInDatabase); if (status != D2FS_SUCCESS) { throw gcnew NdapiException(String::Format("Error saving the form module. Path: {0}", path), status); } } void FormModule::CompileFile() { auto status = d2ffmdcf_CompileFile(NdapiContext::Context, _handler); if (status != D2FS_SUCCESS) { throw gcnew NdapiException(String::Format("Error compiling the form module."), status); } } void FormModule::CompileObjects() { auto status = d2ffmdco_CompileObj(NdapiContext::Context, _handler); if (status != D2FS_SUCCESS) { throw gcnew NdapiException(String::Format("Error compiling the PL/SQL objects."), status); } } String^ FormModule::Comment::get() { return GetStringProperty(D2FP_COMMENT); } void FormModule::Comment::set(String^ value) { SetStringProperty(D2FP_COMMENT, value); } String^ FormModule::ConsoleWindow::get() { return GetStringProperty(D2FP_CONSOLE_WIN); } void FormModule::ConsoleWindow::set(String^ value) { SetStringProperty(D2FP_CONSOLE_WIN, value); } bool FormModule::DeferRequiredEnforcement::get() { return GetBooleanProperty(D2FP_DEFER_REQ_ENF); } void FormModule::DeferRequiredEnforcement::set(bool value) { SetBooleanProperty(D2FP_DEFER_REQ_ENF, value); } NdapiObject^ FormModule::FirstNavigationBlock::get() { return GetObjectProperty<NdapiObject^>(D2FP_FRST_NAVIGATION_BLK_OBJ); } void FormModule::FirstNavigationBlock::set(NdapiObject^ value) { SetObjectProperty(D2FP_FRST_NAVIGATION_BLK_OBJ, value); } String^ FormModule::HelpBookTitle::get() { return GetStringProperty(D2FP_HELP_BOOK_TITLE); } void FormModule::HelpBookTitle::set(String^ value) { SetStringProperty(D2FP_HELP_BOOK_TITLE, value); } String^ FormModule::HorizontalToolbarCanvas::get() { return GetStringProperty(D2FP_HORZ_TLBR_CNV); } void FormModule::HorizontalToolbarCanvas::set(String^ value) { SetStringProperty(D2FP_HORZ_TLBR_CNV, value); } String^ FormModule::InitialMenu::get() { return GetStringProperty(D2FP_INIT_MNU); } void FormModule::InitialMenu::set(String^ value) { SetStringProperty(D2FP_INIT_MNU, value); } Ndapi::InteractionMode FormModule::InteractionMode::get() { return safe_cast<Ndapi::InteractionMode>(GetNumberProperty(D2FP_INTERACTION_MODE)); } void FormModule::InteractionMode::set(Ndapi::InteractionMode value) { SetNumberProperty(D2FP_INTERACTION_MODE, safe_cast<long>(value)); } Ndapi::IsolationMode FormModule::IsolationMode::get() { return safe_cast<Ndapi::IsolationMode>(GetNumberProperty(D2FP_ISOLATION_MODE)); } void FormModule::IsolationMode::set(Ndapi::IsolationMode value) { SetNumberProperty(D2FP_ISOLATION_MODE, safe_cast<long>(value)); } Ndapi::LanguageDirection FormModule::LanguageDirection::get() { return safe_cast<Ndapi::LanguageDirection>(GetNumberProperty(D2FP_LANG_DIR)); } void FormModule::LanguageDirection::set(Ndapi::LanguageDirection value) { SetNumberProperty(D2FP_LANG_DIR, safe_cast<long>(value)); } long FormModule::MaximumQueryTime::get() { return GetNumberProperty(D2FP_MAX_QRY_TIME); } void FormModule::MaximumQueryTime::set(long value) { SetNumberProperty(D2FP_MAX_QRY_TIME, value); } long FormModule::MaxRecordsFetched::get() { return GetNumberProperty(D2FP_MAX_RECS_FETCHED); } void FormModule::MaxRecordsFetched::set(long value) { SetNumberProperty(D2FP_MAX_RECS_FETCHED, value); } String^ FormModule::MenuModule::get() { return GetStringProperty(D2FP_MNU_MOD); } void FormModule::MenuModule::set(String^ value) { SetStringProperty(D2FP_MNU_MOD, value); } String^ FormModule::MenuRole::get() { return GetStringProperty(D2FP_MNU_ROLE); } void FormModule::MenuRole::set(String^ value) { SetStringProperty(D2FP_MNU_ROLE, value); } Ndapi::MenuSource FormModule::MenuSource::get() { return safe_cast<Ndapi::MenuSource>(GetNumberProperty(D2FP_MNU_SRC)); } void FormModule::MenuSource::set(Ndapi::MenuSource value) { SetNumberProperty(D2FP_MNU_SRC, safe_cast<long>(value)); } Ndapi::MenuStyle FormModule::MenuStyle::get() { return safe_cast<Ndapi::MenuStyle>(GetNumberProperty(D2FP_MNU_STY)); } void FormModule::MenuStyle::set(Ndapi::MenuStyle value) { SetNumberProperty(D2FP_MNU_STY, safe_cast<long>(value)); } Ndapi::MouseNavigationLimit FormModule::MouseNavigationLimit::get() { return safe_cast<Ndapi::MouseNavigationLimit>(GetNumberProperty(D2FP_MOUSE_NAVIGATION_LMT)); } void FormModule::MouseNavigationLimit::set(Ndapi::MouseNavigationLimit value) { SetNumberProperty(D2FP_MOUSE_NAVIGATION_LMT, safe_cast<long>(value)); } NdapiObject^ FormModule::CurrentRecordVisualAttribute::get() { return GetObjectProperty<NdapiObject^>(D2FP_REC_VAT_GRP_OBJ); } void FormModule::CurrentRecordVisualAttribute::set(NdapiObject^ value) { SetObjectProperty(D2FP_REC_VAT_GRP_OBJ, value); } Ndapi::RuntimeCompatibility FormModule::RuntimeCompatibility::get() { return safe_cast<Ndapi::RuntimeCompatibility>(GetNumberProperty(D2FP_RUNTIME_COMP)); } void FormModule::RuntimeCompatibility::set(Ndapi::RuntimeCompatibility value) { SetNumberProperty(D2FP_RUNTIME_COMP, safe_cast<long>(value)); } String^ FormModule::Title::get() { return GetStringProperty(D2FP_TITLE); } void FormModule::Title::set(String^ value) { SetStringProperty(D2FP_TITLE, value); } bool FormModule::Use3DControls::get() { return GetBooleanProperty(D2FP_USE_3D_CNTRLS); } void FormModule::Use3DControls::set(bool value) { SetBooleanProperty(D2FP_USE_3D_CNTRLS, value); } Ndapi::ValidationUnit FormModule::ValidationUnit::get() { return safe_cast<Ndapi::ValidationUnit>(GetNumberProperty(D2FP_VALIDATION_UNIT)); } void FormModule::ValidationUnit::set(Ndapi::ValidationUnit value) { SetNumberProperty(D2FP_VALIDATION_UNIT, safe_cast<long>(value)); } String^ FormModule::VerticalToolbarCanvas::get() { return GetStringProperty(D2FP_VERT_TLBR_CNV); } void FormModule::VerticalToolbarCanvas::set(String^ value) { SetStringProperty(D2FP_VERT_TLBR_CNV, value); } NdapiEnumerator<ProgramUnit^>^ FormModule::ProgramUnits::get() { return gcnew NdapiEnumerator<ProgramUnit^>(_handler, D2FP_PROG_UNIT); } FormModule::~FormModule() { d2ffmdde_Destroy(NdapiContext::Context, safe_cast<d2ffmd*>(_handler)); } }<commit_msg>Verify MaximumQueryTime and MaxRecordsFetched in FormModule<commit_after>#include "stdafx.h" #include "FormModule.h" using namespace System::IO; namespace Ndapi { FormModule::FormModule(d2fob* form_module) : NdapiObject(form_module) { } FormModule::FormModule(String^ name) { Create(name, D2FFO_FORM_MODULE); } FormModule^ FormModule::Open(String^ file) { if (!File::Exists(file)) { throw gcnew FileNotFoundException("Module file not found", file); } NativeString<text> filename(file); d2ffmd* form_module; auto status = d2ffmdld_Load(NdapiContext::Context, &form_module, filename, FALSE); if (status != D2FS_SUCCESS) { throw gcnew NdapiException(String::Format("Error opening the form module. Path: {0}", file), status); } return gcnew FormModule(form_module); } void FormModule::Save() { Save(nullptr); } void FormModule::Save(String^ path) { Save(path, false); } void FormModule::Save(String^ path, bool saveInDatabase) { NativeString<text> module_path(path); auto status = d2ffmdsv_Save(NdapiContext::Context, _handler, module_path, saveInDatabase); if (status != D2FS_SUCCESS) { throw gcnew NdapiException(String::Format("Error saving the form module. Path: {0}", path), status); } } void FormModule::CompileFile() { auto status = d2ffmdcf_CompileFile(NdapiContext::Context, _handler); if (status != D2FS_SUCCESS) { throw gcnew NdapiException(String::Format("Error compiling the form module."), status); } } void FormModule::CompileObjects() { auto status = d2ffmdco_CompileObj(NdapiContext::Context, _handler); if (status != D2FS_SUCCESS) { throw gcnew NdapiException(String::Format("Error compiling the PL/SQL objects."), status); } } String^ FormModule::Comment::get() { return GetStringProperty(D2FP_COMMENT); } void FormModule::Comment::set(String^ value) { SetStringProperty(D2FP_COMMENT, value); } String^ FormModule::ConsoleWindow::get() { return GetStringProperty(D2FP_CONSOLE_WIN); } void FormModule::ConsoleWindow::set(String^ value) { SetStringProperty(D2FP_CONSOLE_WIN, value); } bool FormModule::DeferRequiredEnforcement::get() { return GetBooleanProperty(D2FP_DEFER_REQ_ENF); } void FormModule::DeferRequiredEnforcement::set(bool value) { SetBooleanProperty(D2FP_DEFER_REQ_ENF, value); } NdapiObject^ FormModule::FirstNavigationBlock::get() { return GetObjectProperty<NdapiObject^>(D2FP_FRST_NAVIGATION_BLK_OBJ); } void FormModule::FirstNavigationBlock::set(NdapiObject^ value) { SetObjectProperty(D2FP_FRST_NAVIGATION_BLK_OBJ, value); } String^ FormModule::HelpBookTitle::get() { return GetStringProperty(D2FP_HELP_BOOK_TITLE); } void FormModule::HelpBookTitle::set(String^ value) { SetStringProperty(D2FP_HELP_BOOK_TITLE, value); } String^ FormModule::HorizontalToolbarCanvas::get() { return GetStringProperty(D2FP_HORZ_TLBR_CNV); } void FormModule::HorizontalToolbarCanvas::set(String^ value) { SetStringProperty(D2FP_HORZ_TLBR_CNV, value); } String^ FormModule::InitialMenu::get() { return GetStringProperty(D2FP_INIT_MNU); } void FormModule::InitialMenu::set(String^ value) { SetStringProperty(D2FP_INIT_MNU, value); } Ndapi::InteractionMode FormModule::InteractionMode::get() { return safe_cast<Ndapi::InteractionMode>(GetNumberProperty(D2FP_INTERACTION_MODE)); } void FormModule::InteractionMode::set(Ndapi::InteractionMode value) { SetNumberProperty(D2FP_INTERACTION_MODE, safe_cast<long>(value)); } Ndapi::IsolationMode FormModule::IsolationMode::get() { return safe_cast<Ndapi::IsolationMode>(GetNumberProperty(D2FP_ISOLATION_MODE)); } void FormModule::IsolationMode::set(Ndapi::IsolationMode value) { SetNumberProperty(D2FP_ISOLATION_MODE, safe_cast<long>(value)); } Ndapi::LanguageDirection FormModule::LanguageDirection::get() { return safe_cast<Ndapi::LanguageDirection>(GetNumberProperty(D2FP_LANG_DIR)); } void FormModule::LanguageDirection::set(Ndapi::LanguageDirection value) { SetNumberProperty(D2FP_LANG_DIR, safe_cast<long>(value)); } long FormModule::MaximumQueryTime::get() { return GetNumberProperty(D2FP_MAX_QRY_TIME); } void FormModule::MaximumQueryTime::set(long value) { if (value < 0) { throw gcnew ArgumentOutOfRangeException("value", value, "MaximumQueryTime cannot be negative."); } SetNumberProperty(D2FP_MAX_QRY_TIME, value); } long FormModule::MaxRecordsFetched::get() { return GetNumberProperty(D2FP_MAX_RECS_FETCHED); } void FormModule::MaxRecordsFetched::set(long value) { if (value < 0) { throw gcnew ArgumentOutOfRangeException("value", value, "MaxRecordsFetched cannot be negative."); } SetNumberProperty(D2FP_MAX_RECS_FETCHED, value); } String^ FormModule::MenuModule::get() { return GetStringProperty(D2FP_MNU_MOD); } void FormModule::MenuModule::set(String^ value) { SetStringProperty(D2FP_MNU_MOD, value); } String^ FormModule::MenuRole::get() { return GetStringProperty(D2FP_MNU_ROLE); } void FormModule::MenuRole::set(String^ value) { SetStringProperty(D2FP_MNU_ROLE, value); } Ndapi::MenuSource FormModule::MenuSource::get() { return safe_cast<Ndapi::MenuSource>(GetNumberProperty(D2FP_MNU_SRC)); } void FormModule::MenuSource::set(Ndapi::MenuSource value) { SetNumberProperty(D2FP_MNU_SRC, safe_cast<long>(value)); } Ndapi::MenuStyle FormModule::MenuStyle::get() { return safe_cast<Ndapi::MenuStyle>(GetNumberProperty(D2FP_MNU_STY)); } void FormModule::MenuStyle::set(Ndapi::MenuStyle value) { SetNumberProperty(D2FP_MNU_STY, safe_cast<long>(value)); } Ndapi::MouseNavigationLimit FormModule::MouseNavigationLimit::get() { return safe_cast<Ndapi::MouseNavigationLimit>(GetNumberProperty(D2FP_MOUSE_NAVIGATION_LMT)); } void FormModule::MouseNavigationLimit::set(Ndapi::MouseNavigationLimit value) { SetNumberProperty(D2FP_MOUSE_NAVIGATION_LMT, safe_cast<long>(value)); } NdapiObject^ FormModule::CurrentRecordVisualAttribute::get() { return GetObjectProperty<NdapiObject^>(D2FP_REC_VAT_GRP_OBJ); } void FormModule::CurrentRecordVisualAttribute::set(NdapiObject^ value) { SetObjectProperty(D2FP_REC_VAT_GRP_OBJ, value); } Ndapi::RuntimeCompatibility FormModule::RuntimeCompatibility::get() { return safe_cast<Ndapi::RuntimeCompatibility>(GetNumberProperty(D2FP_RUNTIME_COMP)); } void FormModule::RuntimeCompatibility::set(Ndapi::RuntimeCompatibility value) { SetNumberProperty(D2FP_RUNTIME_COMP, safe_cast<long>(value)); } String^ FormModule::Title::get() { return GetStringProperty(D2FP_TITLE); } void FormModule::Title::set(String^ value) { SetStringProperty(D2FP_TITLE, value); } bool FormModule::Use3DControls::get() { return GetBooleanProperty(D2FP_USE_3D_CNTRLS); } void FormModule::Use3DControls::set(bool value) { SetBooleanProperty(D2FP_USE_3D_CNTRLS, value); } Ndapi::ValidationUnit FormModule::ValidationUnit::get() { return safe_cast<Ndapi::ValidationUnit>(GetNumberProperty(D2FP_VALIDATION_UNIT)); } void FormModule::ValidationUnit::set(Ndapi::ValidationUnit value) { SetNumberProperty(D2FP_VALIDATION_UNIT, safe_cast<long>(value)); } String^ FormModule::VerticalToolbarCanvas::get() { return GetStringProperty(D2FP_VERT_TLBR_CNV); } void FormModule::VerticalToolbarCanvas::set(String^ value) { SetStringProperty(D2FP_VERT_TLBR_CNV, value); } NdapiEnumerator<ProgramUnit^>^ FormModule::ProgramUnits::get() { return gcnew NdapiEnumerator<ProgramUnit^>(_handler, D2FP_PROG_UNIT); } FormModule::~FormModule() { d2ffmdde_Destroy(NdapiContext::Context, safe_cast<d2ffmd*>(_handler)); } }<|endoftext|>
<commit_before>/********************************************************************** * $Id$ * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2001-2002 Vivid Solutions Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * **********************************************************************/ #include <geos/geom/Geometry.h> #include <geos/geom/Polygon.h> #include <geos/geom/MultiPolygon.h> #include <geos/geom/prep/PreparedPolygon.h> #include <geos/geom/prep/PreparedPolygonContainsProperly.h> #include <geos/geom/prep/PreparedPolygonPredicate.h> #include <geos/noding/SegmentString.h> #include <geos/noding/SegmentStringUtil.h> #include <geos/noding/FastSegmentSetIntersectionFinder.h> namespace geos { namespace geom { // geos.geom namespace prep { // geos.geom.prep // // private: // // // protected: // // // public: // bool PreparedPolygonContainsProperly::containsProperly( const geom::Geometry * geom) { // Do point-in-poly tests first, since they are cheaper and may result // in a quick negative result. // If a point of any test components does not lie in target, result is false bool isAllInPrepGeomArea = isAllTestComponentsInTargetInterior( geom); if ( !isAllInPrepGeomArea ) return false; // If any segments intersect, result is false noding::SegmentString::ConstVect lineSegStr; noding::SegmentStringUtil::extractSegmentStrings( geom, lineSegStr); bool segsIntersect = prepPoly->getIntersectionFinder()->intersects( &lineSegStr); for ( size_t i = 0, ni = lineSegStr.size(); i < ni; i++ ) delete lineSegStr[ i ]; if (segsIntersect) return false; if ( geom->getGeometryTypeId() == geos::geom::GEOS_MULTIPOLYGON || geom->getGeometryTypeId() == geos::geom::GEOS_POLYGON ) { // TODO: generalize this to handle GeometryCollections bool isTargetGeomInTestArea = isAnyTargetComponentInTestArea( geom, prepPoly->getRepresentativePoints()); if (isTargetGeomInTestArea) return false; } return true; } } // namespace geos.geom.prep } // namespace geos.geom } // namespace geos /********************************************************************** * $Log$ * **********************************************************************/ <commit_msg>One last memory leak fix.<commit_after>/********************************************************************** * $Id$ * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2001-2002 Vivid Solutions Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * **********************************************************************/ #include <geos/geom/Geometry.h> #include <geos/geom/Polygon.h> #include <geos/geom/MultiPolygon.h> #include <geos/geom/prep/PreparedPolygon.h> #include <geos/geom/prep/PreparedPolygonContainsProperly.h> #include <geos/geom/prep/PreparedPolygonPredicate.h> #include <geos/noding/SegmentString.h> #include <geos/noding/SegmentStringUtil.h> #include <geos/noding/FastSegmentSetIntersectionFinder.h> namespace geos { namespace geom { // geos.geom namespace prep { // geos.geom.prep // // private: // // // protected: // // // public: // bool PreparedPolygonContainsProperly::containsProperly( const geom::Geometry * geom) { // Do point-in-poly tests first, since they are cheaper and may result // in a quick negative result. // If a point of any test components does not lie in target, result is false bool isAllInPrepGeomArea = isAllTestComponentsInTargetInterior( geom); if ( !isAllInPrepGeomArea ) return false; // If any segments intersect, result is false noding::SegmentString::ConstVect lineSegStr; noding::SegmentStringUtil::extractSegmentStrings( geom, lineSegStr); bool segsIntersect = prepPoly->getIntersectionFinder()->intersects( &lineSegStr); for ( size_t i = 0, ni = lineSegStr.size(); i < ni; i++ ) { delete lineSegStr[ i ]; delete lineSegStr[ i ]->getCoordinates(); } if (segsIntersect) return false; if ( geom->getGeometryTypeId() == geos::geom::GEOS_MULTIPOLYGON || geom->getGeometryTypeId() == geos::geom::GEOS_POLYGON ) { // TODO: generalize this to handle GeometryCollections bool isTargetGeomInTestArea = isAnyTargetComponentInTestArea( geom, prepPoly->getRepresentativePoints()); if (isTargetGeomInTestArea) return false; } return true; } } // namespace geos.geom.prep } // namespace geos.geom } // namespace geos /********************************************************************** * $Log$ * **********************************************************************/ <|endoftext|>
<commit_before>#pragma once #include <memory> #include <vector> #include <rdestl/vector.h> #include "Logger.hpp" namespace noob { class application; template <typename T> class handle { public: handle() noexcept(true) : inner(0) {} bool operator==(const noob::handle<T> other) const noexcept(true) { return (inner == other.inner); } bool operator!=(const noob::handle<T> other) const noexcept(true) { return (inner != other.inner); } bool operator<(const noob::handle<T> other) const noexcept(true) { return (inner < other.inner); } bool operator>(const noob::handle<T> other) const noexcept(true) { return (inner > other.inner); } uint32_t get_inner() const noexcept(true) { return inner; } static handle make(uint32_t i) { handle h; h.inner = i; return h; } protected: uint32_t inner; }; template <typename T> class component { friend class application; public: inline T get(noob::handle<T> h) const noexcept(true) { if (exists(h)) return items[h.get_inner()]; else { logger::log("Invalid access to component"); return items[0]; } } /* T& get_ref(handle<T> h) noexcept(true) { return get_ref(h.get_inner()); } */ inline handle<T> add(const T& t) noexcept(true) { items.push_back(t); return handle<T>::make(items.size() - 1); } inline bool exists(handle<T> h) const noexcept(true) { return (h.get_inner() < items.size()); } inline void set(handle<T> h, const T t) noexcept(true) { if (exists(h)) { items[h.get_inner()] = t; } } void empty() noexcept(true) { items.resize(0); } inline uint32_t count() const noexcept(true) { return items.size(); } protected: rde::vector<T> items; }; template <typename T> class component_dynamic { public: T* get(handle<T> h) const noexcept(true) { if (exists(h)) { T* temp = items[h.get_inner()].get(); return temp; } else { logger::log("Invalid access to component"); return items[0].get(); } } handle<T> add(std::unique_ptr<T>&& t) noexcept(true) { // items.emplace_back(std::move(t)); items.push_back(std::move(t)); return handle<T>::make(items.size()-1); } bool exists(handle<T> h) const noexcept(true) { bool results = h.get_inner() < items.size(); return results; } void set(handle<T> h, std::unique_ptr<T>&& t) noexcept(true) { if (exists(h)) { items[h.get_inner()] = std::move(t); } } void empty() noexcept(true) { items.resize(0); } uint32_t count() const noexcept(true) { return items.size(); } protected: std::vector<std::unique_ptr<T>> items; }; } <commit_msg>Add get_ptr to component<commit_after>#pragma once #include <memory> #include <vector> #include <rdestl/vector.h> #include "Logger.hpp" namespace noob { class application; template <typename T> class handle { public: handle() noexcept(true) : inner(0) {} bool operator==(const noob::handle<T> other) const noexcept(true) { return (inner == other.inner); } bool operator!=(const noob::handle<T> other) const noexcept(true) { return (inner != other.inner); } bool operator<(const noob::handle<T> other) const noexcept(true) { return (inner < other.inner); } bool operator>(const noob::handle<T> other) const noexcept(true) { return (inner > other.inner); } uint32_t get_inner() const noexcept(true) { return inner; } static handle make(uint32_t i) { handle h; h.inner = i; return h; } protected: uint32_t inner; }; template <typename T> class component { friend class application; public: inline T get(noob::handle<T> h) const noexcept(true) { if (exists(h)) return items[h.get_inner()]; else { logger::log("Invalid access to component"); return items[0]; } } std::tuple<bool, T*> get_ptr(handle<T> h) const noexcept(true) { if (exists(h)) { return std::make_tuple(true, &(items[h.get_inner()])); } else { return std::make_tuple(false, &(items[h.get_inner()])); } } inline handle<T> add(const T& t) noexcept(true) { items.push_back(t); return handle<T>::make(items.size() - 1); } inline bool exists(handle<T> h) const noexcept(true) { return (h.get_inner() < items.size()); } inline void set(handle<T> h, const T t) noexcept(true) { if (exists(h)) { items[h.get_inner()] = t; } } void empty() noexcept(true) { items.resize(0); } inline uint32_t count() const noexcept(true) { return items.size(); } protected: rde::vector<T> items; }; template <typename T> class component_dynamic { public: T* get(handle<T> h) const noexcept(true) { if (exists(h)) { T* temp = items[h.get_inner()].get(); return temp; } else { logger::log("Invalid access to component"); return items[0].get(); } } handle<T> add(std::unique_ptr<T>&& t) noexcept(true) { // items.emplace_back(std::move(t)); items.push_back(std::move(t)); return handle<T>::make(items.size()-1); } bool exists(handle<T> h) const noexcept(true) { bool results = h.get_inner() < items.size(); return results; } void set(handle<T> h, std::unique_ptr<T>&& t) noexcept(true) { if (exists(h)) { items[h.get_inner()] = std::move(t); } } void empty() noexcept(true) { items.resize(0); } uint32_t count() const noexcept(true) { return items.size(); } protected: std::vector<std::unique_ptr<T>> items; }; } <|endoftext|>
<commit_before>/*************************************************************************** cryptographyplugin.cpp - description ------------------- begin : jeu nov 14 2002 copyright : (C) 2002 by Olivier Goffart email : [email protected] ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <qstylesheet.h> #include <qtimer.h> #include <kdebug.h> #include <kaction.h> #include <kgenericfactory.h> #include "kopetemetacontact.h" #include "kopetemessagemanagerfactory.h" #include "cryptographyplugin.h" #include "cryptographypreferences.h" #include "cryptographyselectuserkey.h" #include "kgpginterface.h" K_EXPORT_COMPONENT_FACTORY( kopete_cryptography, KGenericFactory<CryptographyPlugin> ); CryptographyPlugin::CryptographyPlugin( QObject *parent, const char *name, const QStringList &/*args*/ ) : KopetePlugin( parent, name ) , m_cachedPass() { if( !pluginStatic_ ) pluginStatic_=this; //TODO: found a pixmap m_prefs = new CryptographyPreferences ( "kgpg", this ); connect( KopeteMessageManagerFactory::factory(), SIGNAL( aboutToDisplay( KopeteMessage & ) ), SLOT( slotIncomingMessage( KopeteMessage & ) ) ); connect( KopeteMessageManagerFactory::factory(), SIGNAL( aboutToSend( KopeteMessage & ) ), SLOT( slotOutgoingMessage( KopeteMessage & ) ) ); m_collection=0l; m_currentMetaContact=0L; m_cachedPass_timer = new QTimer(this, "m_cachedPass_timer" ); QObject::connect(m_cachedPass_timer, SIGNAL(timeout()), this, SLOT(slotForgetCachedPass() )); } CryptographyPlugin::~CryptographyPlugin() { pluginStatic_ = 0L; delete m_collection; } CryptographyPlugin* CryptographyPlugin::plugin() { return pluginStatic_ ; } CryptographyPlugin* CryptographyPlugin::pluginStatic_ = 0L; QCString CryptographyPlugin::cachedPass() { return pluginStatic_->m_cachedPass; } void CryptographyPlugin::setCachedPass(const QCString& p) { if(pluginStatic_->m_prefs->cacheMode()==CryptographyPreferences::Never) return; if(pluginStatic_->m_prefs->cacheMode()==CryptographyPreferences::Time) pluginStatic_->m_cachedPass_timer->start(pluginStatic_->m_prefs->cacheTime() * 60000, false); pluginStatic_->m_cachedPass=p; } KActionCollection *CryptographyPlugin::customContextMenuActions(KopeteMetaContact *m) { delete m_collection; m_collection = new KActionCollection(this); KAction *action=new KAction( i18n("&Select Cryptography Public Key"), "kgpg", 0, this, SLOT (slotSelectContactKey()), m_collection); m_collection->insert(action); m_currentMetaContact=m; return m_collection; } /*KActionCollection *CryptographyPlugin::customChatActions(KopeteMessageManager *KMM) { delete m_actionCollection; m_actionCollection = new KActionCollection(this); KAction *actionTranslate = new KAction( i18n ("Translate"), 0, this, SLOT( slotTranslateChat() ), m_actionCollection, "actionTranslate" ); m_actionCollection->insert( actionTranslate ); m_currentMessageManager=KMM; return m_actionCollection; }*/ void CryptographyPlugin::slotIncomingMessage( KopeteMessage& msg ) { QString body=msg.plainBody(); if(!body.startsWith("-----BEGIN PGP MESSAGE----")) return; if(msg.direction() != KopeteMessage::Inbound) { QString plainBody; if ( m_cachedMessages.contains( body ) ) { plainBody = m_cachedMessages[ body ]; m_cachedMessages.remove( body ); } else { plainBody = KgpgInterface::KgpgDecryptText( body, m_prefs->privateKey() ); } if(!plainBody.isEmpty()) { msg.setBody("<table width=\"100%\" border=0 cellspacing=0 cellpadding=0><tr bgcolor=\"#41FFFF\"><td><font size=\"-1\"><b>"+i18n("Outgoing Encrypted Message")+"</b></font></td></tr><tr bgcolor=\"#DDFFFF\"><td>"+QStyleSheet::escape(plainBody)+"</td></tr></table>" ,KopeteMessage::RichText); } //if there are too messages in cache, clear the cache if(m_cachedMessages.count()>5) m_cachedMessages.clear(); return; } body=KgpgInterface::KgpgDecryptText(body, m_prefs->privateKey()); if(!body.isEmpty()) { body="<table width=\"100%\" border=0 cellspacing=0 cellpadding=0><tr bgcolor=\"#41FF41\"><td><font size=\"-1\"><b>"+i18n("Incoming Encrypted Message")+"</b></font></td></tr><tr bgcolor=\"#DDFFDD\"><td>"+QStyleSheet::escape(body)+"</td></tr></table>"; msg.setBody(body,KopeteMessage::RichText); } } void CryptographyPlugin::slotOutgoingMessage( KopeteMessage& msg ) { if(msg.direction() != KopeteMessage::Outbound) return; QStringList keys; QPtrList<KopeteContact> contactlist = msg.to(); for( KopeteContact *c = contactlist.first(); c; c = contactlist.next() ) { QString tmpKey; if( c->metaContact() ) tmpKey = c->metaContact()->pluginData( this, "gpgKey" ); if( tmpKey.isEmpty() ) { kdDebug( 14303 ) << "CryptographyPlugin::slotOutgoingMessage: no key selected for one contact" <<endl; return; } keys.append( tmpKey ); } // always encrypt to self, too if(m_prefs->alsoMyKey()) keys.append( m_prefs->privateKey() ); QString key = keys.join( " " ); if(key.isEmpty()) { kdDebug(14303) << "CryptographyPlugin::slotOutgoingMessage: empty key" <<endl; return; } QString original=msg.plainBody(); /* Code From KGPG */ ////////////////// encode from editor QString encryptOptions=""; //if (utrust==true) encryptOptions+=" --always-trust "; //if (arm==true) encryptOptions+=" --armor "; /* if (pubcryptography==true) { if (gpgversion<120) encryptOptions+=" --compress-algo 1 --cipher-algo cast5 "; else encryptOptions+=" --cryptography6 "; }*/ // if (selec==NULL) {KMessageBox::sorry(0,i18n("You have not choosen an encryption key..."));return;} QString resultat=KgpgInterface::KgpgEncryptText(original,key,encryptOptions); if (!resultat.isEmpty()) { msg.setBody(resultat,KopeteMessage::PlainText); m_cachedMessages.insert(resultat,original); } else kdDebug(14303) << "CryptographyPlugin::slotOutgoingMessage: empty result" <<endl; } void CryptographyPlugin::slotSelectContactKey() { QString key = m_currentMetaContact->pluginData( this, "gpgKey" ); CryptographySelectUserKey *opts = new CryptographySelectUserKey( key, m_currentMetaContact ); opts->exec(); if( opts->result() ) { key = opts->publicKey(); m_currentMetaContact->setPluginData( this, "gpgKey", key ); } delete opts; } void CryptographyPlugin::slotForgetCachedPass() { m_cachedPass=QCString(); m_cachedPass_timer->stop(); } #include "cryptographyplugin.moc" // vim: set noet ts=4 sts=4 sw=4: <commit_msg><commit_after>/*************************************************************************** cryptographyplugin.cpp - description ------------------- begin : jeu nov 14 2002 copyright : (C) 2002 by Olivier Goffart email : [email protected] ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <qstylesheet.h> #include <qtimer.h> #include <kdebug.h> #include <kaction.h> #include <kgenericfactory.h> #include "kopetemetacontact.h" #include "kopetemessagemanagerfactory.h" #include "cryptographyplugin.h" #include "cryptographypreferences.h" #include "cryptographyselectuserkey.h" #include "kgpginterface.h" K_EXPORT_COMPONENT_FACTORY( kopete_cryptography, KGenericFactory<CryptographyPlugin> ); CryptographyPlugin::CryptographyPlugin( QObject *parent, const char *name, const QStringList &/*args*/ ) : KopetePlugin( parent, name ) , m_cachedPass() { if( !pluginStatic_ ) pluginStatic_=this; //TODO: found a pixmap m_prefs = new CryptographyPreferences ( "kgpg", this ); connect( KopeteMessageManagerFactory::factory(), SIGNAL( aboutToDisplay( KopeteMessage & ) ), SLOT( slotIncomingMessage( KopeteMessage & ) ) ); connect( KopeteMessageManagerFactory::factory(), SIGNAL( aboutToSend( KopeteMessage & ) ), SLOT( slotOutgoingMessage( KopeteMessage & ) ) ); m_collection=0l; m_currentMetaContact=0L; m_cachedPass_timer = new QTimer(this, "m_cachedPass_timer" ); QObject::connect(m_cachedPass_timer, SIGNAL(timeout()), this, SLOT(slotForgetCachedPass() )); } CryptographyPlugin::~CryptographyPlugin() { pluginStatic_ = 0L; delete m_collection; } CryptographyPlugin* CryptographyPlugin::plugin() { return pluginStatic_ ; } CryptographyPlugin* CryptographyPlugin::pluginStatic_ = 0L; QCString CryptographyPlugin::cachedPass() { return pluginStatic_->m_cachedPass; } void CryptographyPlugin::setCachedPass(const QCString& p) { if(pluginStatic_->m_prefs->cacheMode()==CryptographyPreferences::Never) return; if(pluginStatic_->m_prefs->cacheMode()==CryptographyPreferences::Time) pluginStatic_->m_cachedPass_timer->start(pluginStatic_->m_prefs->cacheTime() * 60000, false); pluginStatic_->m_cachedPass=p; } KActionCollection *CryptographyPlugin::customContextMenuActions(KopeteMetaContact *m) { delete m_collection; m_collection = new KActionCollection(this); KAction *action=new KAction( i18n("&Select Cryptography Public Key"), "kgpg", 0, this, SLOT (slotSelectContactKey()), m_collection); m_collection->insert(action); m_currentMetaContact=m; return m_collection; } /*KActionCollection *CryptographyPlugin::customChatActions(KopeteMessageManager *KMM) { delete m_actionCollection; m_actionCollection = new KActionCollection(this); KAction *actionTranslate = new KAction( i18n ("Translate"), 0, this, SLOT( slotTranslateChat() ), m_actionCollection, "actionTranslate" ); m_actionCollection->insert( actionTranslate ); m_currentMessageManager=KMM; return m_actionCollection; }*/ void CryptographyPlugin::slotIncomingMessage( KopeteMessage& msg ) { QString body=msg.plainBody(); if(!body.startsWith("-----BEGIN PGP MESSAGE----")) return; if(msg.direction() != KopeteMessage::Inbound) { QString plainBody; if ( m_cachedMessages.contains( body ) ) { plainBody = m_cachedMessages[ body ]; m_cachedMessages.remove( body ); } else { plainBody = KgpgInterface::KgpgDecryptText( body, m_prefs->privateKey() ); } if(!plainBody.isEmpty()) { msg.setBody("<table width=\"100%\" border=0 cellspacing=0 cellpadding=0><tr bgcolor=\"#41FFFF\"><td><font size=\"-1\"><b>"+i18n("Outgoing Encrypted Message")+"</b></font></td></tr><tr bgcolor=\"#DDFFFF\"><td>"+QStyleSheet::escape(plainBody).replace("\n", "<br/>")+"</td></tr></table>" ,KopeteMessage::RichText); } //if there are too messages in cache, clear the cache if(m_cachedMessages.count()>5) m_cachedMessages.clear(); return; } body=KgpgInterface::KgpgDecryptText(body, m_prefs->privateKey()); if(!body.isEmpty()) { body="<table width=\"100%\" border=0 cellspacing=0 cellpadding=0><tr bgcolor=\"#41FF41\"><td><font size=\"-1\"><b>"+i18n("Incoming Encrypted Message")+"</b></font></td></tr><tr bgcolor=\"#DDFFDD\"><td>"+QStyleSheet::escape(body).replace("\n", "<br/>") +"</td></tr></table>"; msg.setBody(body,KopeteMessage::RichText); } } void CryptographyPlugin::slotOutgoingMessage( KopeteMessage& msg ) { if(msg.direction() != KopeteMessage::Outbound) return; QStringList keys; QPtrList<KopeteContact> contactlist = msg.to(); for( KopeteContact *c = contactlist.first(); c; c = contactlist.next() ) { QString tmpKey; if( c->metaContact() ) tmpKey = c->metaContact()->pluginData( this, "gpgKey" ); if( tmpKey.isEmpty() ) { kdDebug( 14303 ) << "CryptographyPlugin::slotOutgoingMessage: no key selected for one contact" <<endl; return; } keys.append( tmpKey ); } // always encrypt to self, too if(m_prefs->alsoMyKey()) keys.append( m_prefs->privateKey() ); QString key = keys.join( " " ); if(key.isEmpty()) { kdDebug(14303) << "CryptographyPlugin::slotOutgoingMessage: empty key" <<endl; return; } QString original=msg.plainBody(); /* Code From KGPG */ ////////////////// encode from editor QString encryptOptions=""; //if (utrust==true) encryptOptions+=" --always-trust "; //if (arm==true) encryptOptions+=" --armor "; /* if (pubcryptography==true) { if (gpgversion<120) encryptOptions+=" --compress-algo 1 --cipher-algo cast5 "; else encryptOptions+=" --cryptography6 "; }*/ // if (selec==NULL) {KMessageBox::sorry(0,i18n("You have not choosen an encryption key..."));return;} QString resultat=KgpgInterface::KgpgEncryptText(original,key,encryptOptions); if (!resultat.isEmpty()) { msg.setBody(resultat,KopeteMessage::PlainText); m_cachedMessages.insert(resultat,original); } else kdDebug(14303) << "CryptographyPlugin::slotOutgoingMessage: empty result" <<endl; } void CryptographyPlugin::slotSelectContactKey() { QString key = m_currentMetaContact->pluginData( this, "gpgKey" ); CryptographySelectUserKey *opts = new CryptographySelectUserKey( key, m_currentMetaContact ); opts->exec(); if( opts->result() ) { key = opts->publicKey(); m_currentMetaContact->setPluginData( this, "gpgKey", key ); } delete opts; } void CryptographyPlugin::slotForgetCachedPass() { m_cachedPass=QCString(); m_cachedPass_timer->stop(); } #include "cryptographyplugin.moc" // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>/* * WinFtpClient.cpp * */ #include "WinFtpClient.h" #include <iostream> #include <fstream> #include <sstream> #include <cstdio> #include <vector> using namespace std; /** * Default constructor: replaces WinFtpClient + subsequent call to SetParameters */ WinFtpClient::WinFtpClient(const string& strServerIpAddress, const string& strLogin, const string& strPassword) : m_strIpAddress(strServerIpAddress) , m_strLogin (strLogin) , m_strPassword (strPassword) , m_bIsConnected(false) , m_ulOffset (0 ) { m_csCommand = INVALID_SOCKET; m_csData = INVALID_SOCKET; } /** * Default destructor. Closes all open connections, if possible. */ WinFtpClient::~WinFtpClient() { Disconnect(); } /* * Public functions */ bool WinFtpClient::Connect() { printf("%s() ftp://%s@%s\n", __FUNCTION__, m_strLogin.c_str(), m_strIpAddress.c_str()); /* Test configuration */ if( m_bIsConnected ) { printf("%s() : Already connected\n", __FUNCTION__); return m_bIsConnected; } if( m_strIpAddress.empty() ) { printf("%s() : ERROR - Bad configuration or not ready\n", __FUNCTION__); return false; } m_bIsConnected = true; // Startup WinSock WORD wVersionRequested; WSADATA wsaData; wVersionRequested = MAKEWORD(2, 2); if(WSAStartup(wVersionRequested, &wsaData) != 0) { printf("WSAStartup error\n"); return false; } // Create the commnad socket m_csCommand = GetSocket(m_strIpAddress, FTP_COMMAND_PORT); if (m_csCommand == INVALID_SOCKET) { printf("%s() Socket error: %ld\n", __FUNCTION__, WSAGetLastError()); if (m_csCommand == WSAEISCONN) { printf("Already connected\n"); } m_bIsConnected = false; } else { // Read response char strConn[256] = {0}; ReceiveAnswer(strConn, 256); strConn[255] = 0; if(!CheckExpectedResponse(strConn, "220")) { closesocket(m_csCommand); printf("%s() Closing command socket. Unexpected server response: %s\n", __FUNCTION__, strConn); m_bIsConnected = false; } else { // Force login if user and password are not empty if(!m_strLogin.empty() && !m_strPassword.empty() && !Login()) { m_bIsConnected = false; closesocket(m_csCommand); printf("%s() Closing command socket. Login failed: %ld\n", __FUNCTION__, WSAGetLastError()); } } } return m_bIsConnected; } void WinFtpClient::Disconnect() { printf("%s()\n", __FUNCTION__); if( shutdown(m_csCommand, SD_BOTH) == SOCKET_ERROR ) { printf("m_csCommand shutdown failed: %d\n", WSAGetLastError()); } if ( shutdown(m_csData, SD_BOTH) == SOCKET_ERROR ) { printf("m_csData shutdown failed: %d\n", WSAGetLastError()); } WSACleanup(); // Set flag to false m_bIsConnected = false; } bool WinFtpClient::Login() { printf("Login\n"); SendCommand("USER " + m_strLogin + "\r\n"); Sleep(250); char strUser[256] = {0}; ReceiveAnswer(strUser, 256); strUser[255] = 0; // TODO poner reintentos if (!CheckExpectedResponse(strUser, "331")) { printf("USER failed! -- \"%s\"\n", strUser); return false; } SendCommand("PASS " + m_strPassword + "\r\n"); Sleep(250); char strPass[256] = {0}; ReceiveAnswer(strPass, 256); strPass[255] = 0; int retry = 0; if (!CheckExpectedResponse(strPass, "230")) { printf("PASS failed! -- \"%s\"\n", strPass); return false; } printf("\"%s\"\n", strPass); return true; } bool WinFtpClient::IsConnected() const { return m_bIsConnected; } void WinFtpClient::SetParameters (const std::string& strIpAddress, const std::string& strLogin, const std::string& strPassword) { m_strIpAddress = strIpAddress; m_strLogin = strLogin; m_strPassword = strPassword; } bool WinFtpClient::FileExists (const std::string&) { return true; } bool WinFtpClient::GetFile (const std::string& strSourcePath, const std::string& strTargetPath, bool ) { return true; } list<std::string> WinFtpClient::GetFileList (const std::string& strSourcePath) { std::list<std::string> l; return l; } bool WinFtpClient::SetDirectory(string const & destination) { const string& cwd = BuildCommand<string>("CWD", destination); if(! SendCommand(cwd)) { printf("Error while sending command sequence: %d\n", WSAGetLastError()); return false; } char strBuffer[256]; ReceiveAnswer(strBuffer, 256); return (CheckExpectedResponse(strBuffer, "250")); } bool WinFtpClient::SendFile(const string& strSourceFile, const string& strTargetPath, unsigned long ulOffset) { printf("%s() --> Begin\n", __FUNCTION__); string strDir = strTargetPath.substr(0, strTargetPath.find_last_of('/')); string strTargetFilename = strTargetPath.substr(strTargetPath.find_last_of('/') + 1, strTargetPath.size() - 1); /* * Get text from strSourceFile starting at ulOffset. */ string buffer = ""; ifstream myfile (strSourceFile.c_str(), std::ifstream::in); if (myfile && myfile.is_open()) { myfile.seekg (0, ios::end); // Move position to ulOffset int fsize = myfile.tellg(); if(ulOffset < fsize) { myfile.seekg (ulOffset, ios::beg); // Move position to offset buffer.resize(fsize - ulOffset); // Allocate memory myfile.read(&buffer[0], buffer.size()); // Read the contents from offset to end myfile.close(); } else { printf("%s() Offset value is greater than the file size itself (%lu > %lu)\n", __FUNCTION__, ulOffset, fsize); return false; } } else { printf("%s(): Error opening source file = %\n", __FUNCTION__, strSourceFile.c_str()); return false; } /* Set destination directory */ if(!SetDirectory(strDir)) { printf("%s(): Destination directory not found = %\n", __FUNCTION__, strSourceFile.c_str()); return false; } /* Start passive mode */ char strBuffer[256]; int port = PassiveMode(); if(port == 0) { printf("%s() Couldn't determine connection port number for data interchange\n", __FUNCTION__); printf("%s\n", strBuffer); return false; } printf("%s() Using port %d\n", __FUNCTION__, port); /* Resume upload if proceed */ if(!ResumeUpload(strTargetFilename, ulOffset)) { printf("Error while sending REST + STOR sequence: %d\n", WSAGetLastError()); } printf("%s() Resuming uploading at %d\n", __FUNCTION__, ulOffset); m_csData = GetSocket(m_strIpAddress, port); if (m_csData == INVALID_SOCKET) { printf("%s() Error connecting: %d\n", __FUNCTION__, WSAGetLastError()); return false; } printf("\nSending...\n"); // int result = send(m_csData, buffer.c_str(), buffer.size(), 0) != SOCKET_ERROR ; bool bResult = SendBuffer(m_csData, buffer, buffer.size()) == 0; closesocket(m_csData); printf("%s() closed socket: %d\n", __FUNCTION__, WSAGetLastError()); // Check that the server updated correctly the target file ReceiveAnswer(strBuffer, 256); if(! (bResult &= CheckExpectedResponse(strBuffer, "226")) ) { printf("Unexpected server response: %s\n", strBuffer); } return bResult; } /* * Protected functions */ bool WinFtpClient::ResumeUpload(const string& targetFile, int offset) { // Build rest command const string& rest = BuildCommand<int>("REST", offset); if(!SendCommand(rest)) { printf("REST command failed!\n"); return false; } char strBuffer[256]; ReceiveAnswer(strBuffer, 256); if(!CheckExpectedResponse(strBuffer, "350")) { printf("Unexpected server response: %s\n", strBuffer); return false; } // Stor command const string& stor = BuildCommand<string>("STOR", targetFile); if(!SendCommand(stor)) { printf("STOR command failed!\n"); return false; } ReceiveAnswer(strBuffer, 256); return (CheckExpectedResponse(strBuffer, "150")); } int WinFtpClient::PassiveMode() { // Set type as binary/image if(!SendCommand("TYPE I\r\n")) { printf("TYPE command failed!\n"); return 0; } char strBuffer[256]; ReceiveAnswer(strBuffer, 256); if(!CheckExpectedResponse(strBuffer, "200")) { printf("Unexpected server response: %s\n", strBuffer); return 0; } // Proceed with passive mode if(!SendCommand("PASV\r\n")) { printf("PASV command failed!\n"); return 0; } // Get port for passive mode ReceiveAnswer(strBuffer, 256); if(!CheckExpectedResponse(strBuffer, "227")) { printf("Unexpected server response: %s\n", strBuffer); return 0; } printf("Passive answer: %s\n", strBuffer); return ParsePortPassive(strBuffer); } bool WinFtpClient::SendCommand(const string& strCommand) { int iResult; // Send an initial buffer iResult = send(m_csCommand, strCommand.c_str(), (int) strCommand.size(), 0); return iResult != SOCKET_ERROR; } bool WinFtpClient::ReceiveAnswer(char* const strBuffer, int iLength) { // Clean the array before use memset(&strBuffer[0], 0, iLength); int iResult = -1; // Send an initial buffer iResult = recv(m_csCommand, strBuffer, iLength, 0); if (iResult == SOCKET_ERROR) { printf("Answer failed: %d\n", WSAGetLastError()); return false; } printf("Bytes received: %d\n", iResult); return true; } bool WinFtpClient::CheckExpectedResponse(const string& response, const string& expected) { std::istringstream f(response); std::string line; std::string before; while (std::getline(f, line) && !f.eof()) { before = line; } return (before.find(expected.c_str(), 0) != std::string::npos); } int WinFtpClient::ParsePortPassive(const string& pasvAnswer) { std::istringstream f(pasvAnswer); std::string line; while (std::getline(f, line) && !(line.find("227", 0) != std::string::npos)); if(line.empty()) { return 0; } vector<std::string> elems; std::stringstream ss(line.substr(0, line.find(")"))); std::string item; int count = 0; while (std::getline(ss, item, ',')) { elems.push_back(item); } int p1, p2 = 0; p1 = atoi(elems.at(4).c_str()); p2 = atoi(elems.at(5).c_str()); int port = p1 * 256 + p2; return port; } SOCKET WinFtpClient::GetSocket(const string& strIpAddress, ushort_t usPort) { //Fill out the information needed to initialize a socket… SOCKADDR_IN target; //Socket address information target.sin_family = AF_INET; // address family Internet target.sin_port = htons (usPort); //Port to connect on target.sin_addr.s_addr = inet_addr (strIpAddress.c_str()); //Target IP SOCKET mySocket = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); //Create socket if (mySocket != INVALID_SOCKET) { //Try connecting... connect(mySocket, (SOCKADDR *)&target, sizeof(target)); } return mySocket; } /* * Private functions */ template <typename T> string WinFtpClient::BuildCommand(const string& strCommand, const T& strParams) { std::stringstream ss; ss << strCommand << " " << strParams << "\r\n"; return (ss.str()); } int WinFtpClient::SendBuffer(SOCKET socket, const string& strBuffer, int iStillToSend) { int iRC = 0; int iSendStatus = 0; timeval SendTimeout; fd_set fds; FD_ZERO(&fds); FD_SET(socket, &fds); // Set timeout SendTimeout.tv_sec = 0; SendTimeout.tv_usec = 250000; // 250 ms // As long as we need to send bytes... char *pBuffer = new char[strBuffer.size()]; memcpy(pBuffer, strBuffer.c_str(), strBuffer.size()); while(iStillToSend > 0) { iRC = select(0, NULL, &fds, NULL, &SendTimeout); // Timeout if(!iRC) return -1; // Error if(iRC < 0) return WSAGetLastError(); // Send some bytes iSendStatus = send(socket, pBuffer, iStillToSend, 0); // Error if(iSendStatus < 0) return WSAGetLastError(); else { // Update buffer and counter iStillToSend -= iSendStatus; pBuffer += iSendStatus; } } if(pBuffer) delete[] pBuffer; return 0; } <commit_msg>Update WinFtpClient.cpp<commit_after>/* * WinFtpClient.cpp * */ #include "WinFtpClient.h" #include <iostream> #include <fstream> #include <sstream> #include <cstdio> #include <vector> using namespace std; /** * Default constructor: replaces WinFtpClient + subsequent call to SetParameters */ WinFtpClient::WinFtpClient(const string& strServerIpAddress, const string& strLogin, const string& strPassword) : m_strIpAddress(strServerIpAddress) , m_strLogin (strLogin) , m_strPassword (strPassword) , m_bIsConnected(false) , m_ulOffset (0 ) { m_csCommand = INVALID_SOCKET; m_csData = INVALID_SOCKET; } /** * Default destructor. Closes all open connections, if possible. */ WinFtpClient::~WinFtpClient() { Disconnect(); } /* * Public functions */ bool WinFtpClient::Connect() { printf("%s() ftp://%s@%s\n", __FUNCTION__, m_strLogin.c_str(), m_strIpAddress.c_str()); /* Test configuration */ if( m_bIsConnected ) { printf("%s() : Already connected\n", __FUNCTION__); return m_bIsConnected; } if( m_strIpAddress.empty() ) { printf("%s() : ERROR - Bad configuration or not ready\n", __FUNCTION__); return false; } m_bIsConnected = true; // Startup WinSock WORD wVersionRequested; WSADATA wsaData; wVersionRequested = MAKEWORD(2, 2); if(WSAStartup(wVersionRequested, &wsaData) != 0) { printf("WSAStartup error\n"); return false; } // Create the commnad socket m_csCommand = GetSocket(m_strIpAddress, FTP_COMMAND_PORT); if (m_csCommand == INVALID_SOCKET) { printf("%s() Socket error: %ld\n", __FUNCTION__, WSAGetLastError()); if (m_csCommand == WSAEISCONN) { printf("Already connected\n"); } m_bIsConnected = false; } else { // Read response char strConn[256] = {0}; ReceiveAnswer(strConn, 256); strConn[255] = 0; if(!CheckExpectedResponse(strConn, "220")) { closesocket(m_csCommand); printf("%s() Closing command socket. Unexpected server response: %s\n", __FUNCTION__, strConn); m_bIsConnected = false; } else { // Force login if user and password are not empty if(!m_strLogin.empty() && !m_strPassword.empty() && !Login()) { m_bIsConnected = false; closesocket(m_csCommand); printf("%s() Closing command socket. Login failed: %ld\n", __FUNCTION__, WSAGetLastError()); } } } return m_bIsConnected; } void WinFtpClient::Disconnect() { printf("%s()\n", __FUNCTION__); if( shutdown(m_csCommand, SD_BOTH) == SOCKET_ERROR ) { printf("m_csCommand shutdown failed: %d\n", WSAGetLastError()); } if ( shutdown(m_csData, SD_BOTH) == SOCKET_ERROR ) { printf("m_csData shutdown failed: %d\n", WSAGetLastError()); } WSACleanup(); // Set flag to false m_bIsConnected = false; } bool WinFtpClient::Login() { printf("Login\n"); SendCommand("USER " + m_strLogin + "\r\n"); Sleep(250); char strUser[256] = {0}; ReceiveAnswer(strUser, 256); strUser[255] = 0; // TODO poner reintentos if (!CheckExpectedResponse(strUser, "331")) { printf("USER failed! -- \"%s\"\n", strUser); return false; } SendCommand("PASS " + m_strPassword + "\r\n"); Sleep(250); char strPass[256] = {0}; ReceiveAnswer(strPass, 256); strPass[255] = 0; int retry = 0; if (!CheckExpectedResponse(strPass, "230")) { printf("PASS failed! -- \"%s\"\n", strPass); return false; } printf("\"%s\"\n", strPass); return true; } bool WinFtpClient::IsConnected() const { return m_bIsConnected; } void WinFtpClient::SetParameters (const std::string& strIpAddress, const std::string& strLogin, const std::string& strPassword) { m_strIpAddress = strIpAddress; m_strLogin = strLogin; m_strPassword = strPassword; } bool WinFtpClient::FileExists (const std::string&) { return true; } bool WinFtpClient::GetFile (const std::string& strSourcePath, const std::string& strTargetPath, bool ) { return true; } list<std::string> WinFtpClient::GetFileList (const std::string& strSourcePath) { std::list<std::string> l; return l; } bool WinFtpClient::SetDirectory(string const & destination) { const string& cwd = BuildCommand<string>("CWD", destination); if(! SendCommand(cwd)) { printf("Error while sending command sequence: %d\n", WSAGetLastError()); return false; } char strBuffer[256]; ReceiveAnswer(strBuffer, 256); return (CheckExpectedResponse(strBuffer, "250")); } bool WinFtpClient::SendFile(const string& strSourceFile, const string& strTargetPath, unsigned long ulOffset) { printf("%s() --> Begin\n", __FUNCTION__); string strDir = strTargetPath.substr(0, strTargetPath.find_last_of('/')); string strTargetFilename = strTargetPath.substr(strTargetPath.find_last_of('/') + 1, strTargetPath.size() - 1); /* * Get text from strSourceFile starting at ulOffset. */ string buffer = ""; ifstream myfile (strSourceFile.c_str(), std::ifstream::in); if (myfile && myfile.is_open()) { myfile.seekg (0, ios::end); // Move position to ulOffset int fsize = myfile.tellg(); if(ulOffset < fsize) { myfile.seekg (ulOffset, ios::beg); // Move position to offset buffer.resize(fsize - ulOffset); // Allocate memory myfile.read(&buffer[0], buffer.size()); // Read the contents from offset to end myfile.close(); } else { printf("%s() Offset value is greater than the file size itself (%lu > %lu)\n", __FUNCTION__, ulOffset, fsize); return false; } } else { printf("%s(): Error opening source file = %\n", __FUNCTION__, strSourceFile.c_str()); return false; } /* Set destination directory */ if(!SetDirectory(strDir)) { printf("%s(): Destination directory not found = %\n", __FUNCTION__, strSourceFile.c_str()); return false; } /* Start passive mode */ char strBuffer[256]; int port = PassiveMode(); if(port == 0) { printf("%s() Couldn't determine connection port number for data interchange\n", __FUNCTION__); printf("%s\n", strBuffer); return false; } printf("%s() Using port %d\n", __FUNCTION__, port); /* Resume upload if proceed */ if(!ResumeUpload(strTargetFilename, ulOffset)) { printf("Error while sending REST + STOR sequence: %d\n", WSAGetLastError()); } printf("%s() Resuming uploading at %d\n", __FUNCTION__, ulOffset); m_csData = GetSocket(m_strIpAddress, port); if (m_csData == INVALID_SOCKET) { printf("%s() Error connecting: %d\n", __FUNCTION__, WSAGetLastError()); return false; } printf("\nSending...\n"); // int result = send(m_csData, buffer.c_str(), buffer.size(), 0) != SOCKET_ERROR ; bool bResult = SendBuffer(m_csData, buffer, buffer.size()) == 0; closesocket(m_csData); printf("%s() closed socket: %d\n", __FUNCTION__, WSAGetLastError()); // Check that the server updated correctly the target file ReceiveAnswer(strBuffer, 256); if(! (bResult &= CheckExpectedResponse(strBuffer, "226")) ) { printf("Unexpected server response: %s\n", strBuffer); } return bResult; } /* * Protected functions */ bool WinFtpClient::ResumeUpload(const string& targetFile, int offset) { // Build rest command const string& rest = BuildCommand<int>("REST", offset); if(!SendCommand(rest)) { printf("REST command failed!\n"); return false; } char strBuffer[256]; ReceiveAnswer(strBuffer, 256); if(!CheckExpectedResponse(strBuffer, "350")) { printf("Unexpected server response: %s\n", strBuffer); return false; } // Stor command const string& stor = BuildCommand<string>("STOR", targetFile); if(!SendCommand(stor)) { printf("STOR command failed!\n"); return false; } ReceiveAnswer(strBuffer, 256); return (CheckExpectedResponse(strBuffer, "150")); } int WinFtpClient::PassiveMode() { // Set type as binary/image if(!SendCommand("TYPE I\r\n")) { printf("TYPE command failed!\n"); return 0; } char strBuffer[256]; ReceiveAnswer(strBuffer, 256); if(!CheckExpectedResponse(strBuffer, "200")) { printf("Unexpected server response: %s\n", strBuffer); return 0; } // Proceed with passive mode if(!SendCommand("PASV\r\n")) { printf("PASV command failed!\n"); return 0; } // Get port for passive mode ReceiveAnswer(strBuffer, 256); if(!CheckExpectedResponse(strBuffer, "227")) { printf("Unexpected server response: %s\n", strBuffer); return 0; } printf("Passive answer: %s\n", strBuffer); return ParsePortPassive(strBuffer); } bool WinFtpClient::SendCommand(const string& strCommand) { int iResult; // Send an initial buffer iResult = send(m_csCommand, strCommand.c_str(), (int) strCommand.size(), 0); return iResult != SOCKET_ERROR; } bool WinFtpClient::ReceiveAnswer(char* const strBuffer, int iLength) { // Clean the array before use memset(&strBuffer[0], 0, iLength); int iResult = -1; // Send an initial buffer iResult = recv(m_csCommand, strBuffer, iLength, 0); if (iResult == SOCKET_ERROR) { printf("Answer failed: %d\n", WSAGetLastError()); return false; } printf("Bytes received: %d\n", iResult); return true; } bool WinFtpClient::CheckExpectedResponse(const string& response, const string& expected) { std::istringstream f(response); std::string line; std::string before; while (std::getline(f, line) && !f.eof()) { before = line; } return (before.find(expected.c_str(), 0) != std::string::npos); } int WinFtpClient::ParsePortPassive(const string& pasvAnswer) { std::istringstream f(pasvAnswer); std::string line; while (std::getline(f, line) && !(line.find("227", 0) != std::string::npos)); if(line.empty()) { return 0; } vector<std::string> elems; std::stringstream ss(line.substr(0, line.find(")"))); std::string item; int count = 0; while (std::getline(ss, item, ',')) { elems.push_back(item); } int p1, p2 = 0; p1 = atoi(elems.at(4).c_str()); p2 = atoi(elems.at(5).c_str()); int port = p1 * 256 + p2; return port; } SOCKET WinFtpClient::GetSocket(const string& strIpAddress, ushort_t usPort) { //Fill out the information needed to initialize a socket… SOCKADDR_IN target; //Socket address information target.sin_family = AF_INET; // address family Internet target.sin_port = htons (usPort); //Port to connect on target.sin_addr.s_addr = inet_addr (strIpAddress.c_str()); //Target IP SOCKET mySocket = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); //Create socket if (mySocket != INVALID_SOCKET) { //Try connecting... connect(mySocket, (SOCKADDR *)&target, sizeof(target)); } return mySocket; } /* * Private functions */ template <typename T> string WinFtpClient::BuildCommand(const string& strCommand, const T& strParams) { std::stringstream ss; ss << strCommand << " " << strParams << "\r\n"; return (ss.str()); } int WinFtpClient::SendBuffer(SOCKET socket, const string& strBuffer, int iStillToSend) { int iRC = 0; int iSendStatus = 0; timeval SendTimeout; fd_set fds; FD_ZERO(&fds); FD_SET(socket, &fds); // Set timeout SendTimeout.tv_sec = 0; SendTimeout.tv_usec = 250000; // 250 ms // As long as we need to send bytes... char *pBuffer = new char[strBuffer.size()]; char *pCopyPointer = pBuffer; memcpy(pBuffer, strBuffer.c_str(), strBuffer.size()); while(iStillToSend > 0) { iRC = select(0, NULL, &fds, NULL, &SendTimeout); // Timeout if(!iRC) return -1; // Error if(iRC < 0) return WSAGetLastError(); // Send some bytes iSendStatus = send(socket, pBuffer, iStillToSend, 0); // Error if(iSendStatus < 0) return WSAGetLastError(); else { // Update buffer and counter iStillToSend -= iSendStatus; pBuffer += iSendStatus; } } if(pCopyPointer) delete[] pCopyPointer; return 0; } <|endoftext|>
<commit_before>#include "building_configure.hpp" #include <silicium/file_operations.hpp> #include <silicium/cmake.hpp> #include <fstream> namespace cdm { void build_configure_command_line( Si::absolute_path const &application_source, Si::absolute_path const &temporary, Si::absolute_path const &resulting_executable, Si::Sink<char, Si::success>::interface &output) { Si::absolute_path const cdm = Si::parent( Si::parent(*Si::absolute_path::create(__FILE__)).or_throw( []{ throw std::runtime_error("Could not find parent directory of this file: " __FILE__); } ) ).or_throw( []{ throw std::runtime_error("Could not find the cdm directory"); } ); Si::absolute_path const original_main_cpp = cdm / Si::relative_path("configure_cmdline/main.cpp"); Si::absolute_path const source = temporary / Si::relative_path("source"); Si::recreate_directories(source, Si::throw_); Si::absolute_path const copied_main_cpp = source / Si::relative_path("main.cpp"); Si::copy(original_main_cpp, copied_main_cpp, boost::filesystem::copy_option::fail_if_exists, Si::throw_); { Si::absolute_path const cmakeLists = source / Si::relative_path("CMakeLists.txt"); std::ofstream cmakeListsFile(cmakeLists.c_str()); cmakeListsFile << "cmake_minimum_required(VERSION 2.8)\n"; cmakeListsFile << "project(configure_cmdline_generated)\n"; cmakeListsFile << "if(UNIX)\n"; cmakeListsFile << " add_definitions(-std=c++1y)\n"; cmakeListsFile << "endif()\n"; cmakeListsFile << "find_package(Boost REQUIRED filesystem coroutine program_options system)\n"; cmakeListsFile << "include_directories(${SILICIUM_INCLUDE_DIR} ${BOOST_INCLUDE_DIR} ${CDM_CONFIGURE_INCLUDE_DIRS})\n"; cmakeListsFile << "add_executable(configure main.cpp)\n"; cmakeListsFile << "target_link_libraries(configure ${Boost_LIBRARIES})\n"; if (!cmakeListsFile) { throw std::runtime_error(("Could not generate " + Si::to_utf8_string(cmakeLists)).c_str()); } } Si::absolute_path const build = temporary / Si::relative_path("build"); Si::recreate_directories(build, Si::throw_); { std::vector<Si::os_string> arguments; { Si::absolute_path const silicium = Si::parent(cdm).or_throw([] { throw std::runtime_error("Could not find the silicium directory"); }); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-DSILICIUM_INCLUDE_DIR=") + Si::to_os_string(silicium)); } Si::absolute_path const modules = cdm / Si::relative_path("modules"); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-DCDM_CONFIGURE_INCLUDE_DIRS=") + Si::to_os_string(application_source) + ";" + Si::to_os_string(modules)); arguments.emplace_back(Si::to_os_string(source)); if (Si::run_process(Si::cmake_exe, arguments, build, output).get() != 0) { throw std::runtime_error("Could not CMake-configure the cdm configure executable"); } } { std::vector<Si::os_string> arguments; arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("--build")); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL(".")); if (Si::run_process(Si::cmake_exe, arguments, build, output).get() != 0) { throw std::runtime_error("Could not CMake --build the cdm configure executable"); } } Si::absolute_path const built_executable = build / Si::relative_path("configure"); Si::copy(built_executable, resulting_executable, boost::filesystem::copy_option::fail_if_exists, Si::throw_); } void run_configure_command_line( Si::absolute_path const &configure_executable, Si::absolute_path const &module_permanent, Si::absolute_path const &application_source, Si::absolute_path const &application_build_dir, Si::Sink<char, Si::success>::interface &output) { std::vector<Si::os_string> arguments; arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-m")); arguments.emplace_back(Si::to_os_string(module_permanent)); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-a")); arguments.emplace_back(Si::to_os_string(application_source)); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-b")); arguments.emplace_back(Si::to_os_string(application_build_dir)); int const rc = Si::run_process(configure_executable, arguments, application_build_dir, output).get(); if (rc != 0) { throw std::runtime_error("Could not configure the application: " + boost::lexical_cast<std::string>(rc)); } } } <commit_msg>fix for VC++ 2013<commit_after>#include "building_configure.hpp" #include <silicium/file_operations.hpp> #include <silicium/cmake.hpp> #include <fstream> namespace cdm { void build_configure_command_line( Si::absolute_path const &application_source, Si::absolute_path const &temporary, Si::absolute_path const &resulting_executable, Si::Sink<char, Si::success>::interface &output) { Si::absolute_path const cdm = Si::parent( Si::parent(*Si::absolute_path::create(__FILE__)).or_throw( []{ throw std::runtime_error("Could not find parent directory of this file: " __FILE__); } ) ).or_throw( []{ throw std::runtime_error("Could not find the cdm directory"); } ); Si::absolute_path const original_main_cpp = cdm / Si::relative_path("configure_cmdline/main.cpp"); Si::absolute_path const source = temporary / Si::relative_path("source"); Si::recreate_directories(source, Si::throw_); Si::absolute_path const copied_main_cpp = source / Si::relative_path("main.cpp"); Si::copy(original_main_cpp, copied_main_cpp, boost::filesystem::copy_option::fail_if_exists, Si::throw_); { Si::absolute_path const cmakeLists = source / Si::relative_path("CMakeLists.txt"); std::ofstream cmakeListsFile(cmakeLists.c_str()); cmakeListsFile << "cmake_minimum_required(VERSION 2.8)\n"; cmakeListsFile << "project(configure_cmdline_generated)\n"; cmakeListsFile << "if(UNIX)\n"; cmakeListsFile << " add_definitions(-std=c++1y)\n"; cmakeListsFile << "endif()\n"; cmakeListsFile << "find_package(Boost REQUIRED filesystem coroutine program_options system)\n"; cmakeListsFile << "include_directories(${SILICIUM_INCLUDE_DIR} ${BOOST_INCLUDE_DIR} ${CDM_CONFIGURE_INCLUDE_DIRS})\n"; cmakeListsFile << "add_executable(configure main.cpp)\n"; cmakeListsFile << "target_link_libraries(configure ${Boost_LIBRARIES})\n"; if (!cmakeListsFile) { throw std::runtime_error(("Could not generate " + Si::to_utf8_string(cmakeLists)).c_str()); } } Si::absolute_path const build = temporary / Si::relative_path("build"); Si::recreate_directories(build, Si::throw_); { std::vector<Si::os_string> arguments; { Si::absolute_path const silicium = Si::parent(cdm).or_throw([] { throw std::runtime_error("Could not find the silicium directory"); }); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-DSILICIUM_INCLUDE_DIR=") + Si::to_os_string(silicium)); } Si::absolute_path const modules = cdm / Si::relative_path("modules"); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-DCDM_CONFIGURE_INCLUDE_DIRS=") + Si::to_os_string(application_source) + SILICIUM_SYSTEM_LITERAL(";") + Si::to_os_string(modules)); arguments.emplace_back(Si::to_os_string(source)); if (Si::run_process(Si::cmake_exe, arguments, build, output).get() != 0) { throw std::runtime_error("Could not CMake-configure the cdm configure executable"); } } { std::vector<Si::os_string> arguments; arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("--build")); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL(".")); if (Si::run_process(Si::cmake_exe, arguments, build, output).get() != 0) { throw std::runtime_error("Could not CMake --build the cdm configure executable"); } } Si::absolute_path const built_executable = build / Si::relative_path("configure"); Si::copy(built_executable, resulting_executable, boost::filesystem::copy_option::fail_if_exists, Si::throw_); } void run_configure_command_line( Si::absolute_path const &configure_executable, Si::absolute_path const &module_permanent, Si::absolute_path const &application_source, Si::absolute_path const &application_build_dir, Si::Sink<char, Si::success>::interface &output) { std::vector<Si::os_string> arguments; arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-m")); arguments.emplace_back(Si::to_os_string(module_permanent)); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-a")); arguments.emplace_back(Si::to_os_string(application_source)); arguments.emplace_back(SILICIUM_SYSTEM_LITERAL("-b")); arguments.emplace_back(Si::to_os_string(application_build_dir)); int const rc = Si::run_process(configure_executable, arguments, application_build_dir, output).get(); if (rc != 0) { throw std::runtime_error("Could not configure the application: " + boost::lexical_cast<std::string>(rc)); } } } <|endoftext|>
<commit_before>/* Copyright (c) 2015-present Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <hip/hip_runtime.h> #include "hip_event.hpp" namespace hip { bool Event::ready() { if (event_->status() != CL_COMPLETE) { event_->notifyCmdQueue(); } return (event_->status() == CL_COMPLETE); } hipError_t Event::query() { amd::ScopedLock lock(lock_); // If event is not recorded, event_ is null, hence return hipSuccess if (event_ == nullptr) { return hipSuccess; } return ready() ? hipSuccess : hipErrorNotReady; } hipError_t Event::synchronize() { amd::ScopedLock lock(lock_); // If event is not recorded, event_ is null, hence return hipSuccess if (event_ == nullptr) { return hipSuccess; } event_->awaitCompletion(); return hipSuccess; } hipError_t Event::elapsedTime(Event& eStop, float& ms) { amd::ScopedLock startLock(lock_); if (this == &eStop) { if (event_ == nullptr) { return hipErrorInvalidHandle; } if (flags & hipEventDisableTiming) { return hipErrorInvalidHandle; } if (!ready()) { return hipErrorNotReady; } ms = 0.f; return hipSuccess; } amd::ScopedLock stopLock(eStop.lock_); if (event_ == nullptr || eStop.event_ == nullptr) { return hipErrorInvalidHandle; } if ((flags | eStop.flags) & hipEventDisableTiming) { return hipErrorInvalidHandle; } if (!ready() || !eStop.ready()) { return hipErrorNotReady; } ms = static_cast<float>(static_cast<int64_t>(eStop.event_->profilingInfo().end_ - event_->profilingInfo().end_))/1000000.f; return hipSuccess; } hipError_t Event::streamWait(amd::HostQueue* hostQueue, uint flags) { if ((event_ == nullptr) || (event_->command().queue() == hostQueue)) { return hipSuccess; } amd::ScopedLock lock(lock_); bool retain = false; if (!event_->notifyCmdQueue()) { return hipErrorLaunchOutOfResources; } amd::Command::EventWaitList eventWaitList; eventWaitList.push_back(event_); amd::Command* command = new amd::Marker(*hostQueue, false, eventWaitList); if (command == NULL) { return hipErrorOutOfMemory; } command->enqueue(); command->release(); return hipSuccess; } void Event::addMarker(amd::HostQueue* queue, amd::Command* command) { amd::ScopedLock lock(lock_); if (event_ == &command->event()) return; if (event_ != nullptr) { event_->release(); } event_ = &command->event(); } } hipError_t ihipEventCreateWithFlags(hipEvent_t* event, unsigned flags) { if (event == nullptr) { return hipErrorInvalidValue; } unsigned supportedFlags = hipEventDefault | hipEventBlockingSync | hipEventDisableTiming | hipEventReleaseToDevice | hipEventReleaseToSystem; const unsigned releaseFlags = (hipEventReleaseToDevice | hipEventReleaseToSystem); const bool illegalFlags = (flags & ~supportedFlags) || // can't set any unsupported flags. (flags & releaseFlags) == releaseFlags; // can't set both release flags if (!illegalFlags) { hip::Event* e = new hip::Event(flags); if (e == nullptr) { return hipErrorOutOfMemory; } *event = reinterpret_cast<hipEvent_t>(e); } else { return hipErrorInvalidValue; } return hipSuccess; } hipError_t ihipEventQuery(hipEvent_t event) { if (event == nullptr) { return hipErrorInvalidHandle; } hip::Event* e = reinterpret_cast<hip::Event*>(event); return e->query(); } hipError_t hipEventCreateWithFlags(hipEvent_t* event, unsigned flags) { HIP_INIT_API(hipEventCreateWithFlags, event, flags); HIP_RETURN(ihipEventCreateWithFlags(event, flags)); } hipError_t hipEventCreate(hipEvent_t* event) { HIP_INIT_API(hipEventCreate, event); HIP_RETURN(ihipEventCreateWithFlags(event, 0)); } hipError_t hipEventDestroy(hipEvent_t event) { HIP_INIT_API(hipEventDestroy, event); if (event == nullptr) { HIP_RETURN(hipErrorInvalidHandle); } delete reinterpret_cast<hip::Event*>(event); HIP_RETURN(hipSuccess); } hipError_t hipEventElapsedTime(float *ms, hipEvent_t start, hipEvent_t stop) { HIP_INIT_API(hipEventElapsedTime, ms, start, stop); if (start == nullptr || stop == nullptr) { HIP_RETURN(hipErrorInvalidHandle); } if (ms == nullptr) { HIP_RETURN(hipErrorInvalidValue); } hip::Event* eStart = reinterpret_cast<hip::Event*>(start); hip::Event* eStop = reinterpret_cast<hip::Event*>(stop); HIP_RETURN(eStart->elapsedTime(*eStop, *ms)); } hipError_t hipEventRecord(hipEvent_t event, hipStream_t stream) { HIP_INIT_API(hipEventRecord, event, stream); if (event == nullptr) { HIP_RETURN(hipErrorInvalidHandle); } amd::HostQueue* queue = hip::getQueue(stream); amd::Command* command = queue->getLastQueuedCommand(true); if (command == nullptr) { command = new amd::Marker(*queue, false); command->enqueue(); } hip::Event* e = reinterpret_cast<hip::Event*>(event); e->addMarker(queue, command); HIP_RETURN(hipSuccess); } hipError_t hipEventSynchronize(hipEvent_t event) { HIP_INIT_API(hipEventSynchronize, event); if (event == nullptr) { HIP_RETURN(hipErrorInvalidHandle); } hip::Event* e = reinterpret_cast<hip::Event*>(event); HIP_RETURN(e->synchronize()); } hipError_t hipEventQuery(hipEvent_t event) { HIP_INIT_API(hipEventQuery, event); HIP_RETURN(ihipEventQuery(event)); } <commit_msg>Fix elapsed time calc for hipEventElapsedTime<commit_after>/* Copyright (c) 2015-present Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <hip/hip_runtime.h> #include "hip_event.hpp" namespace hip { bool Event::ready() { if (event_->status() != CL_COMPLETE) { event_->notifyCmdQueue(); } return (event_->status() == CL_COMPLETE); } hipError_t Event::query() { amd::ScopedLock lock(lock_); // If event is not recorded, event_ is null, hence return hipSuccess if (event_ == nullptr) { return hipSuccess; } return ready() ? hipSuccess : hipErrorNotReady; } hipError_t Event::synchronize() { amd::ScopedLock lock(lock_); // If event is not recorded, event_ is null, hence return hipSuccess if (event_ == nullptr) { return hipSuccess; } event_->awaitCompletion(); return hipSuccess; } hipError_t Event::elapsedTime(Event& eStop, float& ms) { amd::ScopedLock startLock(lock_); if (this == &eStop) { if (event_ == nullptr) { return hipErrorInvalidHandle; } if (flags & hipEventDisableTiming) { return hipErrorInvalidHandle; } if (!ready()) { return hipErrorNotReady; } ms = 0.f; return hipSuccess; } amd::ScopedLock stopLock(eStop.lock_); if (event_ == nullptr || eStop.event_ == nullptr) { return hipErrorInvalidHandle; } if ((flags | eStop.flags) & hipEventDisableTiming) { return hipErrorInvalidHandle; } if (!ready() || !eStop.ready()) { return hipErrorNotReady; } // For certain HIP Api's that take start and stop event // the command is the same if (event_ == eStop.event_) { ms = static_cast<float>(static_cast<int64_t>(eStop.event_->profilingInfo().end_ - event_->profilingInfo().start_))/1000000.f; } else { ms = static_cast<float>(static_cast<int64_t>(eStop.event_->profilingInfo().end_ - event_->profilingInfo().end_))/1000000.f; } return hipSuccess; } hipError_t Event::streamWait(amd::HostQueue* hostQueue, uint flags) { if ((event_ == nullptr) || (event_->command().queue() == hostQueue)) { return hipSuccess; } amd::ScopedLock lock(lock_); bool retain = false; if (!event_->notifyCmdQueue()) { return hipErrorLaunchOutOfResources; } amd::Command::EventWaitList eventWaitList; eventWaitList.push_back(event_); amd::Command* command = new amd::Marker(*hostQueue, false, eventWaitList); if (command == NULL) { return hipErrorOutOfMemory; } command->enqueue(); command->release(); return hipSuccess; } void Event::addMarker(amd::HostQueue* queue, amd::Command* command) { amd::ScopedLock lock(lock_); if (event_ == &command->event()) return; if (event_ != nullptr) { event_->release(); } event_ = &command->event(); } } hipError_t ihipEventCreateWithFlags(hipEvent_t* event, unsigned flags) { if (event == nullptr) { return hipErrorInvalidValue; } unsigned supportedFlags = hipEventDefault | hipEventBlockingSync | hipEventDisableTiming | hipEventReleaseToDevice | hipEventReleaseToSystem; const unsigned releaseFlags = (hipEventReleaseToDevice | hipEventReleaseToSystem); const bool illegalFlags = (flags & ~supportedFlags) || // can't set any unsupported flags. (flags & releaseFlags) == releaseFlags; // can't set both release flags if (!illegalFlags) { hip::Event* e = new hip::Event(flags); if (e == nullptr) { return hipErrorOutOfMemory; } *event = reinterpret_cast<hipEvent_t>(e); } else { return hipErrorInvalidValue; } return hipSuccess; } hipError_t ihipEventQuery(hipEvent_t event) { if (event == nullptr) { return hipErrorInvalidHandle; } hip::Event* e = reinterpret_cast<hip::Event*>(event); return e->query(); } hipError_t hipEventCreateWithFlags(hipEvent_t* event, unsigned flags) { HIP_INIT_API(hipEventCreateWithFlags, event, flags); HIP_RETURN(ihipEventCreateWithFlags(event, flags)); } hipError_t hipEventCreate(hipEvent_t* event) { HIP_INIT_API(hipEventCreate, event); HIP_RETURN(ihipEventCreateWithFlags(event, 0)); } hipError_t hipEventDestroy(hipEvent_t event) { HIP_INIT_API(hipEventDestroy, event); if (event == nullptr) { HIP_RETURN(hipErrorInvalidHandle); } delete reinterpret_cast<hip::Event*>(event); HIP_RETURN(hipSuccess); } hipError_t hipEventElapsedTime(float *ms, hipEvent_t start, hipEvent_t stop) { HIP_INIT_API(hipEventElapsedTime, ms, start, stop); if (start == nullptr || stop == nullptr) { HIP_RETURN(hipErrorInvalidHandle); } if (ms == nullptr) { HIP_RETURN(hipErrorInvalidValue); } hip::Event* eStart = reinterpret_cast<hip::Event*>(start); hip::Event* eStop = reinterpret_cast<hip::Event*>(stop); HIP_RETURN(eStart->elapsedTime(*eStop, *ms)); } hipError_t hipEventRecord(hipEvent_t event, hipStream_t stream) { HIP_INIT_API(hipEventRecord, event, stream); if (event == nullptr) { HIP_RETURN(hipErrorInvalidHandle); } amd::HostQueue* queue = hip::getQueue(stream); amd::Command* command = queue->getLastQueuedCommand(true); if (command == nullptr) { command = new amd::Marker(*queue, false); command->enqueue(); } hip::Event* e = reinterpret_cast<hip::Event*>(event); e->addMarker(queue, command); HIP_RETURN(hipSuccess); } hipError_t hipEventSynchronize(hipEvent_t event) { HIP_INIT_API(hipEventSynchronize, event); if (event == nullptr) { HIP_RETURN(hipErrorInvalidHandle); } hip::Event* e = reinterpret_cast<hip::Event*>(event); HIP_RETURN(e->synchronize()); } hipError_t hipEventQuery(hipEvent_t event) { HIP_INIT_API(hipEventQuery, event); HIP_RETURN(ihipEventQuery(event)); } <|endoftext|>
<commit_before>/* Q Light Controller genericfader.cpp Copyright (c) Heikki Junnila Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <cmath> #include <QDebug> #include "genericfader.h" #include "fadechannel.h" #include "doc.h" GenericFader::GenericFader(QObject *parent) : QObject(parent) , m_priority(Universe::Auto) , m_intensity(1.0) , m_paused(false) , m_enabled(true) , m_fadeOut(false) , m_deleteRequest(false) , m_blendMode(Universe::NormalBlend) , m_monitoring(false) { } GenericFader::~GenericFader() { } int GenericFader::priority() const { return m_priority; } void GenericFader::setPriority(int priority) { m_priority = priority; } quint32 GenericFader::channelHash(quint32 fixtureID, quint32 channel) { return ((fixtureID & 0x0000FFFF) << 16) | (channel & 0x0000FFFF); } void GenericFader::add(const FadeChannel& ch) { quint32 hash = channelHash(ch.fixture(), ch.channel()); QHash<quint32,FadeChannel>::iterator channelIterator = m_channels.find(hash); if (channelIterator != m_channels.end()) { // perform a HTP check if (channelIterator.value().current() <= ch.current()) channelIterator.value() = ch; } else { m_channels.insert(hash, ch); qDebug() << "Added new fader with hash" << hash; } } void GenericFader::replace(const FadeChannel &ch) { quint32 hash = channelHash(ch.fixture(), ch.channel()); m_channels.insert(hash, ch); } void GenericFader::remove(FadeChannel *ch) { if (ch == NULL) return; quint32 hash = channelHash(ch->fixture(), ch->channel()); if (m_channels.remove(hash) == 0) qDebug() << "No FadeChannel found with hash" << hash; } void GenericFader::removeAll() { m_channels.clear(); } bool GenericFader::deleteRequest() { return m_deleteRequest; } void GenericFader::requestDelete() { m_deleteRequest = true; } FadeChannel *GenericFader::getChannelFader(const Doc *doc, Universe *universe, quint32 fixtureID, quint32 channel) { FadeChannel fc(doc, fixtureID, channel); quint32 hash = channelHash(fc.fixture(), fc.channel()); QHash<quint32,FadeChannel>::iterator channelIterator = m_channels.find(hash); if (channelIterator != m_channels.end()) return &channelIterator.value(); if (fc.type() & QLCChannel::Intensity) fc.setCurrent(0); // Intensity channels must start at zero else fc.setCurrent(universe->preGMValue(fc.address())); m_channels[hash] = fc; qDebug() << "Added new fader with hash" << hash; return &m_channels[hash]; } const QHash<quint32, FadeChannel> &GenericFader::channels() const { return m_channels; } int GenericFader::channelsCount() const { return m_channels.count(); } void GenericFader::write(Universe *universe) { if (m_monitoring) emit preWriteData(universe->id(), universe->preGMValues()); QMutableHashIterator <quint32,FadeChannel> it(m_channels); while (it.hasNext() == true) { FadeChannel& fc(it.next().value()); int channelType = fc.type(); quint32 address = fc.addressInUniverse(); uchar value; // Calculate the next step if (m_paused) value = fc.current(); else value = fc.nextStep(MasterTimer::tick()); // Apply intensity to HTP channels if ((channelType & FadeChannel::Intensity) && fc.canFade()) value = fc.current(intensity()); //qDebug() << "[GenericFader] >>> uni:" << universe->id() << ", address:" << address << ", value:" << value; if (channelType & FadeChannel::Override) universe->write(address, value, true); else if (channelType & FadeChannel::Relative) universe->writeRelative(address, value); else universe->writeBlended(address, value, m_blendMode); if ((channelType & FadeChannel::Intensity) && m_blendMode == Universe::NormalBlend) { // Remove all HTP channels that reach their target _zero_ value. // They have no effect either way so removing them saves a bit of CPU. if (fc.current() == 0 && fc.target() == 0) { it.remove(); continue; } } /* else { // Remove all LTP channels after their time is up if (fc.elapsed() >= fc.fadeTime()) it.remove(); } */ /* if (channelType & FadeChannel::Flashing) it.remove(); */ } } qreal GenericFader::intensity() const { return m_intensity; } void GenericFader::adjustIntensity(qreal fraction) { m_intensity = fraction; } bool GenericFader::isPaused() const { return m_paused; } void GenericFader::setPaused(bool paused) { m_paused = paused; } bool GenericFader::isEnabled() const { return m_enabled; } void GenericFader::setEnabled(bool enable) { m_enabled = enable; } bool GenericFader::isFadingOut() const { return m_fadeOut; } void GenericFader::setFadeOut(bool enable, uint fadeTime) { m_fadeOut = enable; if (fadeTime) { QMutableHashIterator <quint32,FadeChannel> it(m_channels); while (it.hasNext() == true) { FadeChannel& fc(it.next().value()); int channelType = fc.type(); if ((channelType & FadeChannel::Intensity) == 0) continue; fc.setStart(fc.current()); fc.setElapsed(0); fc.setReady(false); if (fc.canFade() == false) { fc.setFadeTime(0); } else { fc.setFadeTime(fadeTime); fc.setTarget(0); } } } } void GenericFader::setBlendMode(Universe::BlendMode mode) { m_blendMode = mode; } void GenericFader::setMonitoring(bool enable) { m_monitoring = enable; } <commit_msg>engine: fix nasty mistake when setting a new FadeChannel current value<commit_after>/* Q Light Controller genericfader.cpp Copyright (c) Heikki Junnila Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <cmath> #include <QDebug> #include "genericfader.h" #include "fadechannel.h" #include "doc.h" GenericFader::GenericFader(QObject *parent) : QObject(parent) , m_priority(Universe::Auto) , m_intensity(1.0) , m_paused(false) , m_enabled(true) , m_fadeOut(false) , m_deleteRequest(false) , m_blendMode(Universe::NormalBlend) , m_monitoring(false) { } GenericFader::~GenericFader() { } int GenericFader::priority() const { return m_priority; } void GenericFader::setPriority(int priority) { m_priority = priority; } quint32 GenericFader::channelHash(quint32 fixtureID, quint32 channel) { return ((fixtureID & 0x0000FFFF) << 16) | (channel & 0x0000FFFF); } void GenericFader::add(const FadeChannel& ch) { quint32 hash = channelHash(ch.fixture(), ch.channel()); QHash<quint32,FadeChannel>::iterator channelIterator = m_channels.find(hash); if (channelIterator != m_channels.end()) { // perform a HTP check if (channelIterator.value().current() <= ch.current()) channelIterator.value() = ch; } else { m_channels.insert(hash, ch); qDebug() << "Added new fader with hash" << hash; } } void GenericFader::replace(const FadeChannel &ch) { quint32 hash = channelHash(ch.fixture(), ch.channel()); m_channels.insert(hash, ch); } void GenericFader::remove(FadeChannel *ch) { if (ch == NULL) return; quint32 hash = channelHash(ch->fixture(), ch->channel()); if (m_channels.remove(hash) == 0) qDebug() << "No FadeChannel found with hash" << hash; } void GenericFader::removeAll() { m_channels.clear(); } bool GenericFader::deleteRequest() { return m_deleteRequest; } void GenericFader::requestDelete() { m_deleteRequest = true; } FadeChannel *GenericFader::getChannelFader(const Doc *doc, Universe *universe, quint32 fixtureID, quint32 channel) { FadeChannel fc(doc, fixtureID, channel); quint32 hash = channelHash(fc.fixture(), fc.channel()); QHash<quint32,FadeChannel>::iterator channelIterator = m_channels.find(hash); if (channelIterator != m_channels.end()) return &channelIterator.value(); if (fc.type() & FadeChannel::Intensity) fc.setCurrent(0); // Intensity channels must start at zero else fc.setCurrent(universe->preGMValue(fc.address())); m_channels[hash] = fc; qDebug() << "Added new fader with hash" << hash; return &m_channels[hash]; } const QHash<quint32, FadeChannel> &GenericFader::channels() const { return m_channels; } int GenericFader::channelsCount() const { return m_channels.count(); } void GenericFader::write(Universe *universe) { if (m_monitoring) emit preWriteData(universe->id(), universe->preGMValues()); QMutableHashIterator <quint32,FadeChannel> it(m_channels); while (it.hasNext() == true) { FadeChannel& fc(it.next().value()); int channelType = fc.type(); quint32 address = fc.addressInUniverse(); uchar value; // Calculate the next step if (m_paused) value = fc.current(); else value = fc.nextStep(MasterTimer::tick()); // Apply intensity to HTP channels if ((channelType & FadeChannel::Intensity) && fc.canFade()) value = fc.current(intensity()); //qDebug() << "[GenericFader] >>> uni:" << universe->id() << ", address:" << address << ", value:" << value; if (channelType & FadeChannel::Override) universe->write(address, value, true); else if (channelType & FadeChannel::Relative) universe->writeRelative(address, value); else universe->writeBlended(address, value, m_blendMode); if ((channelType & FadeChannel::Intensity) && m_blendMode == Universe::NormalBlend) { // Remove all HTP channels that reach their target _zero_ value. // They have no effect either way so removing them saves a bit of CPU. if (fc.current() == 0 && fc.target() == 0) { it.remove(); continue; } } /* else { // Remove all LTP channels after their time is up if (fc.elapsed() >= fc.fadeTime()) it.remove(); } */ /* if (channelType & FadeChannel::Flashing) it.remove(); */ } } qreal GenericFader::intensity() const { return m_intensity; } void GenericFader::adjustIntensity(qreal fraction) { m_intensity = fraction; } bool GenericFader::isPaused() const { return m_paused; } void GenericFader::setPaused(bool paused) { m_paused = paused; } bool GenericFader::isEnabled() const { return m_enabled; } void GenericFader::setEnabled(bool enable) { m_enabled = enable; } bool GenericFader::isFadingOut() const { return m_fadeOut; } void GenericFader::setFadeOut(bool enable, uint fadeTime) { m_fadeOut = enable; if (fadeTime) { QMutableHashIterator <quint32,FadeChannel> it(m_channels); while (it.hasNext() == true) { FadeChannel& fc(it.next().value()); int channelType = fc.type(); if ((channelType & FadeChannel::Intensity) == 0) continue; fc.setStart(fc.current()); fc.setElapsed(0); fc.setReady(false); if (fc.canFade() == false) { fc.setFadeTime(0); } else { fc.setFadeTime(fadeTime); fc.setTarget(0); } } } } void GenericFader::setBlendMode(Universe::BlendMode mode) { m_blendMode = mode; } void GenericFader::setMonitoring(bool enable) { m_monitoring = enable; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chrome_browser_field_trials.h" #include <string> #include "apps/field_trial_names.h" #include "apps/pref_names.h" #include "base/command_line.h" #include "base/metrics/field_trial.h" #include "base/prefs/pref_service.h" #include "base/string_util.h" #include "base/stringprintf.h" #include "base/strings/string_number_conversions.h" #include "base/strings/sys_string_conversions.h" #include "base/utf_string_conversions.h" #include "chrome/browser/auto_launch_trial.h" #include "chrome/browser/google/google_util.h" #include "chrome/browser/gpu/chrome_gpu_util.h" #include "chrome/browser/metrics/variations/variations_service.h" #include "chrome/browser/omnibox/omnibox_field_trial.h" #include "chrome/browser/prerender/prerender_field_trial.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/safe_browsing/safe_browsing_blocking_page.h" #include "chrome/browser/ui/sync/one_click_signin_helper.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_version_info.h" #include "chrome/common/metrics/variations/uniformity_field_trials.h" #include "chrome/common/metrics/variations/variations_util.h" #include "chrome/common/pref_names.h" #include "net/spdy/spdy_session.h" #include "ui/base/layout.h" #if defined(OS_WIN) #include "net/socket/tcp_client_socket_win.h" #endif // defined(OS_WIN) ChromeBrowserFieldTrials::ChromeBrowserFieldTrials( const CommandLine& parsed_command_line) : parsed_command_line_(parsed_command_line) { } ChromeBrowserFieldTrials::~ChromeBrowserFieldTrials() { } void ChromeBrowserFieldTrials::SetupFieldTrials(PrefService* local_state) { const base::Time install_time = base::Time::FromTimeT( local_state->GetInt64(prefs::kInstallDate)); DCHECK(!install_time.is_null()); chrome_variations::SetupUniformityFieldTrials(install_time); SetUpSimpleCacheFieldTrial(); #if !defined(OS_ANDROID) && !defined(OS_IOS) SetupDesktopFieldTrials(local_state); #endif // defined(OS_ANDROID) #if defined(OS_ANDROID) || defined(OS_IOS) SetupMobileFieldTrials(); #endif // defined(OS_ANDROID) || defined(OS_IOS) } #if defined(OS_ANDROID) || defined(OS_IOS) void ChromeBrowserFieldTrials::SetupMobileFieldTrials() { DataCompressionProxyFieldTrial(); } // Governs the rollout of the compression proxy for Chrome on mobile platforms. // Always enabled in DEV and BETA versions. // Stable percentage will be controlled from server. void ChromeBrowserFieldTrials::DataCompressionProxyFieldTrial() { const char kDataCompressionProxyFieldTrialName[] = "DataCompressionProxyRollout"; const base::FieldTrial::Probability kDataCompressionProxyDivisor = 1000; const base::FieldTrial::Probability kDataCompressionProxyStable = 0; const char kEnabled[] = "Enabled"; const char kDisabled[] = "Disabled"; // Find out if this is a stable channel. const bool kIsStableChannel = chrome::VersionInfo::GetChannel() == chrome::VersionInfo::CHANNEL_STABLE; // Experiment enabled until Jan 1, 2015. By default, disabled. scoped_refptr<base::FieldTrial> trial( base::FieldTrialList::FactoryGetFieldTrial( kDataCompressionProxyFieldTrialName, kDataCompressionProxyDivisor, kDisabled, 2015, 1, 1, NULL)); // Non-stable channels will run with probability 1. const int kEnabledGroup = trial->AppendGroup( kEnabled, kIsStableChannel ? kDataCompressionProxyStable : kDataCompressionProxyDivisor); const int v = trial->group(); VLOG(1) << "DataCompression proxy enabled group id: " << kEnabledGroup << ". Selected group id: " << v; } #endif // defined(OS_ANDROID) || defined(OS_IOS) void ChromeBrowserFieldTrials::SetupDesktopFieldTrials( PrefService* local_state) { prerender::ConfigurePrefetchAndPrerender(parsed_command_line_); SpdyFieldTrial(); AutoLaunchChromeFieldTrial(); gpu_util::InitializeCompositingFieldTrial(); OmniboxFieldTrial::ActivateStaticTrials(); SetUpInfiniteCacheFieldTrial(); SetUpCacheSensitivityAnalysisFieldTrial(); DisableShowProfileSwitcherTrialIfNecessary(); WindowsOverlappedTCPReadsFieldTrial(); #if defined(ENABLE_ONE_CLICK_SIGNIN) OneClickSigninHelper::InitializeFieldTrial(); #endif InstantiateDynamicTrials(); SetupAppLauncherFieldTrial(local_state); } void ChromeBrowserFieldTrials::SetupAppLauncherFieldTrial( PrefService* local_state) { if (base::FieldTrialList::FindFullName(apps::kLauncherPromoTrialName) == apps::kResetShowLauncherPromoPrefGroupName) { local_state->SetBoolean(apps::prefs::kShowAppLauncherPromo, true); } } // When --use-spdy not set, users will be in A/B test for spdy. // group A (npn_with_spdy): this means npn and spdy are enabled. In case server // supports spdy, browser will use spdy. // group B (npn_with_http): this means npn is enabled but spdy won't be used. // Http is still used for all requests. // default group: no npn or spdy is involved. The "old" non-spdy // chrome behavior. void ChromeBrowserFieldTrials::SpdyFieldTrial() { // Setup SPDY CWND Field trial. const base::FieldTrial::Probability kSpdyCwndDivisor = 100; const base::FieldTrial::Probability kSpdyCwnd16 = 20; // fixed at 16 const base::FieldTrial::Probability kSpdyCwnd10 = 20; // fixed at 10 const base::FieldTrial::Probability kSpdyCwndMin16 = 20; // no less than 16 const base::FieldTrial::Probability kSpdyCwndMin10 = 20; // no less than 10 // After June 30, 2013 builds, it will always be in default group // (cwndDynamic). scoped_refptr<base::FieldTrial> trial( base::FieldTrialList::FactoryGetFieldTrial( "SpdyCwnd", kSpdyCwndDivisor, "cwndDynamic", 2013, 6, 30, NULL)); trial->AppendGroup("cwnd10", kSpdyCwnd10); trial->AppendGroup("cwnd16", kSpdyCwnd16); trial->AppendGroup("cwndMin16", kSpdyCwndMin16); trial->AppendGroup("cwndMin10", kSpdyCwndMin10); } void ChromeBrowserFieldTrials::AutoLaunchChromeFieldTrial() { std::string brand; google_util::GetBrand(&brand); // Create a 100% field trial based on the brand code. if (auto_launch_trial::IsInExperimentGroup(brand)) { base::FieldTrialList::CreateFieldTrial(kAutoLaunchTrialName, kAutoLaunchTrialAutoLaunchGroup); } else if (auto_launch_trial::IsInControlGroup(brand)) { base::FieldTrialList::CreateFieldTrial(kAutoLaunchTrialName, kAutoLaunchTrialControlGroup); } } void ChromeBrowserFieldTrials::SetUpInfiniteCacheFieldTrial() { const base::FieldTrial::Probability kDivisor = 100; base::FieldTrial::Probability infinite_cache_probability = 0; scoped_refptr<base::FieldTrial> trial( base::FieldTrialList::FactoryGetFieldTrial("InfiniteCache", kDivisor, "No", 2013, 12, 31, NULL)); trial->UseOneTimeRandomization(); trial->AppendGroup("Yes", infinite_cache_probability); trial->AppendGroup("Control", infinite_cache_probability); } void ChromeBrowserFieldTrials::DisableShowProfileSwitcherTrialIfNecessary() { // This trial is created by the VariationsService, but it needs to be disabled // if multi-profiles isn't enabled or if browser frame avatar menu is // always hidden (Chrome OS). bool avatar_menu_always_hidden = false; #if defined(OS_CHROMEOS) avatar_menu_always_hidden = true; #endif base::FieldTrial* trial = base::FieldTrialList::Find("ShowProfileSwitcher"); if (trial && (!ProfileManager::IsMultipleProfilesEnabled() || avatar_menu_always_hidden)) { trial->Disable(); } } // Sets up the experiment. The actual cache backend choice is made in the net/ // internals by looking at the experiment state. void ChromeBrowserFieldTrials::SetUpSimpleCacheFieldTrial() { if (parsed_command_line_.HasSwitch(switches::kUseSimpleCacheBackend)) { const std::string opt_value = parsed_command_line_.GetSwitchValueASCII( switches::kUseSimpleCacheBackend); if (LowerCaseEqualsASCII(opt_value, "off")) { // This is the default. return; } const base::FieldTrial::Probability kDivisor = 100; scoped_refptr<base::FieldTrial> trial( base::FieldTrialList::FactoryGetFieldTrial("SimpleCacheTrial", kDivisor, "No", 2013, 12, 31, NULL)); trial->UseOneTimeRandomization(); if (LowerCaseEqualsASCII(opt_value, "on")) { trial->AppendGroup("Yes", 100); return; } #if defined(OS_ANDROID) if (LowerCaseEqualsASCII(opt_value, "experiment")) { // TODO(pasko): Make this the default on Android when the simple cache // adds a few more necessary features. Also adjust the probability. const base::FieldTrial::Probability kSimpleCacheProbability = 1; trial->AppendGroup("Yes", kSimpleCacheProbability); trial->AppendGroup("Control", kSimpleCacheProbability); trial->group(); } #endif } } void ChromeBrowserFieldTrials::SetUpCacheSensitivityAnalysisFieldTrial() { const base::FieldTrial::Probability kDivisor = 100; base::FieldTrial::Probability sensitivity_analysis_probability = 0; scoped_refptr<base::FieldTrial> trial( base::FieldTrialList::FactoryGetFieldTrial("CacheSensitivityAnalysis", kDivisor, "No", 2012, 12, 31, NULL)); trial->AppendGroup("ControlA", sensitivity_analysis_probability); trial->AppendGroup("ControlB", sensitivity_analysis_probability); trial->AppendGroup("100A", sensitivity_analysis_probability); trial->AppendGroup("100B", sensitivity_analysis_probability); trial->AppendGroup("200A", sensitivity_analysis_probability); trial->AppendGroup("200B", sensitivity_analysis_probability); trial->AppendGroup("400A", sensitivity_analysis_probability); trial->AppendGroup("400B", sensitivity_analysis_probability); } void ChromeBrowserFieldTrials::WindowsOverlappedTCPReadsFieldTrial() { #if defined(OS_WIN) if (parsed_command_line_.HasSwitch(switches::kOverlappedRead)) { std::string option = parsed_command_line_.GetSwitchValueASCII(switches::kOverlappedRead); if (LowerCaseEqualsASCII(option, "off")) net::TCPClientSocketWin::DisableOverlappedReads(); } else { const base::FieldTrial::Probability kDivisor = 2; // 1 in 2 chance const base::FieldTrial::Probability kOverlappedReadProbability = 1; scoped_refptr<base::FieldTrial> overlapped_reads_trial( base::FieldTrialList::FactoryGetFieldTrial("OverlappedReadImpact", kDivisor, "OverlappedReadEnabled", 2013, 6, 1, NULL)); int overlapped_reads_disabled_group = overlapped_reads_trial->AppendGroup("OverlappedReadDisabled", kOverlappedReadProbability); int assigned_group = overlapped_reads_trial->group(); if (assigned_group == overlapped_reads_disabled_group) net::TCPClientSocketWin::DisableOverlappedReads(); } #endif } void ChromeBrowserFieldTrials::InstantiateDynamicTrials() { // Call |FindValue()| on the trials below, which may come from the server, to // ensure they get marked as "used" for the purposes of data reporting. base::FieldTrialList::FindValue("UMA-Dynamic-Binary-Uniformity-Trial"); base::FieldTrialList::FindValue("UMA-Dynamic-Uniformity-Trial"); base::FieldTrialList::FindValue("InstantDummy"); base::FieldTrialList::FindValue("InstantChannel"); base::FieldTrialList::FindValue("Test0PercentDefault"); // Activate the autocomplete dynamic field trials. OmniboxFieldTrial::ActivateDynamicTrials(); } <commit_msg>1. Use one time randomization 2. We decided on 1% of initial usage.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chrome_browser_field_trials.h" #include <string> #include "apps/field_trial_names.h" #include "apps/pref_names.h" #include "base/command_line.h" #include "base/metrics/field_trial.h" #include "base/prefs/pref_service.h" #include "base/string_util.h" #include "base/stringprintf.h" #include "base/strings/string_number_conversions.h" #include "base/strings/sys_string_conversions.h" #include "base/utf_string_conversions.h" #include "chrome/browser/auto_launch_trial.h" #include "chrome/browser/google/google_util.h" #include "chrome/browser/gpu/chrome_gpu_util.h" #include "chrome/browser/metrics/variations/variations_service.h" #include "chrome/browser/omnibox/omnibox_field_trial.h" #include "chrome/browser/prerender/prerender_field_trial.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/safe_browsing/safe_browsing_blocking_page.h" #include "chrome/browser/ui/sync/one_click_signin_helper.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_version_info.h" #include "chrome/common/metrics/variations/uniformity_field_trials.h" #include "chrome/common/metrics/variations/variations_util.h" #include "chrome/common/pref_names.h" #include "net/spdy/spdy_session.h" #include "ui/base/layout.h" #if defined(OS_WIN) #include "net/socket/tcp_client_socket_win.h" #endif // defined(OS_WIN) ChromeBrowserFieldTrials::ChromeBrowserFieldTrials( const CommandLine& parsed_command_line) : parsed_command_line_(parsed_command_line) { } ChromeBrowserFieldTrials::~ChromeBrowserFieldTrials() { } void ChromeBrowserFieldTrials::SetupFieldTrials(PrefService* local_state) { const base::Time install_time = base::Time::FromTimeT( local_state->GetInt64(prefs::kInstallDate)); DCHECK(!install_time.is_null()); chrome_variations::SetupUniformityFieldTrials(install_time); SetUpSimpleCacheFieldTrial(); #if !defined(OS_ANDROID) && !defined(OS_IOS) SetupDesktopFieldTrials(local_state); #endif // defined(OS_ANDROID) #if defined(OS_ANDROID) || defined(OS_IOS) SetupMobileFieldTrials(); #endif // defined(OS_ANDROID) || defined(OS_IOS) } #if defined(OS_ANDROID) || defined(OS_IOS) void ChromeBrowserFieldTrials::SetupMobileFieldTrials() { DataCompressionProxyFieldTrial(); } // Governs the rollout of the compression proxy for Chrome on mobile platforms. // Always enabled in DEV and BETA versions. // Stable percentage will be controlled from server. void ChromeBrowserFieldTrials::DataCompressionProxyFieldTrial() { const char kDataCompressionProxyFieldTrialName[] = "DataCompressionProxyRollout"; const base::FieldTrial::Probability kDataCompressionProxyDivisor = 1000; // 10/1000 = 1% for starters. const base::FieldTrial::Probability kDataCompressionProxyStable = 10; const char kEnabled[] = "Enabled"; const char kDisabled[] = "Disabled"; // Find out if this is a stable channel. const bool kIsStableChannel = chrome::VersionInfo::GetChannel() == chrome::VersionInfo::CHANNEL_STABLE; // Experiment enabled until Jan 1, 2015. By default, disabled. scoped_refptr<base::FieldTrial> trial( base::FieldTrialList::FactoryGetFieldTrial( kDataCompressionProxyFieldTrialName, kDataCompressionProxyDivisor, kDisabled, 2015, 1, 1, NULL)); // We want our trial results to be persistent. trial->UseOneTimeRandomization(); // Non-stable channels will run with probability 1. const int kEnabledGroup = trial->AppendGroup( kEnabled, kIsStableChannel ? kDataCompressionProxyStable : kDataCompressionProxyDivisor); const int v = trial->group(); VLOG(1) << "DataCompression proxy enabled group id: " << kEnabledGroup << ". Selected group id: " << v; } #endif // defined(OS_ANDROID) || defined(OS_IOS) void ChromeBrowserFieldTrials::SetupDesktopFieldTrials( PrefService* local_state) { prerender::ConfigurePrefetchAndPrerender(parsed_command_line_); SpdyFieldTrial(); AutoLaunchChromeFieldTrial(); gpu_util::InitializeCompositingFieldTrial(); OmniboxFieldTrial::ActivateStaticTrials(); SetUpInfiniteCacheFieldTrial(); SetUpCacheSensitivityAnalysisFieldTrial(); DisableShowProfileSwitcherTrialIfNecessary(); WindowsOverlappedTCPReadsFieldTrial(); #if defined(ENABLE_ONE_CLICK_SIGNIN) OneClickSigninHelper::InitializeFieldTrial(); #endif InstantiateDynamicTrials(); SetupAppLauncherFieldTrial(local_state); } void ChromeBrowserFieldTrials::SetupAppLauncherFieldTrial( PrefService* local_state) { if (base::FieldTrialList::FindFullName(apps::kLauncherPromoTrialName) == apps::kResetShowLauncherPromoPrefGroupName) { local_state->SetBoolean(apps::prefs::kShowAppLauncherPromo, true); } } // When --use-spdy not set, users will be in A/B test for spdy. // group A (npn_with_spdy): this means npn and spdy are enabled. In case server // supports spdy, browser will use spdy. // group B (npn_with_http): this means npn is enabled but spdy won't be used. // Http is still used for all requests. // default group: no npn or spdy is involved. The "old" non-spdy // chrome behavior. void ChromeBrowserFieldTrials::SpdyFieldTrial() { // Setup SPDY CWND Field trial. const base::FieldTrial::Probability kSpdyCwndDivisor = 100; const base::FieldTrial::Probability kSpdyCwnd16 = 20; // fixed at 16 const base::FieldTrial::Probability kSpdyCwnd10 = 20; // fixed at 10 const base::FieldTrial::Probability kSpdyCwndMin16 = 20; // no less than 16 const base::FieldTrial::Probability kSpdyCwndMin10 = 20; // no less than 10 // After June 30, 2013 builds, it will always be in default group // (cwndDynamic). scoped_refptr<base::FieldTrial> trial( base::FieldTrialList::FactoryGetFieldTrial( "SpdyCwnd", kSpdyCwndDivisor, "cwndDynamic", 2013, 6, 30, NULL)); trial->AppendGroup("cwnd10", kSpdyCwnd10); trial->AppendGroup("cwnd16", kSpdyCwnd16); trial->AppendGroup("cwndMin16", kSpdyCwndMin16); trial->AppendGroup("cwndMin10", kSpdyCwndMin10); } void ChromeBrowserFieldTrials::AutoLaunchChromeFieldTrial() { std::string brand; google_util::GetBrand(&brand); // Create a 100% field trial based on the brand code. if (auto_launch_trial::IsInExperimentGroup(brand)) { base::FieldTrialList::CreateFieldTrial(kAutoLaunchTrialName, kAutoLaunchTrialAutoLaunchGroup); } else if (auto_launch_trial::IsInControlGroup(brand)) { base::FieldTrialList::CreateFieldTrial(kAutoLaunchTrialName, kAutoLaunchTrialControlGroup); } } void ChromeBrowserFieldTrials::SetUpInfiniteCacheFieldTrial() { const base::FieldTrial::Probability kDivisor = 100; base::FieldTrial::Probability infinite_cache_probability = 0; scoped_refptr<base::FieldTrial> trial( base::FieldTrialList::FactoryGetFieldTrial("InfiniteCache", kDivisor, "No", 2013, 12, 31, NULL)); trial->UseOneTimeRandomization(); trial->AppendGroup("Yes", infinite_cache_probability); trial->AppendGroup("Control", infinite_cache_probability); } void ChromeBrowserFieldTrials::DisableShowProfileSwitcherTrialIfNecessary() { // This trial is created by the VariationsService, but it needs to be disabled // if multi-profiles isn't enabled or if browser frame avatar menu is // always hidden (Chrome OS). bool avatar_menu_always_hidden = false; #if defined(OS_CHROMEOS) avatar_menu_always_hidden = true; #endif base::FieldTrial* trial = base::FieldTrialList::Find("ShowProfileSwitcher"); if (trial && (!ProfileManager::IsMultipleProfilesEnabled() || avatar_menu_always_hidden)) { trial->Disable(); } } // Sets up the experiment. The actual cache backend choice is made in the net/ // internals by looking at the experiment state. void ChromeBrowserFieldTrials::SetUpSimpleCacheFieldTrial() { if (parsed_command_line_.HasSwitch(switches::kUseSimpleCacheBackend)) { const std::string opt_value = parsed_command_line_.GetSwitchValueASCII( switches::kUseSimpleCacheBackend); if (LowerCaseEqualsASCII(opt_value, "off")) { // This is the default. return; } const base::FieldTrial::Probability kDivisor = 100; scoped_refptr<base::FieldTrial> trial( base::FieldTrialList::FactoryGetFieldTrial("SimpleCacheTrial", kDivisor, "No", 2013, 12, 31, NULL)); trial->UseOneTimeRandomization(); if (LowerCaseEqualsASCII(opt_value, "on")) { trial->AppendGroup("Yes", 100); return; } #if defined(OS_ANDROID) if (LowerCaseEqualsASCII(opt_value, "experiment")) { // TODO(pasko): Make this the default on Android when the simple cache // adds a few more necessary features. Also adjust the probability. const base::FieldTrial::Probability kSimpleCacheProbability = 1; trial->AppendGroup("Yes", kSimpleCacheProbability); trial->AppendGroup("Control", kSimpleCacheProbability); trial->group(); } #endif } } void ChromeBrowserFieldTrials::SetUpCacheSensitivityAnalysisFieldTrial() { const base::FieldTrial::Probability kDivisor = 100; base::FieldTrial::Probability sensitivity_analysis_probability = 0; scoped_refptr<base::FieldTrial> trial( base::FieldTrialList::FactoryGetFieldTrial("CacheSensitivityAnalysis", kDivisor, "No", 2012, 12, 31, NULL)); trial->AppendGroup("ControlA", sensitivity_analysis_probability); trial->AppendGroup("ControlB", sensitivity_analysis_probability); trial->AppendGroup("100A", sensitivity_analysis_probability); trial->AppendGroup("100B", sensitivity_analysis_probability); trial->AppendGroup("200A", sensitivity_analysis_probability); trial->AppendGroup("200B", sensitivity_analysis_probability); trial->AppendGroup("400A", sensitivity_analysis_probability); trial->AppendGroup("400B", sensitivity_analysis_probability); } void ChromeBrowserFieldTrials::WindowsOverlappedTCPReadsFieldTrial() { #if defined(OS_WIN) if (parsed_command_line_.HasSwitch(switches::kOverlappedRead)) { std::string option = parsed_command_line_.GetSwitchValueASCII(switches::kOverlappedRead); if (LowerCaseEqualsASCII(option, "off")) net::TCPClientSocketWin::DisableOverlappedReads(); } else { const base::FieldTrial::Probability kDivisor = 2; // 1 in 2 chance const base::FieldTrial::Probability kOverlappedReadProbability = 1; scoped_refptr<base::FieldTrial> overlapped_reads_trial( base::FieldTrialList::FactoryGetFieldTrial("OverlappedReadImpact", kDivisor, "OverlappedReadEnabled", 2013, 6, 1, NULL)); int overlapped_reads_disabled_group = overlapped_reads_trial->AppendGroup("OverlappedReadDisabled", kOverlappedReadProbability); int assigned_group = overlapped_reads_trial->group(); if (assigned_group == overlapped_reads_disabled_group) net::TCPClientSocketWin::DisableOverlappedReads(); } #endif } void ChromeBrowserFieldTrials::InstantiateDynamicTrials() { // Call |FindValue()| on the trials below, which may come from the server, to // ensure they get marked as "used" for the purposes of data reporting. base::FieldTrialList::FindValue("UMA-Dynamic-Binary-Uniformity-Trial"); base::FieldTrialList::FindValue("UMA-Dynamic-Uniformity-Trial"); base::FieldTrialList::FindValue("InstantDummy"); base::FieldTrialList::FindValue("InstantChannel"); base::FieldTrialList::FindValue("Test0PercentDefault"); // Activate the autocomplete dynamic field trials. OmniboxFieldTrial::ActivateDynamicTrials(); } <|endoftext|>
<commit_before>/* Copyright [2014] [John-Michael Reed] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* * File: main.cpp * Author: johnmichaelreed2 * * Created on November 29, 2014, 3:35 PM */ #include <cstdlib> using namespace std; // 64 bit integers used for type identification #define THING -9223372036854775808LL #define ACTION -9223372036854775807LL // Functional allows me to bind functions and call them with different numbers of parameters #include <functional> #include <iostream> #include <unordered_map> // cstdarg allows for variadic function pointers #include <cstdarg> // out_of_range exceptions are thrown by unordered_map #include <exception> #include <bits/unordered_map.h> #include <memory> // Function pointer cast. // Produces a function that takes in an arbitrary # of args and returns a shared pointer typedef std::shared_ptr<void> (*pcast) (...); // type is stored as a 64 bit value at the head of an object long long getType(void * head) { return (long long) head; } // Function is a container for a re-assignable function pointer struct Function { // type is used to get the type of an object via the getType global function. static const long long type = ACTION; // execute is a re-assignable general purpose function pointer. // Takes in an arbitrary # of args and returns a void * public: pcast execute; Function() { this->execute = nullptr; //apparently you can't set a variadic funtion pointer to zero. } void operator=(const Function& other) // copy assignment { this->execute = other.execute; } }; //Thing is a container of local variables and actions. class Thing { public: const long long type = THING; private: std::unordered_map<std::string, std::shared_ptr<void> > Properties_Table; private: std::unordered_map<std::string, Function > Functions_Table; public: Thing * my_parent; Thing() { Properties_Table = {}; Functions_Table = {}; } Thing(Thing &new_parent) { Properties_Table = {}; Functions_Table = {}; this->my_parent = &new_parent; } // Add a copy of a single object property to the properties hash table. template <class Type> void addProperty(const std::string property_name, const Type &property_value) { Properties_Table[property_name] = std::shared_ptr<void>(new Type(property_value)); } // Add a single action to the actions hash table. void addFunction(std::string action_name, Function action_value) { Functions_Table[action_name] = action_value; } std::shared_ptr<void> get(const std::string &toGet) { //If the element exists, get it. try { return Properties_Table.at(toGet); } //Else check to see if the my_parent has it catch (const std::out_of_range& oor) { if (this->my_parent != nullptr) { return this->my_parent->get(toGet); } else { throw std::out_of_range("Member not found."); std::shared_ptr<int> ERROR_POINTER(nullptr); return ERROR_POINTER; } } } // Provides the pointer to call a function // Function_name is the name as a std::string. template<class Type> pcast Do(const Type function_name) { pcast return_value = nullptr; //Calls the corresponding function in the hash table of function objects. try { return_value = (Functions_Table.at((std::string)function_name)).execute; } //C++ map throws an exception if function not found. catch (const std::out_of_range& oor) { //Check my_parent. if (this->my_parent != nullptr) return_value = this->my_parent->Do(function_name); //Give up. else throw std::out_of_range("Function cound not be found."); } return return_value; } // Assigns a function pointer to an action in the table of actions. template< class Type> void set(const std::string function_name, const Type newFunction) { (Functions_Table.at(function_name)).execute = (pcast) newFunction; } }; #define a auto #define pbool (std::static_pointer_cast<bool>) #define pint (std::static_pointer_cast<int>) #define pdouble (std::static_pointer_cast<double>) #define pstring (std::static_pointer_cast<std::string>) #define pThing (std::static_pointer_cast<Thing>) std::shared_ptr<int> add(int aa, int bb) { std::shared_ptr<int> return_pointer(new int(aa + bb)); return return_pointer; } int main() { Thing snake; //Create a snake Function doMath; //add is the add function doMath.execute = (pcast) add; //Make doMath execute function add snake.addFunction("add", doMath); a distance = pint((snake.Do("add"))(5, 6)); //Tell snake to call doMath printf("Parent: 5 + 6 = %d \n", *distance); //doMath executes add Thing baby_snake(snake); //Create a baby whose parent is snake a baby_distance = pint((baby_snake.Do("add"))(1, 2)); //Call parent function printf("Child: 1 + 2 = %d \n", *baby_distance); a rr = 444; snake.addProperty("age", rr); //Give snake an age a age_of_snake = pint(snake.get("age")); //retrieve age with a string printf("Age of parent is: %d \n", *age_of_snake); //don't call free on this a segments = 32.5; snake.addProperty("seg", segments); a number_of_segments = pdouble(snake.get("seg")); //retrieve segments cout << "Number of segments in snake: " << *number_of_segments << endl; a number_of_segments_in_baby = pdouble(baby_snake.get("seg")); cout << "Child inherits segment variable: " << *number_of_segments_in_baby << endl; static struct New_Function : public Function { //Create a new function closure long long value = 123ll; static std::shared_ptr<int> execute(int aa, int bb, int dd) { cout << "Call return5 function to get: " << return5() << endl; cout << "do subtract" << endl; std::shared_ptr<int> ret(new int(aa - bb - dd)); return ret; } New_Function() { cout << "Function type value is: " << this->type << endl; cout << "Function parent's type value is: " << Function::type << endl; Function::execute = (pcast)this->execute; } static int return5() { return 5; } } new_action; snake.addFunction("measure", new_action); //"measure" will call execute a subtraction = pint((snake.Do("measure"))(10, 2, 1)); printf("10 - 2 - 1 = %d", *subtraction); return 0; } <commit_msg>Added ()<commit_after>/* Copyright [2014] [John-Michael Reed] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* * File: main.cpp * Author: johnmichaelreed2 * * Created on November 29, 2014, 3:35 PM */ #include <cstdlib> using namespace std; // 64 bit integers used for type identification #define THING -9223372036854775808LL #define ACTION -9223372036854775807LL // Functional allows me to bind functions and call them with different numbers of parameters #include <functional> #include <iostream> #include <unordered_map> // cstdarg allows for variadic function pointers #include <cstdarg> // out_of_range exceptions are thrown by unordered_map #include <exception> #include <bits/unordered_map.h> #include <memory> // Function pointer cast. // Produces a function that takes in an arbitrary # of args and returns a shared pointer typedef std::shared_ptr<void> (*pcast) (...); // type is stored as a 64 bit value at the head of an object long long getType(void * head) { return (long long) head; } // Function is a container for a re-assignable function pointer struct Function { // type is used to get the type of an object via the getType global function. static const long long type = ACTION; // execute is a re-assignable general purpose function pointer. // Takes in an arbitrary # of args and returns a void * public: pcast execute; Function() { this->execute = nullptr; //apparently you can't set a variadic funtion pointer to zero. } void operator=(const Function& other) // copy assignment { this->execute = other.execute; } pcast &operator()() {return this->execute;} }; //Thing is a container of local variables and actions. class Thing { public: const long long type = THING; private: std::unordered_map<std::string, std::shared_ptr<void> > Properties_Table; private: std::unordered_map<std::string, Function > Functions_Table; public: Thing * my_parent; Thing() { Properties_Table = {}; Functions_Table = {}; } Thing(Thing &new_parent) { Properties_Table = {}; Functions_Table = {}; this->my_parent = &new_parent; } // Add a copy of a single object property to the properties hash table. template <class Type> void addProperty(const std::string property_name, const Type &property_value) { Properties_Table[property_name] = std::shared_ptr<void>(new Type(property_value)); } // Add a single action to the actions hash table. void addFunction(std::string action_name, Function action_value) { Functions_Table[action_name] = action_value; } std::shared_ptr<void> get(const std::string &toGet) { //If the element exists, get it. try { return Properties_Table.at(toGet); } //Else check to see if the my_parent has it catch (const std::out_of_range& oor) { if (this->my_parent != nullptr) { return this->my_parent->get(toGet); } else { throw std::out_of_range("Member not found."); std::shared_ptr<int> ERROR_POINTER(nullptr); return ERROR_POINTER; } } } // Provides the pointer to call a function // Function_name is the name as a std::string. template<class Type> pcast Do(const Type function_name) { pcast return_value = nullptr; //Calls the corresponding function in the hash table of function objects. try { return_value = (Functions_Table.at((std::string)function_name)).execute; } //C++ map throws an exception if function not found. catch (const std::out_of_range& oor) { //Check my_parent. if (this->my_parent != nullptr) return_value = this->my_parent->Do(function_name); //Give up. else throw std::out_of_range("Function cound not be found."); } return return_value; } // Assigns a function pointer to an action in the table of actions. template< class Type> void set(const std::string function_name, const Type newFunction) { (Functions_Table.at(function_name)).execute = (pcast) newFunction; } }; #define a auto #define pbool (std::static_pointer_cast<bool>) #define pint (std::static_pointer_cast<int>) #define pdouble (std::static_pointer_cast<double>) #define pstring (std::static_pointer_cast<std::string>) #define pThing (std::static_pointer_cast<Thing>) std::shared_ptr<int> add(int aa, int bb) { std::shared_ptr<int> return_pointer(new int(aa + bb)); return return_pointer; } int main() { Thing snake; //Create a snake Function doMath; //add is the add function doMath() = (pcast) add; //Make doMath execute function add snake.addFunction("add", doMath); a distance = pint((snake.Do("add"))(5, 6)); //Tell snake to call doMath printf("Parent: 5 + 6 = %d \n", *distance); //doMath executes add Thing baby_snake(snake); //Create a baby whose parent is snake a baby_distance = pint((baby_snake.Do("add"))(1, 2)); //Call parent function printf("Child: 1 + 2 = %d \n", *baby_distance); a rr = 444; snake.addProperty("age", rr); //Give snake an age a age_of_snake = pint(snake.get("age")); //retrieve age with a string printf("Age of parent is: %d \n", *age_of_snake); //don't call free on this a segments = 32.5; snake.addProperty("seg", segments); a number_of_segments = pdouble(snake.get("seg")); //retrieve segments cout << "Number of segments in snake: " << *number_of_segments << endl; a number_of_segments_in_baby = pdouble(baby_snake.get("seg")); cout << "Child inherits segment variable: " << *number_of_segments_in_baby << endl; static struct New_Function : public Function { //Create a new function closure long long value = 123ll; static std::shared_ptr<int> execute(int aa, int bb, int dd) { cout << "Call return5 function to get: " << return5() << endl; cout << "do subtract" << endl; std::shared_ptr<int> ret(new int(aa - bb - dd)); return ret; } New_Function() { cout << "Function type value is: " << this->type << endl; cout << "Function parent's type value is: " << Function::type << endl; Function::execute = (pcast)this->execute; } static int return5() { return 5; } } new_action; snake.addFunction("measure", new_action); //"measure" will call execute a subtraction = pint((snake.Do("measure"))(10, 2, 1)); printf("10 - 2 - 1 = %d", *subtraction); return 0; } <|endoftext|>
<commit_before>#ifndef H_DSCPP_PUSHABLE #define H_DSCPP_PUSHABLE #include "api.hh" #include "rapidjson/document.h" #include <curl/curl.h> namespace dsc { class Pushable : Fetchable { private: typedef size_t(*CURL_WRITEFUNCTION_PTR)(void*, size_t, size_t, void*); rapidjson::Document serialize(); const char* endpoint_name; void buildEndpointUri(char* out); bool getErrCode(rapidjson::Document* d, ErrorCode* r); public: marshal(char* out); // to make thread-safe, call curl_global_init() ErrorCode push(Client* c, long* err); // to make thread-safe, call curl_global_init() ErrorCode delete(Client* c, long* err); }; void Pushable::marshal(char* out) { using namespace rapidjson; Document d = serialize(); StringBuffer buf; Writer<StringBuffer> writer(buf); d.Accept(writer); out = buf.GetString(); }; void Pushable::buildEndpointUri(Client* c, char* out) { sprintf(out, "%s/%s/llu", c->sessionEndpointUri, endpoint_name, id); } ErrorCode Pushable::getErrCode(rapidjson::Document* d) { if(!d["code"].IsInt()) return JSON_PARSE_FAILED; return static_cast<ErrorCode>(d["code"].GetInt()); } ErrorCode Pushable::push(Client* c, long* err, bool mkNew = false) { char* uri; buildEndpointUri(c, uri); curl_global_init(); CURL* curl = c->getCurl(); CURLcode res; if(!curl) return CURL_INIT_FAILED; if(res = curl_easy_setopt(curl, CURLOPT_URL, uri) != CURLE_OK) { *err = res; return CURL_INIT_FAILED; } if(mkNew) { if(res = curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST")) { *err = res; return CURL_INIT_FAILED; } } else { if(res = curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PATCH") != CURLE_OK) { *err = res; return CURL_INIT_FAILED; } } struct curl_slist* header; header = curl_slist_append(header, "Content-Type:application/json"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header); char* payload; marshal(payload); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload); ErrorCode ret; curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ret); auto wfunc = [](void* dat, size_t size, size_t nmemb, void* ret) { using namespace rapidjson; Document d = new Document(); ParseResult ok = d.Parse(static_cast<char*>(dat)); if(!ok) { *err = ok; *ret = JSON_PARSE_FAILED; } long httpStat; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpStat); if(httpStat > 299) { getErrCode(d, ret); *err = httpStat; } else { *ret = NIL; } return size * nmemb; }; curl_easy_setopt(curl, CURLOPT_WRITEFUNC, static_cast<CURLOPT_WRITEFUNCTION_PTR>(&wfunc)); CURLcode res = curl_easy_perform(curl); if(cresp != CURLE_OK) return res; curl_easy_cleanup(c->getCurl()); curl_slist_free(header); return NIL; } ErrorCode Pushable::delete(Client* c, long* err) { char* uri; buildEndpointUri(c, uri); curl_global_init(); CURL* curl = curl_easy_init(); if(!curl) return CURL_INIT_FAILED; CURLcode res; if(res = curl_easy_setopt(curl, CURLOPT_URL, uri) != CURLE_OK) { *err = res; return CURL_INIT_FAILED; } if(res = curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE")) { *err = res; return CURL_INIT_FAILED; } if(res = curl_easy_perform(curl) != CURLE_OK) { *err = res; return CURL_PERFORM_FAILED; } long httpStat; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpStat); curl_easy_cleanup(c->getCurl()); if(300 <= httpStat < 200) { *err = httpStat; return getRespCode(d, err); } return NIL; } } #endif<commit_msg>remove extraneous cURL initialization calls<commit_after>#ifndef H_DSCPP_PUSHABLE #define H_DSCPP_PUSHABLE #include "api.hh" #include "rapidjson/document.h" #include <curl/curl.h> namespace dsc { class Pushable : Fetchable { private: typedef size_t(*CURL_WRITEFUNCTION_PTR)(void*, size_t, size_t, void*); rapidjson::Document serialize(); const char* endpoint_name; void buildEndpointUri(char* out); bool getErrCode(rapidjson::Document* d, ErrorCode* r); public: marshal(char* out); // to make thread-safe, call curl_global_init() ErrorCode push(Client* c, long* err); // to make thread-safe, call curl_global_init() ErrorCode delete(Client* c, long* err); }; void Pushable::marshal(char* out) { using namespace rapidjson; Document d = serialize(); StringBuffer buf; Writer<StringBuffer> writer(buf); d.Accept(writer); out = buf.GetString(); }; void Pushable::buildEndpointUri(Client* c, char* out) { sprintf(out, "%s/%s/llu", c->sessionEndpointUri, endpoint_name, id); } ErrorCode Pushable::getErrCode(rapidjson::Document* d) { if(!d["code"].IsInt()) return JSON_PARSE_FAILED; return static_cast<ErrorCode>(d["code"].GetInt()); } ErrorCode Pushable::push(Client* c, long* err, bool mkNew = false) { char* uri; buildEndpointUri(c, uri); CURL* curl = c->getCurl(); CURLcode res; if(!curl) return CURL_INIT_FAILED; if(res = curl_easy_setopt(curl, CURLOPT_URL, uri) != CURLE_OK) { *err = res; return CURL_INIT_FAILED; } if(mkNew) { if(res = curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST")) { *err = res; return CURL_INIT_FAILED; } } else { if(res = curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PATCH") != CURLE_OK) { *err = res; return CURL_INIT_FAILED; } } struct curl_slist* header; header = curl_slist_append(header, "Content-Type:application/json"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header); char* payload; marshal(payload); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload); ErrorCode ret; curl_easy_setopt(curl, CURLOPT_WRITEDATA, &ret); auto wfunc = [](void* dat, size_t size, size_t nmemb, void* ret) { using namespace rapidjson; Document d = new Document(); ParseResult ok = d.Parse(static_cast<char*>(dat)); if(!ok) { *err = ok; *ret = JSON_PARSE_FAILED; } long httpStat; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpStat); if(httpStat > 299) { getErrCode(d, ret); *err = httpStat; } else { *ret = NIL; } return size * nmemb; }; curl_easy_setopt(curl, CURLOPT_WRITEFUNC, static_cast<CURLOPT_WRITEFUNCTION_PTR>(&wfunc)); CURLcode res = curl_easy_perform(curl); if(cresp != CURLE_OK) return res; curl_easy_cleanup(c->getCurl()); curl_slist_free(header); return NIL; } ErrorCode Pushable::delete(Client* c, long* err) { char* uri; buildEndpointUri(c, uri); CURL* curl = curl_easy_init(); if(!curl) return CURL_INIT_FAILED; CURLcode res; if(res = curl_easy_setopt(curl, CURLOPT_URL, uri) != CURLE_OK) { *err = res; return CURL_INIT_FAILED; } if(res = curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE")) { *err = res; return CURL_INIT_FAILED; } if(res = curl_easy_perform(curl) != CURLE_OK) { *err = res; return CURL_PERFORM_FAILED; } long httpStat; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpStat); curl_easy_cleanup(c->getCurl()); if(300 <= httpStat < 200) { *err = httpStat; return getRespCode(d, err); } return NIL; } } #endif<|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2015 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include "taskqueue.h" #include "executorpool.h" #include "executorthread.h" #include <cmath> TaskQueue::TaskQueue(ExecutorPool *m, task_type_t t, const char *nm) : name(nm), queueType(t), manager(m), sleepers(0) { // EMPTY } TaskQueue::~TaskQueue() { LOG(EXTENSION_LOG_INFO, "Task Queue killing %s", name.c_str()); } const std::string TaskQueue::getName() const { return (name+taskType2Str(queueType)); } size_t TaskQueue::getReadyQueueSize() { LockHolder lh(mutex); return readyQueue.size(); } size_t TaskQueue::getFutureQueueSize() { LockHolder lh(mutex); return futureQueue.size(); } size_t TaskQueue::getPendingQueueSize() { LockHolder lh(mutex); return pendingQueue.size(); } ExTask TaskQueue::_popReadyTask(void) { ExTask t = readyQueue.top(); readyQueue.pop(); manager->lessWork(queueType); return t; } void TaskQueue::doWake(size_t &numToWake) { LockHolder lh(mutex); _doWake_UNLOCKED(numToWake); } void TaskQueue::_doWake_UNLOCKED(size_t &numToWake) { if (sleepers && numToWake) { if (numToWake < sleepers) { for (; numToWake; --numToWake) { mutex.notify_one(); // cond_signal 1 } } else { mutex.notify_all(); // cond_broadcast numToWake -= sleepers; } } } bool TaskQueue::_doSleep(ExecutorThread &t, std::unique_lock<std::mutex>& lock) { t.updateCurrentTime(); if (t.getCurTime() < t.getWaketime() && manager->trySleep(queueType)) { // Atomically switch from running to sleeping; iff we were previously // running. executor_state_t expected_state = EXECUTOR_RUNNING; if (!t.state.compare_exchange_strong(expected_state, EXECUTOR_SLEEPING)) { return false; } sleepers++; // zzz.... const auto snooze = t.getWaketime() - t.getCurTime(); if (snooze > std::chrono::seconds((int)round(MIN_SLEEP_TIME))) { mutex.wait_for(lock, MIN_SLEEP_TIME); } else { mutex.wait_for(lock, snooze); } // ... woke! sleepers--; manager->woke(); // Finished our sleep, atomically switch back to running iff we were // previously sleeping. expected_state = EXECUTOR_SLEEPING; if (!t.state.compare_exchange_strong(expected_state, EXECUTOR_RUNNING)) { return false; } t.updateCurrentTime(); } t.setWaketime(ProcessClock::time_point(ProcessClock::time_point::max())); return true; } bool TaskQueue::_fetchNextTask(ExecutorThread &t, bool toSleep) { bool ret = false; std::unique_lock<std::mutex> lh(mutex); if (toSleep && !_doSleep(t, lh)) { return ret; // shutting down } size_t numToWake = _moveReadyTasks(t.getCurTime()); if (!futureQueue.empty() && t.taskType == queueType && futureQueue.top()->getWaketime() < t.getWaketime()) { // record earliest waketime t.setWaketime(futureQueue.top()->getWaketime()); } if (!readyQueue.empty() && readyQueue.top()->isdead()) { t.setCurrentTask(_popReadyTask()); // clean out dead tasks first ret = true; } else if (!readyQueue.empty() || !pendingQueue.empty()) { // we must consider any pending tasks too. To ensure prioritized run // order, the function below will push any pending task back into the // readyQueue (sorted by priority) _checkPendingQueue(); ExTask tid = _popReadyTask(); // and pop out the top task t.setCurrentTask(tid); ret = true; } else { // Let the task continue waiting in pendingQueue numToWake = numToWake ? numToWake - 1 : 0; // 1 fewer task ready } _doWake_UNLOCKED(numToWake); lh.unlock(); return ret; } bool TaskQueue::fetchNextTask(ExecutorThread &thread, bool toSleep) { EventuallyPersistentEngine *epe = ObjectRegistry::onSwitchThread(NULL, true); bool rv = _fetchNextTask(thread, toSleep); ObjectRegistry::onSwitchThread(epe); return rv; } size_t TaskQueue::_moveReadyTasks(const ProcessClock::time_point tv) { if (!readyQueue.empty()) { return 0; } size_t numReady = 0; while (!futureQueue.empty()) { ExTask tid = futureQueue.top(); if (tid->getWaketime() <= tv) { futureQueue.pop(); readyQueue.push(tid); numReady++; } else { break; } } manager->addWork(numReady, queueType); // Current thread will pop one task, so wake up one less thread return numReady ? numReady - 1 : 0; } void TaskQueue::_checkPendingQueue(void) { if (!pendingQueue.empty()) { ExTask runnableTask = pendingQueue.front(); readyQueue.push(runnableTask); manager->addWork(1, queueType); pendingQueue.pop_front(); } } ProcessClock::time_point TaskQueue::_reschedule(ExTask &task) { LockHolder lh(mutex); futureQueue.push(task); return futureQueue.top()->getWaketime(); } ProcessClock::time_point TaskQueue::reschedule(ExTask &task) { EventuallyPersistentEngine *epe = ObjectRegistry::onSwitchThread(NULL, true); auto rv = _reschedule(task); ObjectRegistry::onSwitchThread(epe); return rv; } void TaskQueue::_schedule(ExTask &task) { TaskQueue* sleepQ; size_t numToWake = 1; { LockHolder lh(mutex); // If we are rescheduling a previously cancelled task, we should reset // the task state to the initial value of running. task->setState(TASK_RUNNING, TASK_DEAD); futureQueue.push(task); LOG(EXTENSION_LOG_DEBUG, "%s: Schedule a task \"%.*s\" id %" PRIu64, name.c_str(), int(task->getDescription().size()), task->getDescription().data(), uint64_t(task->getId())); sleepQ = manager->getSleepQ(queueType); _doWake_UNLOCKED(numToWake); } if (this != sleepQ) { sleepQ->doWake(numToWake); } } void TaskQueue::schedule(ExTask &task) { EventuallyPersistentEngine *epe = ObjectRegistry::onSwitchThread(NULL, true); _schedule(task); ObjectRegistry::onSwitchThread(epe); } void TaskQueue::_wake(ExTask &task) { const ProcessClock::time_point now = ProcessClock::now(); TaskQueue* sleepQ; // One task is being made ready regardless of the queue it's in. size_t readyCount = 1; { LockHolder lh(mutex); LOG(EXTENSION_LOG_DEBUG, "%s: Wake a task \"%.*s\" id %" PRIu64, name.c_str(), int(task->getDescription().size()), task->getDescription().data(), uint64_t(task->getId())); std::queue<ExTask> notReady; // Wake thread-count-serialized tasks too for (std::list<ExTask>::iterator it = pendingQueue.begin(); it != pendingQueue.end();) { ExTask tid = *it; if (tid->getId() == task->getId() || tid->isdead()) { notReady.push(tid); it = pendingQueue.erase(it); } else { it++; } } futureQueue.updateWaketime(task, now); task->setState(TASK_RUNNING, TASK_SNOOZED); while (!notReady.empty()) { ExTask tid = notReady.front(); if (tid->getWaketime() <= now || tid->isdead()) { readyCount++; } // MB-18453: Only push to the futureQueue futureQueue.push(tid); notReady.pop(); } _doWake_UNLOCKED(readyCount); sleepQ = manager->getSleepQ(queueType); } if (this != sleepQ) { sleepQ->doWake(readyCount); } } void TaskQueue::wake(ExTask &task) { EventuallyPersistentEngine *epe = ObjectRegistry::onSwitchThread(NULL, true); _wake(task); ObjectRegistry::onSwitchThread(epe); } const std::string TaskQueue::taskType2Str(task_type_t type) { switch (type) { case WRITER_TASK_IDX: return std::string("Writer"); case READER_TASK_IDX: return std::string("Reader"); case AUXIO_TASK_IDX: return std::string("AuxIO"); case NONIO_TASK_IDX: return std::string("NonIO"); default: return std::string("None"); } } <commit_msg>MB-35649: Fix lost (delayed) wakeups in ep background tasks<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2015 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "config.h" #include "taskqueue.h" #include "executorpool.h" #include "executorthread.h" #include <cmath> TaskQueue::TaskQueue(ExecutorPool *m, task_type_t t, const char *nm) : name(nm), queueType(t), manager(m), sleepers(0) { // EMPTY } TaskQueue::~TaskQueue() { LOG(EXTENSION_LOG_INFO, "Task Queue killing %s", name.c_str()); } const std::string TaskQueue::getName() const { return (name+taskType2Str(queueType)); } size_t TaskQueue::getReadyQueueSize() { LockHolder lh(mutex); return readyQueue.size(); } size_t TaskQueue::getFutureQueueSize() { LockHolder lh(mutex); return futureQueue.size(); } size_t TaskQueue::getPendingQueueSize() { LockHolder lh(mutex); return pendingQueue.size(); } ExTask TaskQueue::_popReadyTask(void) { ExTask t = readyQueue.top(); readyQueue.pop(); manager->lessWork(queueType); return t; } void TaskQueue::doWake(size_t &numToWake) { LockHolder lh(mutex); _doWake_UNLOCKED(numToWake); } void TaskQueue::_doWake_UNLOCKED(size_t &numToWake) { if (sleepers && numToWake) { if (numToWake < sleepers) { for (; numToWake; --numToWake) { mutex.notify_one(); // cond_signal 1 } } else { mutex.notify_all(); // cond_broadcast numToWake -= sleepers; } } } bool TaskQueue::_doSleep(ExecutorThread &t, std::unique_lock<std::mutex>& lock) { t.updateCurrentTime(); // Determine the time point to wake this thread - either "forever" if the // futureQueue is empty, or the earliest wake time in the futureQueue. const auto wakeTime = futureQueue.empty() ? std::chrono::steady_clock::time_point::max() : futureQueue.top()->getWaketime(); if (t.getCurTime() < wakeTime && manager->trySleep(queueType)) { // Atomically switch from running to sleeping; iff we were previously // running. executor_state_t expected_state = EXECUTOR_RUNNING; if (!t.state.compare_exchange_strong(expected_state, EXECUTOR_SLEEPING)) { return false; } sleepers++; // zzz.... const auto snooze = wakeTime - t.getCurTime(); if (snooze > std::chrono::seconds((int)round(MIN_SLEEP_TIME))) { mutex.wait_for(lock, MIN_SLEEP_TIME); } else { mutex.wait_for(lock, snooze); } // ... woke! sleepers--; manager->woke(); // Finished our sleep, atomically switch back to running iff we were // previously sleeping. expected_state = EXECUTOR_SLEEPING; if (!t.state.compare_exchange_strong(expected_state, EXECUTOR_RUNNING)) { return false; } t.updateCurrentTime(); } t.setWaketime(ProcessClock::time_point(ProcessClock::time_point::max())); return true; } bool TaskQueue::_fetchNextTask(ExecutorThread &t, bool toSleep) { bool ret = false; std::unique_lock<std::mutex> lh(mutex); if (toSleep && !_doSleep(t, lh)) { return ret; // shutting down } size_t numToWake = _moveReadyTasks(t.getCurTime()); if (!futureQueue.empty() && t.taskType == queueType && futureQueue.top()->getWaketime() < t.getWaketime()) { // record earliest waketime t.setWaketime(futureQueue.top()->getWaketime()); } if (!readyQueue.empty() && readyQueue.top()->isdead()) { t.setCurrentTask(_popReadyTask()); // clean out dead tasks first ret = true; } else if (!readyQueue.empty() || !pendingQueue.empty()) { // we must consider any pending tasks too. To ensure prioritized run // order, the function below will push any pending task back into the // readyQueue (sorted by priority) _checkPendingQueue(); ExTask tid = _popReadyTask(); // and pop out the top task t.setCurrentTask(tid); ret = true; } else { // Let the task continue waiting in pendingQueue numToWake = numToWake ? numToWake - 1 : 0; // 1 fewer task ready } _doWake_UNLOCKED(numToWake); lh.unlock(); return ret; } bool TaskQueue::fetchNextTask(ExecutorThread &thread, bool toSleep) { EventuallyPersistentEngine *epe = ObjectRegistry::onSwitchThread(NULL, true); bool rv = _fetchNextTask(thread, toSleep); ObjectRegistry::onSwitchThread(epe); return rv; } size_t TaskQueue::_moveReadyTasks(const ProcessClock::time_point tv) { if (!readyQueue.empty()) { return 0; } size_t numReady = 0; while (!futureQueue.empty()) { ExTask tid = futureQueue.top(); if (tid->getWaketime() <= tv) { futureQueue.pop(); readyQueue.push(tid); numReady++; } else { break; } } manager->addWork(numReady, queueType); // Current thread will pop one task, so wake up one less thread return numReady ? numReady - 1 : 0; } void TaskQueue::_checkPendingQueue(void) { if (!pendingQueue.empty()) { ExTask runnableTask = pendingQueue.front(); readyQueue.push(runnableTask); manager->addWork(1, queueType); pendingQueue.pop_front(); } } ProcessClock::time_point TaskQueue::_reschedule(ExTask &task) { LockHolder lh(mutex); futureQueue.push(task); return futureQueue.top()->getWaketime(); } ProcessClock::time_point TaskQueue::reschedule(ExTask &task) { EventuallyPersistentEngine *epe = ObjectRegistry::onSwitchThread(NULL, true); auto rv = _reschedule(task); ObjectRegistry::onSwitchThread(epe); return rv; } void TaskQueue::_schedule(ExTask &task) { TaskQueue* sleepQ; size_t numToWake = 1; { LockHolder lh(mutex); // If we are rescheduling a previously cancelled task, we should reset // the task state to the initial value of running. task->setState(TASK_RUNNING, TASK_DEAD); futureQueue.push(task); LOG(EXTENSION_LOG_DEBUG, "%s: Schedule a task \"%.*s\" id %" PRIu64, name.c_str(), int(task->getDescription().size()), task->getDescription().data(), uint64_t(task->getId())); sleepQ = manager->getSleepQ(queueType); _doWake_UNLOCKED(numToWake); } if (this != sleepQ) { sleepQ->doWake(numToWake); } } void TaskQueue::schedule(ExTask &task) { EventuallyPersistentEngine *epe = ObjectRegistry::onSwitchThread(NULL, true); _schedule(task); ObjectRegistry::onSwitchThread(epe); } void TaskQueue::_wake(ExTask &task) { const ProcessClock::time_point now = ProcessClock::now(); TaskQueue* sleepQ; // One task is being made ready regardless of the queue it's in. size_t readyCount = 1; { LockHolder lh(mutex); LOG(EXTENSION_LOG_DEBUG, "%s: Wake a task \"%.*s\" id %" PRIu64, name.c_str(), int(task->getDescription().size()), task->getDescription().data(), uint64_t(task->getId())); std::queue<ExTask> notReady; // Wake thread-count-serialized tasks too for (std::list<ExTask>::iterator it = pendingQueue.begin(); it != pendingQueue.end();) { ExTask tid = *it; if (tid->getId() == task->getId() || tid->isdead()) { notReady.push(tid); it = pendingQueue.erase(it); } else { it++; } } futureQueue.updateWaketime(task, now); task->setState(TASK_RUNNING, TASK_SNOOZED); while (!notReady.empty()) { ExTask tid = notReady.front(); if (tid->getWaketime() <= now || tid->isdead()) { readyCount++; } // MB-18453: Only push to the futureQueue futureQueue.push(tid); notReady.pop(); } _doWake_UNLOCKED(readyCount); sleepQ = manager->getSleepQ(queueType); } if (this != sleepQ) { sleepQ->doWake(readyCount); } } void TaskQueue::wake(ExTask &task) { EventuallyPersistentEngine *epe = ObjectRegistry::onSwitchThread(NULL, true); _wake(task); ObjectRegistry::onSwitchThread(epe); } const std::string TaskQueue::taskType2Str(task_type_t type) { switch (type) { case WRITER_TASK_IDX: return std::string("Writer"); case READER_TASK_IDX: return std::string("Reader"); case AUXIO_TASK_IDX: return std::string("AuxIO"); case NONIO_TASK_IDX: return std::string("NonIO"); default: return std::string("None"); } } <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : D.cpp * Author : Kazune Takahashi * Created : 6/14/2020, 2:15:35 AM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <climits> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; using ld = long double; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1'000'000'007LL}; // constexpr ll MOD{998'244'353LL}; // be careful constexpr ll MAX_SIZE{3'000'010LL}; // constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(Mint const &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(Mint const &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(Mint const &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(Mint const &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(Mint const &a) const { return Mint(*this) += a; } Mint operator-(Mint const &a) const { return Mint(*this) -= a; } Mint operator*(Mint const &a) const { return Mint(*this) *= a; } Mint operator/(Mint const &a) const { return Mint(*this) /= a; } bool operator<(Mint const &a) const { return x < a.x; } bool operator<=(Mint const &a) const { return x <= a.x; } bool operator>(Mint const &a) const { return x > a.x; } bool operator>=(Mint const &a) const { return x >= a.x; } bool operator==(Mint const &a) const { return x == a.x; } bool operator!=(Mint const &a) const { return !(*this == a); } Mint power(ll N) const { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i{2LL}; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i{1LL}; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- Infty ----- template <typename T> constexpr T Infty() { return numeric_limits<T>::max(); } template <typename T> constexpr T mInfty() { return numeric_limits<T>::min(); } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1'000'000'000'000'010LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- Solve ----- constexpr int D{12}; constexpr int M{100010}; struct Info { int value, weight; }; Info operator+(Info const &l, Info const &r) { return Info{l.value + r.value, l.weight + r.weight}; } class Solve { int N, Q; vector<int> V, W; vector<int> X, L; vector<vector<int>> DP; public: Solve() : V(1), W(1), X{}, L{}, DP(1 << D) { cin >> N; for (auto i{0}; i < N; ++i) { int x, y; cin >> x >> y; V.push_back(x); W.push_back(y); } cin >> Q; for (auto i{0}; i < Q; ++i) { int x, y; cin >> x >> y; X.push_back(x); L.push_back(y); } } void flush() { for (auto i{0}; i < min(N, 1 << D); ++i) { DP[i] = make_knapsack(i); } for (auto i{0}; i < Q; ++i) { #if DEBUG == 1 cerr << "i = " << i << endl; cerr << "X[" << i << "] = " << X[i] << endl; cerr << "L[" << i << "] = " << L[i] << endl; #endif cerr << calc_ans(X[i], L[i]) << endl; } } private: int calc_ans(int v, int l) { vector<Info> T{Info{0, 0}}; while (v >= 1 << D) { vector<Info> U; Info tmp{V[v], W[v]}; for (auto const &e : T) { U.push_back(tmp + e); } copy(U.begin(), U.end(), back_inserter(T)); v >>= 1; } int ans{0}; for (auto const &e : T) { if (e.weight > l) { continue; } ch_max(ans, DP[v][l - e.weight] + e.value); } return ans; } vector<int> make_knapsack(int v) { vector<int> dp(M, 0); while (v > 0) { for (auto i{M - 1}; i >= 0; --i) { if (int t{i + W[v]}; t < M) { ch_max(dp[t], dp[i] + V[v]); } } v >>= 1; } return dp; } }; // ----- main() ----- int main() { Solve solve; solve.flush(); } <commit_msg>tried D.cpp to 'D'<commit_after>#define DEBUG 1 /** * File : D.cpp * Author : Kazune Takahashi * Created : 6/14/2020, 2:15:35 AM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <climits> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; using ld = long double; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1'000'000'007LL}; // constexpr ll MOD{998'244'353LL}; // be careful constexpr ll MAX_SIZE{3'000'010LL}; // constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(Mint const &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(Mint const &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(Mint const &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(Mint const &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(Mint const &a) const { return Mint(*this) += a; } Mint operator-(Mint const &a) const { return Mint(*this) -= a; } Mint operator*(Mint const &a) const { return Mint(*this) *= a; } Mint operator/(Mint const &a) const { return Mint(*this) /= a; } bool operator<(Mint const &a) const { return x < a.x; } bool operator<=(Mint const &a) const { return x <= a.x; } bool operator>(Mint const &a) const { return x > a.x; } bool operator>=(Mint const &a) const { return x >= a.x; } bool operator==(Mint const &a) const { return x == a.x; } bool operator!=(Mint const &a) const { return !(*this == a); } Mint power(ll N) const { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i{2LL}; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i{1LL}; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- Infty ----- template <typename T> constexpr T Infty() { return numeric_limits<T>::max(); } template <typename T> constexpr T mInfty() { return numeric_limits<T>::min(); } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1'000'000'000'000'010LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- Solve ----- constexpr int D{12}; constexpr int M{100010}; struct Info { int value, weight; }; Info operator+(Info const &l, Info const &r) { return Info{l.value + r.value, l.weight + r.weight}; } class Solve { int N, Q; vector<int> V, W; vector<int> X, L; vector<vector<int>> DP; public: Solve() : V(1), W(1), X{}, L{}, DP(1 << D) { cin >> N; for (auto i{0}; i < N; ++i) { int x, y; cin >> x >> y; V.push_back(x); W.push_back(y); } cin >> Q; for (auto i{0}; i < Q; ++i) { int x, y; cin >> x >> y; X.push_back(x); L.push_back(y); } } void flush() { for (auto i{0}; i < min(N, 1 << D); ++i) { DP[i] = make_knapsack(i); } for (auto i{0}; i < Q; ++i) { #if DEBUG == 1 cerr << "i = " << i << endl; cerr << "X[" << i << "] = " << X[i] << endl; cerr << "L[" << i << "] = " << L[i] << endl; #endif cout << calc_ans(X[i], L[i]) << endl; } } private: int calc_ans(int v, int l) { vector<Info> T{Info{0, 0}}; while (v >= 1 << D) { vector<Info> U; Info tmp{V[v], W[v]}; for (auto const &e : T) { U.push_back(tmp + e); } copy(U.begin(), U.end(), back_inserter(T)); v >>= 1; } int ans{0}; for (auto const &e : T) { if (e.weight > l) { continue; } ch_max(ans, DP[v][l - e.weight] + e.value); } return ans; } vector<int> make_knapsack(int v) { vector<int> dp(M, 0); while (v > 0) { for (auto i{M - 1}; i >= 0; --i) { if (int t{i + W[v]}; t < M) { ch_max(dp[t], dp[i] + V[v]); } } v >>= 1; } return dp; } }; // ----- main() ----- int main() { Solve solve; solve.flush(); } <|endoftext|>
<commit_before><commit_msg>This can be const.<commit_after><|endoftext|>
<commit_before><commit_msg>bail out early if maTableColumnNames.empty()<commit_after><|endoftext|>
<commit_before>/*------------------------------------------------------------------------ * Vulkan Conformance Tests * ------------------------ * * Copyright (c) 2015 The Khronos Group Inc. * Copyright (c) 2015 Samsung Electronics Co., Ltd. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and/or associated documentation files (the * "Materials"), to deal in the Materials without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Materials, and to * permit persons to whom the Materials are furnished to do so, subject to * the following conditions: * * The above copyright notice(s) and this permission notice shall be included * in all copies or substantial portions of the Materials. * * The Materials are Confidential Information as defined by the * Khronos Membership Agreement until designated non-confidential by Khronos, * at which point this condition clause shall be removed. * * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. * *//*! * \file * \brief Vulkan Buffers Tests *//*--------------------------------------------------------------------*/ #include "vktApiBufferTests.hpp" #include "deStringUtil.hpp" #include "gluVarType.hpp" #include "tcuTestLog.hpp" #include "vkPrograms.hpp" #include "vkQueryUtil.hpp" #include "vktTestCase.hpp" namespace vkt { using namespace vk; namespace api { namespace { struct BufferCaseParameters { VkBufferUsageFlags usage; VkBufferCreateFlags flags; VkSharingMode sharingMode; }; class BufferTestInstance : public TestInstance { public: BufferTestInstance (Context& ctx, BufferCaseParameters testCase) : TestInstance (ctx) , m_testCase (testCase) {} virtual tcu::TestStatus iterate (void); tcu::TestStatus bufferCreateAndAllocTest (VkDeviceSize size); private: BufferCaseParameters m_testCase; }; class BuffersTestCase : public TestCase { public: BuffersTestCase (tcu::TestContext& testCtx, const std::string& name, const std::string& description, BufferCaseParameters testCase) : TestCase(testCtx, name, description) , m_testCase(testCase) {} virtual ~BuffersTestCase (void) {} virtual TestInstance* createInstance (Context& ctx) const { tcu::TestLog& log = m_testCtx.getLog(); log << tcu::TestLog::Message << getBufferUsageFlagsStr(m_testCase.usage) << tcu::TestLog::EndMessage; return new BufferTestInstance(ctx, m_testCase); } private: BufferCaseParameters m_testCase; }; tcu::TestStatus BufferTestInstance::bufferCreateAndAllocTest (VkDeviceSize size) { const VkDevice vkDevice = m_context.getDevice(); const DeviceInterface& vk = m_context.getDeviceInterface(); VkBuffer testBuffer; VkMemoryRequirements memReqs; VkDeviceMemory memory; const deUint32 queueFamilyIndex = m_context.getUniversalQueueFamilyIndex(); // Create buffer { const VkBufferCreateInfo bufferParams = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, DE_NULL, m_testCase.flags, size, m_testCase.usage, m_testCase.sharingMode, 1u, // deUint32 queueFamilyCount; &queueFamilyIndex, }; if (vk.createBuffer(vkDevice, &bufferParams, (const VkAllocationCallbacks*)DE_NULL, &testBuffer) != VK_SUCCESS) return tcu::TestStatus::fail("Buffer creation failed! (requested memory size: " + de::toString(size) + ")"); vk.getBufferMemoryRequirements(vkDevice, testBuffer, &memReqs); if (size > memReqs.size) { std::ostringstream errorMsg; errorMsg << "Requied memory size (" << memReqs.size << " bytes) smaller than the buffer's size (" << size << " bytes)!"; return tcu::TestStatus::fail(errorMsg.str()); } } // Allocate and bind memory { const VkMemoryAllocateInfo memAlloc = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, NULL, memReqs.size, 0 // deUint32 memoryTypeIndex }; if (vk.allocateMemory(vkDevice, &memAlloc, (const VkAllocationCallbacks*)DE_NULL, &memory) != VK_SUCCESS) return tcu::TestStatus::fail("Alloc memory failed! (requested memory size: " + de::toString(size) + ")"); if ((m_testCase.flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT) || (m_testCase.flags & VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT) || (m_testCase.flags & VK_BUFFER_CREATE_SPARSE_ALIASED_BIT)) { VkQueue queue = 0; vk.getDeviceQueue(vkDevice, queueFamilyIndex, 0, &queue); const VkSparseMemoryBind sparseMemoryBind = { 0, // VkDeviceSize resourceOffset; memReqs.size, // VkDeviceSize size; memory, // VkDeviceMemory memory; 0, // VkDeviceSize memoryOffset; 0 // VkSparseMemoryBindFlags flags; }; const VkSparseBufferMemoryBindInfo sparseBufferMemoryBindInfo = { testBuffer, // VkBuffer buffer; 1u, // deUint32 bindCount; &sparseMemoryBind // const VkSparseMemoryBind* pBinds; }; const VkBindSparseInfo bindSparseInfo = { VK_STRUCTURE_TYPE_BIND_SPARSE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0, // deUint32 waitSemaphoreCount; DE_NULL, // const VkSemaphore* pWaitSemaphores; 1u, // deUint32 bufferBindCount; &sparseBufferMemoryBindInfo, // const VkSparseBufferMemoryBindInfo* pBufferBinds; 0, // deUint32 imageOpaqueBindCount; DE_NULL, // const VkSparseImageOpaqueMemoryBindInfo* pImageOpaqueBinds; 0, // deUint32 imageBindCount; DE_NULL, // const VkSparseImageMemoryBindInfo* pImageBinds; 0, // deUint32 signalSemaphoreCount; DE_NULL, // const VkSemaphore* pSignalSemaphores; }; if (vk.queueBindSparse(queue, 1, &bindSparseInfo, DE_NULL) != VK_SUCCESS) return tcu::TestStatus::fail("Bind sparse buffer memory failed! (requested memory size: " + de::toString(size) + ")"); } else if (vk.bindBufferMemory(vkDevice, testBuffer, memory, 0) != VK_SUCCESS) return tcu::TestStatus::fail("Bind buffer memory failed! (requested memory size: " + de::toString(size) + ")"); } vk.freeMemory(vkDevice, memory, (const VkAllocationCallbacks*)DE_NULL); vk.destroyBuffer(vkDevice, testBuffer, (const VkAllocationCallbacks*)DE_NULL); return tcu::TestStatus::pass("Buffer test"); } tcu::TestStatus BufferTestInstance::iterate (void) { const VkPhysicalDeviceFeatures& physicalDeviceFeatures = m_context.getDeviceFeatures(); if ((m_testCase.flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT ) && !physicalDeviceFeatures.sparseBinding) return tcu::TestStatus::pass("Sparse bindings feature is not enabled"); if ((m_testCase.flags & VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT ) && !physicalDeviceFeatures.sparseResidencyBuffer) return tcu::TestStatus::pass("Sparse buffer residency feature is not enabled"); if ((m_testCase.flags & VK_BUFFER_CREATE_SPARSE_ALIASED_BIT ) && !physicalDeviceFeatures.sparseResidencyAliased) return tcu::TestStatus::pass("Sparse aliased residency feature is not enabled"); const VkDeviceSize testSizes[] = { 1, 1181, 15991, 16384 }; tcu::TestStatus testStatus = tcu::TestStatus::pass("Buffer test"); for (int i = 0; i < DE_LENGTH_OF_ARRAY(testSizes); i++) { if ((testStatus = bufferCreateAndAllocTest(testSizes[i])).getCode() != QP_TEST_RESULT_PASS) return testStatus; } if (m_testCase.usage & (VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT)) { const VkPhysicalDevice vkPhysicalDevice = m_context.getPhysicalDevice(); const InstanceInterface& vkInstance = m_context.getInstanceInterface(); const VkPhysicalDeviceMemoryProperties memoryProperties = getPhysicalDeviceMemoryProperties(vkInstance, vkPhysicalDevice); VkPhysicalDeviceProperties props; vkInstance.getPhysicalDeviceProperties(vkPhysicalDevice, &props); const VkDeviceSize maxTestBufferSize = de::min((VkDeviceSize) props.limits.maxTexelBufferElements, memoryProperties.memoryHeaps[memoryProperties.memoryTypes[0].heapIndex].size / 16); testStatus = bufferCreateAndAllocTest(maxTestBufferSize); } return testStatus; } } // anonymous tcu::TestCaseGroup* createBufferTests (tcu::TestContext& testCtx) { const VkBufferUsageFlags bufferUsageModes[] = { VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT, VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT }; const VkBufferCreateFlags bufferCreateFlags[] = { VK_BUFFER_CREATE_SPARSE_BINDING_BIT, VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT, VK_BUFFER_CREATE_SPARSE_ALIASED_BIT }; de::MovePtr<tcu::TestCaseGroup> buffersTests (new tcu::TestCaseGroup(testCtx, "buffer", "Buffer Tests")); deUint32 numberOfBufferUsageFlags = DE_LENGTH_OF_ARRAY(bufferUsageModes); deUint32 numberOfBufferCreateFlags = DE_LENGTH_OF_ARRAY(bufferCreateFlags); deUint32 maximumValueOfBufferUsageFlags = (1 << (numberOfBufferUsageFlags - 1)) - 1; deUint32 maximumValueOfBufferCreateFlags = (1 << (numberOfBufferCreateFlags)) - 1; for (deUint32 combinedBufferCreateFlags = 0; combinedBufferCreateFlags <= maximumValueOfBufferCreateFlags; combinedBufferCreateFlags++) { for (deUint32 combinedBufferUsageFlags = 1; combinedBufferUsageFlags <= maximumValueOfBufferUsageFlags; combinedBufferUsageFlags++) { BufferCaseParameters testParams = { combinedBufferUsageFlags, combinedBufferCreateFlags, VK_SHARING_MODE_EXCLUSIVE }; std::ostringstream testName; std::ostringstream testDescription; testName << "createBuffer_" << combinedBufferUsageFlags << "_" << combinedBufferCreateFlags; testDescription << "vkCreateBuffer test " << combinedBufferUsageFlags << " " << combinedBufferCreateFlags; buffersTests->addChild(new BuffersTestCase(testCtx, testName.str(), testDescription.str(), testParams)); } } return buffersTests.release(); } } // api } // vk <commit_msg>Fixing buffer test results if spares memory is not suppoerted.<commit_after>/*------------------------------------------------------------------------ * Vulkan Conformance Tests * ------------------------ * * Copyright (c) 2015 The Khronos Group Inc. * Copyright (c) 2015 Samsung Electronics Co., Ltd. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and/or associated documentation files (the * "Materials"), to deal in the Materials without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Materials, and to * permit persons to whom the Materials are furnished to do so, subject to * the following conditions: * * The above copyright notice(s) and this permission notice shall be included * in all copies or substantial portions of the Materials. * * The Materials are Confidential Information as defined by the * Khronos Membership Agreement until designated non-confidential by Khronos, * at which point this condition clause shall be removed. * * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. * *//*! * \file * \brief Vulkan Buffers Tests *//*--------------------------------------------------------------------*/ #include "vktApiBufferTests.hpp" #include "deStringUtil.hpp" #include "gluVarType.hpp" #include "tcuTestLog.hpp" #include "vkPrograms.hpp" #include "vkQueryUtil.hpp" #include "vktTestCase.hpp" namespace vkt { using namespace vk; namespace api { namespace { struct BufferCaseParameters { VkBufferUsageFlags usage; VkBufferCreateFlags flags; VkSharingMode sharingMode; }; class BufferTestInstance : public TestInstance { public: BufferTestInstance (Context& ctx, BufferCaseParameters testCase) : TestInstance (ctx) , m_testCase (testCase) {} virtual tcu::TestStatus iterate (void); tcu::TestStatus bufferCreateAndAllocTest (VkDeviceSize size); private: BufferCaseParameters m_testCase; }; class BuffersTestCase : public TestCase { public: BuffersTestCase (tcu::TestContext& testCtx, const std::string& name, const std::string& description, BufferCaseParameters testCase) : TestCase(testCtx, name, description) , m_testCase(testCase) {} virtual ~BuffersTestCase (void) {} virtual TestInstance* createInstance (Context& ctx) const { tcu::TestLog& log = m_testCtx.getLog(); log << tcu::TestLog::Message << getBufferUsageFlagsStr(m_testCase.usage) << tcu::TestLog::EndMessage; return new BufferTestInstance(ctx, m_testCase); } private: BufferCaseParameters m_testCase; }; tcu::TestStatus BufferTestInstance::bufferCreateAndAllocTest (VkDeviceSize size) { const VkDevice vkDevice = m_context.getDevice(); const DeviceInterface& vk = m_context.getDeviceInterface(); VkBuffer testBuffer; VkMemoryRequirements memReqs; VkDeviceMemory memory; const deUint32 queueFamilyIndex = m_context.getUniversalQueueFamilyIndex(); // Create buffer { const VkBufferCreateInfo bufferParams = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, DE_NULL, m_testCase.flags, size, m_testCase.usage, m_testCase.sharingMode, 1u, // deUint32 queueFamilyCount; &queueFamilyIndex, }; if (vk.createBuffer(vkDevice, &bufferParams, (const VkAllocationCallbacks*)DE_NULL, &testBuffer) != VK_SUCCESS) return tcu::TestStatus::fail("Buffer creation failed! (requested memory size: " + de::toString(size) + ")"); vk.getBufferMemoryRequirements(vkDevice, testBuffer, &memReqs); if (size > memReqs.size) { std::ostringstream errorMsg; errorMsg << "Requied memory size (" << memReqs.size << " bytes) smaller than the buffer's size (" << size << " bytes)!"; return tcu::TestStatus::fail(errorMsg.str()); } } // Allocate and bind memory { const VkMemoryAllocateInfo memAlloc = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, NULL, memReqs.size, 0 // deUint32 memoryTypeIndex }; if (vk.allocateMemory(vkDevice, &memAlloc, (const VkAllocationCallbacks*)DE_NULL, &memory) != VK_SUCCESS) return tcu::TestStatus::fail("Alloc memory failed! (requested memory size: " + de::toString(size) + ")"); if ((m_testCase.flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT) || (m_testCase.flags & VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT) || (m_testCase.flags & VK_BUFFER_CREATE_SPARSE_ALIASED_BIT)) { VkQueue queue = 0; vk.getDeviceQueue(vkDevice, queueFamilyIndex, 0, &queue); const VkSparseMemoryBind sparseMemoryBind = { 0, // VkDeviceSize resourceOffset; memReqs.size, // VkDeviceSize size; memory, // VkDeviceMemory memory; 0, // VkDeviceSize memoryOffset; 0 // VkSparseMemoryBindFlags flags; }; const VkSparseBufferMemoryBindInfo sparseBufferMemoryBindInfo = { testBuffer, // VkBuffer buffer; 1u, // deUint32 bindCount; &sparseMemoryBind // const VkSparseMemoryBind* pBinds; }; const VkBindSparseInfo bindSparseInfo = { VK_STRUCTURE_TYPE_BIND_SPARSE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0, // deUint32 waitSemaphoreCount; DE_NULL, // const VkSemaphore* pWaitSemaphores; 1u, // deUint32 bufferBindCount; &sparseBufferMemoryBindInfo, // const VkSparseBufferMemoryBindInfo* pBufferBinds; 0, // deUint32 imageOpaqueBindCount; DE_NULL, // const VkSparseImageOpaqueMemoryBindInfo* pImageOpaqueBinds; 0, // deUint32 imageBindCount; DE_NULL, // const VkSparseImageMemoryBindInfo* pImageBinds; 0, // deUint32 signalSemaphoreCount; DE_NULL, // const VkSemaphore* pSignalSemaphores; }; if (vk.queueBindSparse(queue, 1, &bindSparseInfo, DE_NULL) != VK_SUCCESS) return tcu::TestStatus::fail("Bind sparse buffer memory failed! (requested memory size: " + de::toString(size) + ")"); } else if (vk.bindBufferMemory(vkDevice, testBuffer, memory, 0) != VK_SUCCESS) return tcu::TestStatus::fail("Bind buffer memory failed! (requested memory size: " + de::toString(size) + ")"); } vk.freeMemory(vkDevice, memory, (const VkAllocationCallbacks*)DE_NULL); vk.destroyBuffer(vkDevice, testBuffer, (const VkAllocationCallbacks*)DE_NULL); return tcu::TestStatus::pass("Buffer test"); } tcu::TestStatus BufferTestInstance::iterate (void) { const VkPhysicalDeviceFeatures& physicalDeviceFeatures = m_context.getDeviceFeatures(); if ((m_testCase.flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT ) && !physicalDeviceFeatures.sparseBinding) TCU_THROW(NotSupportedError, "Sparse bindings feature is not supported"); if ((m_testCase.flags & VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT ) && !physicalDeviceFeatures.sparseResidencyBuffer) TCU_THROW(NotSupportedError, "Sparse buffer residency feature is not supported"); if ((m_testCase.flags & VK_BUFFER_CREATE_SPARSE_ALIASED_BIT ) && !physicalDeviceFeatures.sparseResidencyAliased) TCU_THROW(NotSupportedError, "Sparse aliased residency feature is not supported"); const VkDeviceSize testSizes[] = { 1, 1181, 15991, 16384 }; tcu::TestStatus testStatus = tcu::TestStatus::pass("Buffer test"); for (int i = 0; i < DE_LENGTH_OF_ARRAY(testSizes); i++) { if ((testStatus = bufferCreateAndAllocTest(testSizes[i])).getCode() != QP_TEST_RESULT_PASS) return testStatus; } if (m_testCase.usage & (VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT)) { const VkPhysicalDevice vkPhysicalDevice = m_context.getPhysicalDevice(); const InstanceInterface& vkInstance = m_context.getInstanceInterface(); const VkPhysicalDeviceMemoryProperties memoryProperties = getPhysicalDeviceMemoryProperties(vkInstance, vkPhysicalDevice); VkPhysicalDeviceProperties props; vkInstance.getPhysicalDeviceProperties(vkPhysicalDevice, &props); const VkDeviceSize maxTestBufferSize = de::min((VkDeviceSize) props.limits.maxTexelBufferElements, memoryProperties.memoryHeaps[memoryProperties.memoryTypes[0].heapIndex].size / 16); testStatus = bufferCreateAndAllocTest(maxTestBufferSize); } return testStatus; } } // anonymous tcu::TestCaseGroup* createBufferTests (tcu::TestContext& testCtx) { const VkBufferUsageFlags bufferUsageModes[] = { VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT, VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_BUFFER_USAGE_INDEX_BUFFER_BIT, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT }; const VkBufferCreateFlags bufferCreateFlags[] = { VK_BUFFER_CREATE_SPARSE_BINDING_BIT, VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT, VK_BUFFER_CREATE_SPARSE_ALIASED_BIT }; de::MovePtr<tcu::TestCaseGroup> buffersTests (new tcu::TestCaseGroup(testCtx, "buffer", "Buffer Tests")); deUint32 numberOfBufferUsageFlags = DE_LENGTH_OF_ARRAY(bufferUsageModes); deUint32 numberOfBufferCreateFlags = DE_LENGTH_OF_ARRAY(bufferCreateFlags); deUint32 maximumValueOfBufferUsageFlags = (1 << (numberOfBufferUsageFlags - 1)) - 1; deUint32 maximumValueOfBufferCreateFlags = (1 << (numberOfBufferCreateFlags)) - 1; for (deUint32 combinedBufferCreateFlags = 0; combinedBufferCreateFlags <= maximumValueOfBufferCreateFlags; combinedBufferCreateFlags++) { for (deUint32 combinedBufferUsageFlags = 1; combinedBufferUsageFlags <= maximumValueOfBufferUsageFlags; combinedBufferUsageFlags++) { BufferCaseParameters testParams = { combinedBufferUsageFlags, combinedBufferCreateFlags, VK_SHARING_MODE_EXCLUSIVE }; std::ostringstream testName; std::ostringstream testDescription; testName << "createBuffer_" << combinedBufferUsageFlags << "_" << combinedBufferCreateFlags; testDescription << "vkCreateBuffer test " << combinedBufferUsageFlags << " " << combinedBufferCreateFlags; buffersTests->addChild(new BuffersTestCase(testCtx, testName.str(), testDescription.str(), testParams)); } } return buffersTests.release(); } } // api } // vk <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2009-2014 DreamWorks Animation LLC. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of DreamWorks Animation nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// #include "ImfSimd.h" #include "ImfSystemSpecific.h" #include "ImfNamespace.h" OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER namespace { #if defined(IMF_HAVE_SSE2) && defined(__GNUC__) // Helper functions for gcc + SSE enabled void cpuid(int n, int &eax, int &ebx, int &ecx, int &edx) { __asm__ __volatile__ ( "cpuid" : /* Output */ "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx) : /* Input */ "a"(n) : /* Clobber */); } void xgetbv(int n, int &eax, int &edx) { // Some compiler versions might not recognize "xgetbv" as a mnemonic. // Might end up needing to use ".byte 0x0f, 0x01, 0xd0" instead. __asm__ __volatile__ ( "xgetbv" : /* Output */ "=a"(eax), "=d"(edx) : /* Input */ "c"(n) : /* Clobber */); } #else // IMF_HAVE_SSE2 && __GNUC__ // Helper functions for generic compiler - all disabled void cpuid(int n, int &eax, int &ebx, int &ecx, int &edx) { eax = ebx = ecx = edx = 0; } void xgetbv(int n, int &eax, int &edx) { eax = edx = 0; } #endif // IMF_HAVE_SSE2 && __GNUC__ } // namespace CpuId::CpuId(): sse2(false), sse3(false), ssse3(false), sse4_1(false), sse4_2(false), avx(false), f16c(false) { bool osxsave = false; int max = 0; int eax, ebx, ecx, edx; cpuid(0, max, ebx, ecx, edx); if (max > 0) { cpuid(1, eax, ebx, ecx, edx); sse2 = ( edx & (1<<26) ); sse3 = ( ecx & (1<< 0) ); ssse3 = ( ecx & (1<< 9) ); sse4_1 = ( ecx & (1<<19) ); sse4_2 = ( ecx & (1<<20) ); osxsave = ( ecx & (1<<27) ); avx = ( ecx & (1<<28) ); f16c = ( ecx & (1<<29) ); if (!osxsave) { avx = f16c = false; } else { xgetbv(0, eax, edx); // eax bit 1 - SSE managed, bit 2 - AVX managed if ((eax & 6) != 6) { avx = f16c = false; } } } } OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_EXIT <commit_msg>Updated indentation style to match current practice.<commit_after>/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2009-2014 DreamWorks Animation LLC. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of DreamWorks Animation nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// #include "ImfSimd.h" #include "ImfSystemSpecific.h" #include "ImfNamespace.h" OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER namespace { #if defined(IMF_HAVE_SSE2) && defined(__GNUC__) // Helper functions for gcc + SSE enabled void cpuid(int n, int &eax, int &ebx, int &ecx, int &edx) { __asm__ __volatile__ ( "cpuid" : /* Output */ "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx) : /* Input */ "a"(n) : /* Clobber */); } void xgetbv(int n, int &eax, int &edx) { // Some compiler versions might not recognize "xgetbv" as a mnemonic. // Might end up needing to use ".byte 0x0f, 0x01, 0xd0" instead. __asm__ __volatile__ ( "xgetbv" : /* Output */ "=a"(eax), "=d"(edx) : /* Input */ "c"(n) : /* Clobber */); } #else // IMF_HAVE_SSE2 && __GNUC__ // Helper functions for generic compiler - all disabled void cpuid(int n, int &eax, int &ebx, int &ecx, int &edx) { eax = ebx = ecx = edx = 0; } void xgetbv(int n, int &eax, int &edx) { eax = edx = 0; } #endif // IMF_HAVE_SSE2 && __GNUC__ } // namespace CpuId::CpuId(): sse2(false), sse3(false), ssse3(false), sse4_1(false), sse4_2(false), avx(false), f16c(false) { bool osxsave = false; int max = 0; int eax, ebx, ecx, edx; cpuid(0, max, ebx, ecx, edx); if (max > 0) { cpuid(1, eax, ebx, ecx, edx); sse2 = ( edx & (1<<26) ); sse3 = ( ecx & (1<< 0) ); ssse3 = ( ecx & (1<< 9) ); sse4_1 = ( ecx & (1<<19) ); sse4_2 = ( ecx & (1<<20) ); osxsave = ( ecx & (1<<27) ); avx = ( ecx & (1<<28) ); f16c = ( ecx & (1<<29) ); if (!osxsave) { avx = f16c = false; } else { xgetbv(0, eax, edx); // eax bit 1 - SSE managed, bit 2 - AVX managed if ((eax & 6) != 6) { avx = f16c = false; } } } } OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_EXIT <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/speech/speech_input_manager.h" #include <map> #include <string> #include "app/l10n_util.h" #include "base/command_line.h" #include "base/lock.h" #include "base/ref_counted.h" #include "base/lazy_instance.h" #include "base/threading/thread_restrictions.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_thread.h" #include "chrome/common/chrome_switches.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/speech/speech_input_bubble_controller.h" #include "chrome/browser/speech/speech_recognizer.h" #include "chrome/browser/tab_contents/infobar_delegate.h" #include "chrome/browser/tab_contents/tab_util.h" #include "chrome/common/pref_names.h" #include "grit/generated_resources.h" #include "media/audio/audio_manager.h" #if defined(OS_WIN) #include "chrome/browser/browser_process.h" #include "chrome/installer/util/wmi.h" #endif namespace { // Asynchronously fetches the PC and audio hardware/driver info on windows if // the user has opted into UMA. This information is sent with speech input // requests to the server for identifying and improving quality issues with // specific device configurations. class HardwareInfo : public base::RefCountedThreadSafe<HardwareInfo> { public: HardwareInfo() {} #if defined(OS_WIN) void Refresh() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // UMA opt-in can be checked only from the UI thread, so switch to that. BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &HardwareInfo::CheckUMAAndGetHardwareInfo)); } void CheckUMAAndGetHardwareInfo() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (g_browser_process->local_state()->GetBoolean( prefs::kMetricsReportingEnabled)) { // Access potentially slow OS calls from the FILE thread. BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, NewRunnableMethod(this, &HardwareInfo::GetHardwareInfo)); } } void GetHardwareInfo() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); AutoLock lock(lock_); value_ = UTF16ToUTF8( installer::WMIComputerSystem::GetModel() + L"|" + AudioManager::GetAudioManager()->GetAudioInputDeviceModel()); } std::string value() { AutoLock lock(lock_); return value_; } private: Lock lock_; std::string value_; #else // defined(OS_WIN) void Refresh() {} std::string value() { return std::string(); } #endif // defined(OS_WIN) DISALLOW_COPY_AND_ASSIGN(HardwareInfo); }; } // namespace namespace speech_input { class SpeechInputManagerImpl : public SpeechInputManager, public SpeechInputBubbleControllerDelegate, public SpeechRecognizerDelegate { public: // SpeechInputManager methods. virtual void StartRecognition(SpeechInputManagerDelegate* delegate, int caller_id, int render_process_id, int render_view_id, const gfx::Rect& element_rect, const std::string& language, const std::string& grammar); virtual void CancelRecognition(int caller_id); virtual void StopRecording(int caller_id); // SpeechRecognizer::Delegate methods. virtual void SetRecognitionResult(int caller_id, bool error, const SpeechInputResultArray& result); virtual void DidCompleteRecording(int caller_id); virtual void DidCompleteRecognition(int caller_id); virtual void OnRecognizerError(int caller_id, SpeechRecognizer::ErrorCode error); virtual void DidCompleteEnvironmentEstimation(int caller_id); virtual void SetInputVolume(int caller_id, float volume); // SpeechInputBubbleController::Delegate methods. virtual void InfoBubbleButtonClicked(int caller_id, SpeechInputBubble::Button button); virtual void InfoBubbleFocusChanged(int caller_id); private: struct SpeechInputRequest { SpeechInputManagerDelegate* delegate; scoped_refptr<SpeechRecognizer> recognizer; bool is_active; // Set to true when recording or recognition is going on. }; // Private constructor to enforce singleton. friend struct base::DefaultLazyInstanceTraits<SpeechInputManagerImpl>; SpeechInputManagerImpl(); virtual ~SpeechInputManagerImpl(); bool HasPendingRequest(int caller_id) const; SpeechInputManagerDelegate* GetDelegate(int caller_id) const; void CancelRecognitionAndInformDelegate(int caller_id); // Starts/restarts recognition for an existing request. void StartRecognitionForRequest(int caller_id); SpeechInputManagerDelegate* delegate_; typedef std::map<int, SpeechInputRequest> SpeechRecognizerMap; SpeechRecognizerMap requests_; int recording_caller_id_; scoped_refptr<SpeechInputBubbleController> bubble_controller_; scoped_refptr<HardwareInfo> hardware_info_; }; static ::base::LazyInstance<SpeechInputManagerImpl> g_speech_input_manager_impl( base::LINKER_INITIALIZED); SpeechInputManager* SpeechInputManager::Get() { return g_speech_input_manager_impl.Pointer(); } bool SpeechInputManager::IsFeatureEnabled() { bool enabled = true; const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kDisableSpeechInput)) { enabled = false; #if defined(GOOGLE_CHROME_BUILD) } else if (!command_line.HasSwitch(switches::kEnableSpeechInput)) { // We need to evaluate whether IO is OK here. http://crbug.com/63335. base::ThreadRestrictions::ScopedAllowIO allow_io; // Official Chrome builds have speech input enabled by default only in the // dev channel. std::string channel = platform_util::GetVersionStringModifier(); enabled = (channel == "dev"); #endif } return enabled; } SpeechInputManagerImpl::SpeechInputManagerImpl() : recording_caller_id_(0), bubble_controller_(new SpeechInputBubbleController( ALLOW_THIS_IN_INITIALIZER_LIST(this))) { } SpeechInputManagerImpl::~SpeechInputManagerImpl() { while (requests_.begin() != requests_.end()) CancelRecognition(requests_.begin()->first); } bool SpeechInputManagerImpl::HasPendingRequest(int caller_id) const { return requests_.find(caller_id) != requests_.end(); } SpeechInputManagerDelegate* SpeechInputManagerImpl::GetDelegate( int caller_id) const { return requests_.find(caller_id)->second.delegate; } void SpeechInputManagerImpl::StartRecognition( SpeechInputManagerDelegate* delegate, int caller_id, int render_process_id, int render_view_id, const gfx::Rect& element_rect, const std::string& language, const std::string& grammar) { DCHECK(!HasPendingRequest(caller_id)); bubble_controller_->CreateBubble(caller_id, render_process_id, render_view_id, element_rect); if (!hardware_info_.get()) { hardware_info_ = new HardwareInfo(); // Since hardware info is optional with speech input requests, we start an // asynchronous fetch here and move on with recording audio. This first // speech input request would send an empty string for hardware info and // subsequent requests may have the hardware info available if the fetch // completed before them. This way we don't end up stalling the user with // a long wait and disk seeks when they click on a UI element and start // speaking. hardware_info_->Refresh(); } SpeechInputRequest* request = &requests_[caller_id]; request->delegate = delegate; request->recognizer = new SpeechRecognizer(this, caller_id, language, grammar, hardware_info_->value()); request->is_active = false; StartRecognitionForRequest(caller_id); } void SpeechInputManagerImpl::StartRecognitionForRequest(int caller_id) { DCHECK(HasPendingRequest(caller_id)); // If we are currently recording audio for another caller, abort that cleanly. if (recording_caller_id_) CancelRecognitionAndInformDelegate(recording_caller_id_); if (!AudioManager::GetAudioManager()->HasAudioInputDevices()) { bubble_controller_->SetBubbleMessage( caller_id, l10n_util::GetStringUTF16(IDS_SPEECH_INPUT_NO_MIC)); } else { recording_caller_id_ = caller_id; requests_[caller_id].is_active = true; requests_[caller_id].recognizer->StartRecording(); } } void SpeechInputManagerImpl::CancelRecognition(int caller_id) { DCHECK(HasPendingRequest(caller_id)); if (requests_[caller_id].is_active) requests_[caller_id].recognizer->CancelRecognition(); requests_.erase(caller_id); if (recording_caller_id_ == caller_id) recording_caller_id_ = 0; bubble_controller_->CloseBubble(caller_id); } void SpeechInputManagerImpl::StopRecording(int caller_id) { DCHECK(HasPendingRequest(caller_id)); requests_[caller_id].recognizer->StopRecording(); } void SpeechInputManagerImpl::SetRecognitionResult( int caller_id, bool error, const SpeechInputResultArray& result) { DCHECK(HasPendingRequest(caller_id)); GetDelegate(caller_id)->SetRecognitionResult(caller_id, result); } void SpeechInputManagerImpl::DidCompleteRecording(int caller_id) { DCHECK(recording_caller_id_ == caller_id); DCHECK(HasPendingRequest(caller_id)); recording_caller_id_ = 0; GetDelegate(caller_id)->DidCompleteRecording(caller_id); bubble_controller_->SetBubbleRecognizingMode(caller_id); } void SpeechInputManagerImpl::DidCompleteRecognition(int caller_id) { GetDelegate(caller_id)->DidCompleteRecognition(caller_id); requests_.erase(caller_id); bubble_controller_->CloseBubble(caller_id); } void SpeechInputManagerImpl::OnRecognizerError( int caller_id, SpeechRecognizer::ErrorCode error) { if (caller_id == recording_caller_id_) recording_caller_id_ = 0; requests_[caller_id].is_active = false; int message_id; switch (error) { case SpeechRecognizer::RECOGNIZER_ERROR_CAPTURE: message_id = IDS_SPEECH_INPUT_ERROR; break; case SpeechRecognizer::RECOGNIZER_ERROR_NO_SPEECH: message_id = IDS_SPEECH_INPUT_NO_SPEECH; break; case SpeechRecognizer::RECOGNIZER_ERROR_NO_RESULTS: message_id = IDS_SPEECH_INPUT_NO_RESULTS; break; default: NOTREACHED() << "unknown error " << error; return; } bubble_controller_->SetBubbleMessage(caller_id, l10n_util::GetStringUTF16(message_id)); } void SpeechInputManagerImpl::DidCompleteEnvironmentEstimation(int caller_id) { DCHECK(HasPendingRequest(caller_id)); DCHECK(recording_caller_id_ == caller_id); // Speech recognizer has gathered enough background audio so we can ask the // user to start speaking. bubble_controller_->SetBubbleRecordingMode(caller_id); } void SpeechInputManagerImpl::SetInputVolume(int caller_id, float volume) { DCHECK(HasPendingRequest(caller_id)); DCHECK_EQ(recording_caller_id_, caller_id); bubble_controller_->SetBubbleInputVolume(caller_id, volume); } void SpeechInputManagerImpl::CancelRecognitionAndInformDelegate(int caller_id) { SpeechInputManagerDelegate* cur_delegate = GetDelegate(caller_id); CancelRecognition(caller_id); cur_delegate->DidCompleteRecording(caller_id); cur_delegate->DidCompleteRecognition(caller_id); } void SpeechInputManagerImpl::InfoBubbleButtonClicked( int caller_id, SpeechInputBubble::Button button) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // Ignore if the caller id was not in our active recognizers list because the // user might have clicked more than once, or recognition could have been // cancelled due to other reasons before the user click was processed. if (!HasPendingRequest(caller_id)) return; if (button == SpeechInputBubble::BUTTON_CANCEL) { CancelRecognitionAndInformDelegate(caller_id); } else if (button == SpeechInputBubble::BUTTON_TRY_AGAIN) { StartRecognitionForRequest(caller_id); } } void SpeechInputManagerImpl::InfoBubbleFocusChanged(int caller_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // Ignore if the caller id was not in our active recognizers list because the // user might have clicked more than once, or recognition could have been // ended due to other reasons before the user click was processed. if (HasPendingRequest(caller_id)) { // If this is an ongoing recording or if we were displaying an error message // to the user, abort it since user has switched focus. Otherwise // recognition has started and keep that going so user can start speaking to // another element while this gets the results in parallel. if (recording_caller_id_ == caller_id || !requests_[caller_id].is_active) { CancelRecognitionAndInformDelegate(caller_id); } } } } // namespace speech_input <commit_msg>Fix official chrome linux builder (missing include).<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/speech/speech_input_manager.h" #include <map> #include <string> #include "app/l10n_util.h" #include "base/command_line.h" #include "base/lazy_instance.h" #include "base/lock.h" #include "base/ref_counted.h" #include "base/threading/thread_restrictions.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_thread.h" #include "chrome/browser/platform_util.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/speech/speech_input_bubble_controller.h" #include "chrome/browser/speech/speech_recognizer.h" #include "chrome/browser/tab_contents/infobar_delegate.h" #include "chrome/browser/tab_contents/tab_util.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "grit/generated_resources.h" #include "media/audio/audio_manager.h" #if defined(OS_WIN) #include "chrome/browser/browser_process.h" #include "chrome/installer/util/wmi.h" #endif namespace { // Asynchronously fetches the PC and audio hardware/driver info on windows if // the user has opted into UMA. This information is sent with speech input // requests to the server for identifying and improving quality issues with // specific device configurations. class HardwareInfo : public base::RefCountedThreadSafe<HardwareInfo> { public: HardwareInfo() {} #if defined(OS_WIN) void Refresh() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // UMA opt-in can be checked only from the UI thread, so switch to that. BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, NewRunnableMethod(this, &HardwareInfo::CheckUMAAndGetHardwareInfo)); } void CheckUMAAndGetHardwareInfo() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (g_browser_process->local_state()->GetBoolean( prefs::kMetricsReportingEnabled)) { // Access potentially slow OS calls from the FILE thread. BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, NewRunnableMethod(this, &HardwareInfo::GetHardwareInfo)); } } void GetHardwareInfo() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); AutoLock lock(lock_); value_ = UTF16ToUTF8( installer::WMIComputerSystem::GetModel() + L"|" + AudioManager::GetAudioManager()->GetAudioInputDeviceModel()); } std::string value() { AutoLock lock(lock_); return value_; } private: Lock lock_; std::string value_; #else // defined(OS_WIN) void Refresh() {} std::string value() { return std::string(); } #endif // defined(OS_WIN) DISALLOW_COPY_AND_ASSIGN(HardwareInfo); }; } // namespace namespace speech_input { class SpeechInputManagerImpl : public SpeechInputManager, public SpeechInputBubbleControllerDelegate, public SpeechRecognizerDelegate { public: // SpeechInputManager methods. virtual void StartRecognition(SpeechInputManagerDelegate* delegate, int caller_id, int render_process_id, int render_view_id, const gfx::Rect& element_rect, const std::string& language, const std::string& grammar); virtual void CancelRecognition(int caller_id); virtual void StopRecording(int caller_id); // SpeechRecognizer::Delegate methods. virtual void SetRecognitionResult(int caller_id, bool error, const SpeechInputResultArray& result); virtual void DidCompleteRecording(int caller_id); virtual void DidCompleteRecognition(int caller_id); virtual void OnRecognizerError(int caller_id, SpeechRecognizer::ErrorCode error); virtual void DidCompleteEnvironmentEstimation(int caller_id); virtual void SetInputVolume(int caller_id, float volume); // SpeechInputBubbleController::Delegate methods. virtual void InfoBubbleButtonClicked(int caller_id, SpeechInputBubble::Button button); virtual void InfoBubbleFocusChanged(int caller_id); private: struct SpeechInputRequest { SpeechInputManagerDelegate* delegate; scoped_refptr<SpeechRecognizer> recognizer; bool is_active; // Set to true when recording or recognition is going on. }; // Private constructor to enforce singleton. friend struct base::DefaultLazyInstanceTraits<SpeechInputManagerImpl>; SpeechInputManagerImpl(); virtual ~SpeechInputManagerImpl(); bool HasPendingRequest(int caller_id) const; SpeechInputManagerDelegate* GetDelegate(int caller_id) const; void CancelRecognitionAndInformDelegate(int caller_id); // Starts/restarts recognition for an existing request. void StartRecognitionForRequest(int caller_id); SpeechInputManagerDelegate* delegate_; typedef std::map<int, SpeechInputRequest> SpeechRecognizerMap; SpeechRecognizerMap requests_; int recording_caller_id_; scoped_refptr<SpeechInputBubbleController> bubble_controller_; scoped_refptr<HardwareInfo> hardware_info_; }; static ::base::LazyInstance<SpeechInputManagerImpl> g_speech_input_manager_impl( base::LINKER_INITIALIZED); SpeechInputManager* SpeechInputManager::Get() { return g_speech_input_manager_impl.Pointer(); } bool SpeechInputManager::IsFeatureEnabled() { bool enabled = true; const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kDisableSpeechInput)) { enabled = false; #if defined(GOOGLE_CHROME_BUILD) } else if (!command_line.HasSwitch(switches::kEnableSpeechInput)) { // We need to evaluate whether IO is OK here. http://crbug.com/63335. base::ThreadRestrictions::ScopedAllowIO allow_io; // Official Chrome builds have speech input enabled by default only in the // dev channel. std::string channel = platform_util::GetVersionStringModifier(); enabled = (channel == "dev"); #endif } return enabled; } SpeechInputManagerImpl::SpeechInputManagerImpl() : recording_caller_id_(0), bubble_controller_(new SpeechInputBubbleController( ALLOW_THIS_IN_INITIALIZER_LIST(this))) { } SpeechInputManagerImpl::~SpeechInputManagerImpl() { while (requests_.begin() != requests_.end()) CancelRecognition(requests_.begin()->first); } bool SpeechInputManagerImpl::HasPendingRequest(int caller_id) const { return requests_.find(caller_id) != requests_.end(); } SpeechInputManagerDelegate* SpeechInputManagerImpl::GetDelegate( int caller_id) const { return requests_.find(caller_id)->second.delegate; } void SpeechInputManagerImpl::StartRecognition( SpeechInputManagerDelegate* delegate, int caller_id, int render_process_id, int render_view_id, const gfx::Rect& element_rect, const std::string& language, const std::string& grammar) { DCHECK(!HasPendingRequest(caller_id)); bubble_controller_->CreateBubble(caller_id, render_process_id, render_view_id, element_rect); if (!hardware_info_.get()) { hardware_info_ = new HardwareInfo(); // Since hardware info is optional with speech input requests, we start an // asynchronous fetch here and move on with recording audio. This first // speech input request would send an empty string for hardware info and // subsequent requests may have the hardware info available if the fetch // completed before them. This way we don't end up stalling the user with // a long wait and disk seeks when they click on a UI element and start // speaking. hardware_info_->Refresh(); } SpeechInputRequest* request = &requests_[caller_id]; request->delegate = delegate; request->recognizer = new SpeechRecognizer(this, caller_id, language, grammar, hardware_info_->value()); request->is_active = false; StartRecognitionForRequest(caller_id); } void SpeechInputManagerImpl::StartRecognitionForRequest(int caller_id) { DCHECK(HasPendingRequest(caller_id)); // If we are currently recording audio for another caller, abort that cleanly. if (recording_caller_id_) CancelRecognitionAndInformDelegate(recording_caller_id_); if (!AudioManager::GetAudioManager()->HasAudioInputDevices()) { bubble_controller_->SetBubbleMessage( caller_id, l10n_util::GetStringUTF16(IDS_SPEECH_INPUT_NO_MIC)); } else { recording_caller_id_ = caller_id; requests_[caller_id].is_active = true; requests_[caller_id].recognizer->StartRecording(); } } void SpeechInputManagerImpl::CancelRecognition(int caller_id) { DCHECK(HasPendingRequest(caller_id)); if (requests_[caller_id].is_active) requests_[caller_id].recognizer->CancelRecognition(); requests_.erase(caller_id); if (recording_caller_id_ == caller_id) recording_caller_id_ = 0; bubble_controller_->CloseBubble(caller_id); } void SpeechInputManagerImpl::StopRecording(int caller_id) { DCHECK(HasPendingRequest(caller_id)); requests_[caller_id].recognizer->StopRecording(); } void SpeechInputManagerImpl::SetRecognitionResult( int caller_id, bool error, const SpeechInputResultArray& result) { DCHECK(HasPendingRequest(caller_id)); GetDelegate(caller_id)->SetRecognitionResult(caller_id, result); } void SpeechInputManagerImpl::DidCompleteRecording(int caller_id) { DCHECK(recording_caller_id_ == caller_id); DCHECK(HasPendingRequest(caller_id)); recording_caller_id_ = 0; GetDelegate(caller_id)->DidCompleteRecording(caller_id); bubble_controller_->SetBubbleRecognizingMode(caller_id); } void SpeechInputManagerImpl::DidCompleteRecognition(int caller_id) { GetDelegate(caller_id)->DidCompleteRecognition(caller_id); requests_.erase(caller_id); bubble_controller_->CloseBubble(caller_id); } void SpeechInputManagerImpl::OnRecognizerError( int caller_id, SpeechRecognizer::ErrorCode error) { if (caller_id == recording_caller_id_) recording_caller_id_ = 0; requests_[caller_id].is_active = false; int message_id; switch (error) { case SpeechRecognizer::RECOGNIZER_ERROR_CAPTURE: message_id = IDS_SPEECH_INPUT_ERROR; break; case SpeechRecognizer::RECOGNIZER_ERROR_NO_SPEECH: message_id = IDS_SPEECH_INPUT_NO_SPEECH; break; case SpeechRecognizer::RECOGNIZER_ERROR_NO_RESULTS: message_id = IDS_SPEECH_INPUT_NO_RESULTS; break; default: NOTREACHED() << "unknown error " << error; return; } bubble_controller_->SetBubbleMessage(caller_id, l10n_util::GetStringUTF16(message_id)); } void SpeechInputManagerImpl::DidCompleteEnvironmentEstimation(int caller_id) { DCHECK(HasPendingRequest(caller_id)); DCHECK(recording_caller_id_ == caller_id); // Speech recognizer has gathered enough background audio so we can ask the // user to start speaking. bubble_controller_->SetBubbleRecordingMode(caller_id); } void SpeechInputManagerImpl::SetInputVolume(int caller_id, float volume) { DCHECK(HasPendingRequest(caller_id)); DCHECK_EQ(recording_caller_id_, caller_id); bubble_controller_->SetBubbleInputVolume(caller_id, volume); } void SpeechInputManagerImpl::CancelRecognitionAndInformDelegate(int caller_id) { SpeechInputManagerDelegate* cur_delegate = GetDelegate(caller_id); CancelRecognition(caller_id); cur_delegate->DidCompleteRecording(caller_id); cur_delegate->DidCompleteRecognition(caller_id); } void SpeechInputManagerImpl::InfoBubbleButtonClicked( int caller_id, SpeechInputBubble::Button button) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // Ignore if the caller id was not in our active recognizers list because the // user might have clicked more than once, or recognition could have been // cancelled due to other reasons before the user click was processed. if (!HasPendingRequest(caller_id)) return; if (button == SpeechInputBubble::BUTTON_CANCEL) { CancelRecognitionAndInformDelegate(caller_id); } else if (button == SpeechInputBubble::BUTTON_TRY_AGAIN) { StartRecognitionForRequest(caller_id); } } void SpeechInputManagerImpl::InfoBubbleFocusChanged(int caller_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // Ignore if the caller id was not in our active recognizers list because the // user might have clicked more than once, or recognition could have been // ended due to other reasons before the user click was processed. if (HasPendingRequest(caller_id)) { // If this is an ongoing recording or if we were displaying an error message // to the user, abort it since user has switched focus. Otherwise // recognition has started and keep that going so user can start speaking to // another element while this gets the results in parallel. if (recording_caller_id_ == caller_id || !requests_[caller_id].is_active) { CancelRecognitionAndInformDelegate(caller_id); } } } } // namespace speech_input <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- * * OpenSim: testModelCopy.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the Authors * * Author(s): Ayman Habib * * * * Licensed under the Apache License, Version 2.0 (the "License"); you may * * not use this file except in compliance with the License. You may obtain a * * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * -------------------------------------------------------------------------- */ #include <stdint.h> #include <OpenSim/Simulation/Model/Model.h> #include <OpenSim/Common/LoadOpenSimLibrary.h> #include <OpenSim/Auxiliary/auxiliaryTestFunctions.h> using namespace OpenSim; using namespace std; // Test copying, serializing and deserializing models and verify // that the number of bodies (nbods) and the number of attached geometry // (ngeom) on a given PhysicalFrame (by name) are preserved. void testCopyModel( const string& fileName, const int nbod, const string& physicalFrameName, const int ngeom); int main() { try { // Test copying a simple property. { std::cout << "Test copying a simple property." << std::endl; Property<double>* a = Property<double>::TypeHelper::create("a", true); a->setValue(0.123456789); Property<double>* b = Property<double>::TypeHelper::create("b", true); b->setValue(10.0); b->assign(*a); cout << "b = " << b->toString() << endl; ASSERT(*a == *b); } // Test copying a an Object property. { std::cout << "Test copying a object property." << std::endl; Body A("A", 0.12345, SimTK::Vec3(0.1, 0.2, 0.3), SimTK::Inertia(0.33, 0.22, 0.11)); Body B; Property<Body>* a = Property<Body>::TypeHelper::create("a", true); a->setValue(A); Property<Body>* b = Property<Body>::TypeHelper::create("b", true); b->setValue(B); b->assign(*a); cout << "b = " << b->toString() << endl; ASSERT(*a == *b); B = A; ASSERT(B == A); } Model arm("arm26.osim"); Model armAssigned; armAssigned = arm; ASSERT(armAssigned == arm); arm.finalizeFromProperties(); LoadOpenSimLibrary("osimActuators"); testCopyModel("arm26.osim", 2, "ground", 6); testCopyModel("Neck3dof_point_constraint.osim", 25, "spine", 1); } catch (const Exception& e) { e.print(cerr); return 1; } cout << "Done" << endl; return 0; } void testCopyModel(const string& fileName, const int nbod, const string& physicalFrameName, const int ngeom) { const size_t mem0 = getCurrentRSS(); // Automatically finalizes properties by default when loading from file Model* model = new Model(fileName); model->finalizeFromProperties(); // Catch a possible decrease in the memory footprint, which will cause // size_t (unsigned int) to wrap through zero. const size_t mem1 = getCurrentRSS(); const size_t increaseInMemory = mem1 > mem0 ? mem1-mem0 : 0; cout << "Memory use of '" << fileName <<"' model: " << increaseInMemory/1024 << "KB" << endl; Model *test = nullptr; for (int i = 0; i < 10; ++i){ test = new Model(fileName); delete test; } //model->print("clone_" + fileName); //SimTK::State& defaultState = model->initSystem(); Model* modelCopy = new Model(*model); modelCopy->finalizeFromProperties(); // At this point properties should all match. assert that ASSERT(*model==*modelCopy); ASSERT( model->getActuators().getSize() == modelCopy->getActuators().getSize() ); //SimTK::State& defaultStateOfCopy = modelCopy->initSystem(); // Compare state //defaultState.getY().dump("defaultState:Y"); //ASSERT ((defaultState.getY()-defaultStateOfCopy.getY()).norm() < 1e-7); // Now delete original model and make sure copy can stand Model *cloneModel = modelCopy->clone(); cloneModel->finalizeFromProperties(); ASSERT(*model == *cloneModel); ASSERT(model->getActuators().getSize() == cloneModel->getActuators().getSize()); // Compare state again //SimTK::State& defaultStateOfCopy2 = newModel->initSystem(); // Compare state //ASSERT ((defaultState.getY()-defaultStateOfCopy2.getY()).norm() < 1e-7); //ASSERT ((defaultState.getZ()-defaultStateOfCopy2.getZ()).norm() < 1e-7); std::string latestFile = "lastest_" + fileName; modelCopy->print(latestFile); modelCopy->finalizeFromProperties(); Model* modelSerialized = new Model(latestFile); modelSerialized->finalizeFromProperties(); ASSERT(*modelSerialized == *modelCopy); int nb = modelSerialized->getNumBodies(); const PhysicalFrame& physFrame = modelSerialized->getComponent<PhysicalFrame>("./"+physicalFrameName); int ng = physFrame.getProperty_attached_geometry().size(); ASSERT(nb == nbod); ASSERT(ng == ngeom); delete model; delete modelCopy; delete cloneModel; delete modelSerialized; // New memory footprint. const size_t mem2 = getCurrentRSS(); // Increase in memory footprint. const int64_t memory_increase = mem2 > mem1 ? mem2-mem1 : 0; cout << "Memory increase AFTER copy and init and delete: " << double(memory_increase)/mem1*100 << "%." << endl; } <commit_msg>80 char.<commit_after>/* -------------------------------------------------------------------------- * * OpenSim: testModelCopy.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the Authors * * Author(s): Ayman Habib * * * * Licensed under the Apache License, Version 2.0 (the "License"); you may * * not use this file except in compliance with the License. You may obtain a * * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * -------------------------------------------------------------------------- */ #include <stdint.h> #include <OpenSim/Simulation/Model/Model.h> #include <OpenSim/Common/LoadOpenSimLibrary.h> #include <OpenSim/Auxiliary/auxiliaryTestFunctions.h> using namespace OpenSim; using namespace std; // Test copying, serializing and deserializing models and verify // that the number of bodies (nbods) and the number of attached geometry // (ngeom) on a given PhysicalFrame (by name) are preserved. void testCopyModel( const string& fileName, const int nbod, const string& physicalFrameName, const int ngeom); int main() { try { // Test copying a simple property. { std::cout << "Test copying a simple property." << std::endl; Property<double>* a = Property<double>::TypeHelper::create("a", true); a->setValue(0.123456789); Property<double>* b = Property<double>::TypeHelper::create("b", true); b->setValue(10.0); b->assign(*a); cout << "b = " << b->toString() << endl; ASSERT(*a == *b); } // Test copying a an Object property. { std::cout << "Test copying a object property." << std::endl; Body A("A", 0.12345, SimTK::Vec3(0.1, 0.2, 0.3), SimTK::Inertia(0.33, 0.22, 0.11)); Body B; Property<Body>* a = Property<Body>::TypeHelper::create("a", true); a->setValue(A); Property<Body>* b = Property<Body>::TypeHelper::create("b", true); b->setValue(B); b->assign(*a); cout << "b = " << b->toString() << endl; ASSERT(*a == *b); B = A; ASSERT(B == A); } Model arm("arm26.osim"); Model armAssigned; armAssigned = arm; ASSERT(armAssigned == arm); arm.finalizeFromProperties(); LoadOpenSimLibrary("osimActuators"); testCopyModel("arm26.osim", 2, "ground", 6); testCopyModel("Neck3dof_point_constraint.osim", 25, "spine", 1); } catch (const Exception& e) { e.print(cerr); return 1; } cout << "Done" << endl; return 0; } void testCopyModel(const string& fileName, const int nbod, const string& physicalFrameName, const int ngeom) { const size_t mem0 = getCurrentRSS(); // Automatically finalizes properties by default when loading from file Model* model = new Model(fileName); model->finalizeFromProperties(); // Catch a possible decrease in the memory footprint, which will cause // size_t (unsigned int) to wrap through zero. const size_t mem1 = getCurrentRSS(); const size_t increaseInMemory = mem1 > mem0 ? mem1-mem0 : 0; cout << "Memory use of '" << fileName <<"' model: " << increaseInMemory/1024 << "KB" << endl; Model *test = nullptr; for (int i = 0; i < 10; ++i){ test = new Model(fileName); delete test; } //model->print("clone_" + fileName); //SimTK::State& defaultState = model->initSystem(); Model* modelCopy = new Model(*model); modelCopy->finalizeFromProperties(); // At this point properties should all match. assert that ASSERT(*model==*modelCopy); ASSERT(model->getActuators().getSize() == modelCopy->getActuators().getSize()); //SimTK::State& defaultStateOfCopy = modelCopy->initSystem(); // Compare state //defaultState.getY().dump("defaultState:Y"); //ASSERT ((defaultState.getY()-defaultStateOfCopy.getY()).norm() < 1e-7); // Now delete original model and make sure copy can stand Model *cloneModel = modelCopy->clone(); cloneModel->finalizeFromProperties(); ASSERT(*model == *cloneModel); ASSERT(model->getActuators().getSize() == cloneModel->getActuators().getSize()); // Compare state again //SimTK::State& defaultStateOfCopy2 = newModel->initSystem(); // Compare state //ASSERT ((defaultState.getY()-defaultStateOfCopy2.getY()).norm() < 1e-7); //ASSERT ((defaultState.getZ()-defaultStateOfCopy2.getZ()).norm() < 1e-7); std::string latestFile = "lastest_" + fileName; modelCopy->print(latestFile); modelCopy->finalizeFromProperties(); Model* modelSerialized = new Model(latestFile); modelSerialized->finalizeFromProperties(); ASSERT(*modelSerialized == *modelCopy); int nb = modelSerialized->getNumBodies(); const PhysicalFrame& physFrame = modelSerialized->getComponent<PhysicalFrame>("./"+physicalFrameName); int ng = physFrame.getProperty_attached_geometry().size(); ASSERT(nb == nbod); ASSERT(ng == ngeom); delete model; delete modelCopy; delete cloneModel; delete modelSerialized; // New memory footprint. const size_t mem2 = getCurrentRSS(); // Increase in memory footprint. const int64_t memory_increase = mem2 > mem1 ? mem2-mem1 : 0; cout << "Memory increase AFTER copy and init and delete: " << double(memory_increase)/mem1*100 << "%." << endl; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: detreg.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: kz $ $Date: 2006-07-21 14:34:46 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" #include "scdetect.hxx" #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_ #include <com/sun/star/registry/XRegistryKey.hpp> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_ #include <com/sun/star/uno/Sequence.h> #endif #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif using namespace ::rtl; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; extern "C" { SAL_DLLPUBLIC_EXPORT void SAL_CALL component_getImplementationEnvironment( const sal_Char** ppEnvironmentTypeName, uno_Environment** ppEnvironment ) { *ppEnvironmentTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ; } SAL_DLLPUBLIC_EXPORT sal_Bool SAL_CALL component_writeInfo( void* pServiceManager , void* pRegistryKey ) { Reference< ::registry::XRegistryKey > xKey( reinterpret_cast< ::registry::XRegistryKey* >( pRegistryKey ) ) ; OUString aDelimiter( RTL_CONSTASCII_USTRINGPARAM("/") ); OUString aUnoServices( RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") ); // Eigentliche Implementierung und ihre Services registrieren sal_Int32 i; Reference< ::registry::XRegistryKey > xNewKey(xKey->createKey( aDelimiter + ScFilterDetect::impl_getStaticImplementationName() + aUnoServices )); Sequence< OUString > aServices(ScFilterDetect::impl_getStaticSupportedServiceNames()); for(i = 0; i < aServices.getLength(); i++ ) xNewKey->createKey( aServices.getConstArray()[i] ); return sal_True; } SAL_DLLPUBLIC_EXPORT void* SAL_CALL component_getFactory( const sal_Char* pImplementationName, void* pServiceManager, void* pRegistryKey ) { // Set default return value for this operation - if it failed. void* pReturn = NULL ; if ( ( pImplementationName != NULL ) && ( pServiceManager != NULL ) ) { // Define variables which are used in following macros. Reference< XSingleServiceFactory > xFactory ; Reference< XMultiServiceFactory > xServiceManager( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ; if( ScFilterDetect::impl_getStaticImplementationName().equalsAscii( pImplementationName ) ) { xFactory.set(::cppu::createSingleFactory( xServiceManager, ScFilterDetect::impl_getStaticImplementationName(), ScFilterDetect::impl_createInstance, ScFilterDetect::impl_getStaticSupportedServiceNames() )); } // Factory is valid - service was found. if ( xFactory.is() ) { xFactory->acquire(); pReturn = xFactory.get(); } } // Return with result of this operation. return pReturn ; } } // extern "C" <commit_msg>INTEGRATION: CWS calcwarnings (1.6.110); FILE MERGED 2006/12/01 08:53:42 nn 1.6.110.1: #i69284# warning-free: ui, wntmsci10<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: detreg.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: vg $ $Date: 2007-02-27 13:43:40 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" #include "scdetect.hxx" #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_ #include <com/sun/star/registry/XRegistryKey.hpp> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_ #include <com/sun/star/uno/Sequence.h> #endif #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif using namespace ::rtl; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; extern "C" { SAL_DLLPUBLIC_EXPORT void SAL_CALL component_getImplementationEnvironment( const sal_Char** ppEnvironmentTypeName, uno_Environment** /* ppEnvironment */ ) { *ppEnvironmentTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME ; } SAL_DLLPUBLIC_EXPORT sal_Bool SAL_CALL component_writeInfo( void* /* pServiceManager */ , void* pRegistryKey ) { Reference< ::registry::XRegistryKey > xKey( reinterpret_cast< ::registry::XRegistryKey* >( pRegistryKey ) ) ; OUString aDelimiter( RTL_CONSTASCII_USTRINGPARAM("/") ); OUString aUnoServices( RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") ); // Eigentliche Implementierung und ihre Services registrieren sal_Int32 i; Reference< ::registry::XRegistryKey > xNewKey(xKey->createKey( aDelimiter + ScFilterDetect::impl_getStaticImplementationName() + aUnoServices )); Sequence< OUString > aServices(ScFilterDetect::impl_getStaticSupportedServiceNames()); for(i = 0; i < aServices.getLength(); i++ ) xNewKey->createKey( aServices.getConstArray()[i] ); return sal_True; } SAL_DLLPUBLIC_EXPORT void* SAL_CALL component_getFactory( const sal_Char* pImplementationName, void* pServiceManager, void* /* pRegistryKey */ ) { // Set default return value for this operation - if it failed. void* pReturn = NULL ; if ( ( pImplementationName != NULL ) && ( pServiceManager != NULL ) ) { // Define variables which are used in following macros. Reference< XSingleServiceFactory > xFactory ; Reference< XMultiServiceFactory > xServiceManager( reinterpret_cast< XMultiServiceFactory* >( pServiceManager ) ) ; if( ScFilterDetect::impl_getStaticImplementationName().equalsAscii( pImplementationName ) ) { xFactory.set(::cppu::createSingleFactory( xServiceManager, ScFilterDetect::impl_getStaticImplementationName(), ScFilterDetect::impl_createInstance, ScFilterDetect::impl_getStaticSupportedServiceNames() )); } // Factory is valid - service was found. if ( xFactory.is() ) { xFactory->acquire(); pReturn = xFactory.get(); } } // Return with result of this operation. return pReturn ; } } // extern "C" <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU General Public License as published by the Free * * Software Foundation; either version 2 of the License, or (at your option) * * any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * * more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., 51 * * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Applications * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #include <SofaTest/Mapping_test.h> #include <SofaTest/MultiMapping_test.h> #include <sofa/defaulttype/VecTypes.h> #include <Compliant/mapping/DotProductMapping.h> namespace sofa { /** Test suite for DotProductMapping */ template <typename Mapping> struct DotProductMappingTest : public Mapping_test<Mapping> { typedef DotProductMappingTest self; typedef Mapping_test<Mapping> base; typedef sofa::defaulttype::Vec<3,SReal> Vec3; Mapping* mapping; DotProductMappingTest() { mapping = static_cast<Mapping*>(this->base::mapping); } bool test() { // we need to increase the error for avoiding numerical problem this->errorMax *= 600; this->deltaRange.first = this->errorMax*100; this->deltaRange.second = this->errorMax*1000; // parents typename self::InVecCoord xin(4); xin[0] = typename self::InCoord(1,1,1); xin[1] = typename self::InCoord(5,6,7); xin[2] = typename self::InCoord(12,-3,6); xin[3] = typename self::InCoord(8,-2,-4); typename self::OutVecCoord expected(3); expected[0] = typename self::OutCoord(18); expected[1] = typename self::OutCoord(78); expected[2] = typename self::OutCoord(2); // mapping parameters typename Mapping::pairs_type pairs(3); pairs[0][0] = 0; pairs[0][1] = 1; pairs[1][0] = 2; pairs[1][1] = 3; pairs[2][0] = 0; pairs[2][1] = 3; mapping->pairs.setValue(pairs); return this->runTest(xin, expected); } }; // Define the list of types to instanciate. We do not necessarily need to test all combinations. using testing::Types; typedef Types< component::mapping::DotProductMapping<defaulttype::Vec3Types, defaulttype::Vec1Types> > DataTypes; // the types to instanciate. // Test suite for all the instanciations TYPED_TEST_CASE(DotProductMappingTest, DataTypes); TYPED_TEST( DotProductMappingTest, test ) { ASSERT_TRUE( this->test() ); } //////////////////////// /** Test suite for DotProductMultiMapping */ template <typename Mapping> struct DotProductMultiMappingTest : public MultiMapping_test<Mapping> { typedef DotProductMultiMappingTest self; typedef MultiMapping_test<Mapping> base; Mapping* mapping; DotProductMultiMappingTest() { mapping = static_cast<Mapping*>(this->base::mapping); } bool test() { // we need to increase the error for avoiding numerical problem this->errorMax *= 600; this->deltaRange.first = this->errorMax*100; this->deltaRange.second = this->errorMax*1000; const int NP = 2; this->setupScene(NP); // NP parents, 1 child // parent positions helper::vector< typename self::InVecCoord > incoords(NP); for( int i=0; i<NP; i++ ) { incoords[i].resize(2); } self::In::set( incoords[0][0], 1,1,1 ); self::In::set( incoords[0][1], 65,3,-51 ); self::In::set( incoords[1][0], 23,35,-4 ); self::In::set( incoords[1][1], -100,100,20 ); // expected child positions typename self::OutVecCoord outcoords(2); outcoords[0][0] = 54; outcoords[1][0] = -7220; return this->runTest(incoords,outcoords); } }; // Define the list of types to instanciate. We do not necessarily need to test all combinations. typedef Types< component::mapping::DotProductMultiMapping<defaulttype::Vec3Types, defaulttype::Vec1Types> > DataTypes2; // the types to instanciate. // Test suite for all the instanciations TYPED_TEST_CASE(DotProductMultiMappingTest, DataTypes2); TYPED_TEST( DotProductMultiMappingTest, test ) { ASSERT_TRUE( this->test() ); } ///////////////////// /** Test suite for DotProductFromTargetMapping */ template <typename Mapping> struct DotProductFromTargetMappingTest : public Mapping_test<Mapping> { typedef DotProductFromTargetMappingTest self; typedef Mapping_test<Mapping> base; typedef sofa::defaulttype::Vec<3,SReal> Vec3; Mapping* mapping; DotProductFromTargetMappingTest() { mapping = static_cast<Mapping*>(this->base::mapping); } bool test() { // we need to increase the error for avoiding numerical problem this->errorMax *= 600; this->deltaRange.first = this->errorMax*100; this->deltaRange.second = this->errorMax*1000; // parents typename self::InVecCoord xin(4); xin[0] = typename self::InCoord(1,1,1); xin[1] = typename self::InCoord(5,6,7); xin[2] = typename self::InCoord(12,-3,6); xin[3] = typename self::InCoord(8,-2,-4); typename self::OutVecCoord expected(3); expected[0] = typename self::OutCoord(20); expected[1] = typename self::OutCoord(18); expected[2] = typename self::OutCoord(15); // mapping parameters helper::vector<unsigned> indices(3); indices[0] = 0; indices[1] = 1; indices[2] = 2; mapping->d_indices.setValue(indices); typename self::InVecCoord targets(2); targets[0] = typename self::InCoord(10,-20,30); targets[1] = typename self::InCoord(1,1,1); mapping->d_targets.setValue(targets); return this->runTest(xin, expected); } }; // Define the list of types to instanciate. We do not necessarily need to test all combinations. typedef Types< component::mapping::DotProductFromTargetMapping<defaulttype::Vec3Types, defaulttype::Vec1Types> > DataTypes3; // the types to instanciate. // Test suite for all the instanciations TYPED_TEST_CASE(DotProductFromTargetMappingTest, DataTypes3); TYPED_TEST( DotProductFromTargetMappingTest, test ) { ASSERT_TRUE( this->test() ); } } // namespace sofa <commit_msg>[Compliant] increasing a bit the tolerance of DotProductMappingTest<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU General Public License as published by the Free * * Software Foundation; either version 2 of the License, or (at your option) * * any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * * more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., 51 * * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Applications * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #include <SofaTest/Mapping_test.h> #include <SofaTest/MultiMapping_test.h> #include <sofa/defaulttype/VecTypes.h> #include <Compliant/mapping/DotProductMapping.h> namespace sofa { /** Test suite for DotProductMapping */ template <typename Mapping> struct DotProductMappingTest : public Mapping_test<Mapping> { typedef DotProductMappingTest self; typedef Mapping_test<Mapping> base; typedef sofa::defaulttype::Vec<3,SReal> Vec3; Mapping* mapping; DotProductMappingTest() { mapping = static_cast<Mapping*>(this->base::mapping); } bool test() { // we need to increase the error for avoiding numerical problem this->errorMax *= 1000; this->deltaRange.first = this->errorMax*100; this->deltaRange.second = this->errorMax*1000; // parents typename self::InVecCoord xin(4); xin[0] = typename self::InCoord(1,1,1); xin[1] = typename self::InCoord(5,6,7); xin[2] = typename self::InCoord(12,-3,6); xin[3] = typename self::InCoord(8,-2,-4); typename self::OutVecCoord expected(3); expected[0] = typename self::OutCoord(18); expected[1] = typename self::OutCoord(78); expected[2] = typename self::OutCoord(2); // mapping parameters typename Mapping::pairs_type pairs(3); pairs[0][0] = 0; pairs[0][1] = 1; pairs[1][0] = 2; pairs[1][1] = 3; pairs[2][0] = 0; pairs[2][1] = 3; mapping->pairs.setValue(pairs); return this->runTest(xin, expected); } }; // Define the list of types to instanciate. We do not necessarily need to test all combinations. using testing::Types; typedef Types< component::mapping::DotProductMapping<defaulttype::Vec3Types, defaulttype::Vec1Types> > DataTypes; // the types to instanciate. // Test suite for all the instanciations TYPED_TEST_CASE(DotProductMappingTest, DataTypes); TYPED_TEST( DotProductMappingTest, test ) { ASSERT_TRUE( this->test() ); } //////////////////////// /** Test suite for DotProductMultiMapping */ template <typename Mapping> struct DotProductMultiMappingTest : public MultiMapping_test<Mapping> { typedef DotProductMultiMappingTest self; typedef MultiMapping_test<Mapping> base; Mapping* mapping; DotProductMultiMappingTest() { mapping = static_cast<Mapping*>(this->base::mapping); } bool test() { // we need to increase the error for avoiding numerical problem this->errorMax *= 1000; this->deltaRange.first = this->errorMax*100; this->deltaRange.second = this->errorMax*1000; const int NP = 2; this->setupScene(NP); // NP parents, 1 child // parent positions helper::vector< typename self::InVecCoord > incoords(NP); for( int i=0; i<NP; i++ ) { incoords[i].resize(2); } self::In::set( incoords[0][0], 1,1,1 ); self::In::set( incoords[0][1], 65,3,-51 ); self::In::set( incoords[1][0], 23,35,-4 ); self::In::set( incoords[1][1], -100,100,20 ); // expected child positions typename self::OutVecCoord outcoords(2); outcoords[0][0] = 54; outcoords[1][0] = -7220; return this->runTest(incoords,outcoords); } }; // Define the list of types to instanciate. We do not necessarily need to test all combinations. typedef Types< component::mapping::DotProductMultiMapping<defaulttype::Vec3Types, defaulttype::Vec1Types> > DataTypes2; // the types to instanciate. // Test suite for all the instanciations TYPED_TEST_CASE(DotProductMultiMappingTest, DataTypes2); TYPED_TEST( DotProductMultiMappingTest, test ) { ASSERT_TRUE( this->test() ); } ///////////////////// /** Test suite for DotProductFromTargetMapping */ template <typename Mapping> struct DotProductFromTargetMappingTest : public Mapping_test<Mapping> { typedef DotProductFromTargetMappingTest self; typedef Mapping_test<Mapping> base; typedef sofa::defaulttype::Vec<3,SReal> Vec3; Mapping* mapping; DotProductFromTargetMappingTest() { mapping = static_cast<Mapping*>(this->base::mapping); } bool test() { // we need to increase the error for avoiding numerical problem this->errorMax *= 1000; this->deltaRange.first = this->errorMax*100; this->deltaRange.second = this->errorMax*1000; // parents typename self::InVecCoord xin(4); xin[0] = typename self::InCoord(1,1,1); xin[1] = typename self::InCoord(5,6,7); xin[2] = typename self::InCoord(12,-3,6); xin[3] = typename self::InCoord(8,-2,-4); typename self::OutVecCoord expected(3); expected[0] = typename self::OutCoord(20); expected[1] = typename self::OutCoord(18); expected[2] = typename self::OutCoord(15); // mapping parameters helper::vector<unsigned> indices(3); indices[0] = 0; indices[1] = 1; indices[2] = 2; mapping->d_indices.setValue(indices); typename self::InVecCoord targets(2); targets[0] = typename self::InCoord(10,-20,30); targets[1] = typename self::InCoord(1,1,1); mapping->d_targets.setValue(targets); return this->runTest(xin, expected); } }; // Define the list of types to instanciate. We do not necessarily need to test all combinations. typedef Types< component::mapping::DotProductFromTargetMapping<defaulttype::Vec3Types, defaulttype::Vec1Types> > DataTypes3; // the types to instanciate. // Test suite for all the instanciations TYPED_TEST_CASE(DotProductFromTargetMappingTest, DataTypes3); TYPED_TEST( DotProductFromTargetMappingTest, test ) { ASSERT_TRUE( this->test() ); } } // namespace sofa <|endoftext|>
<commit_before>/* $Id$ */ testESDtrackCuts(Char_t* dataDir=, Int_t nRuns=10) { Char_t str[256]; gSystem->Load("libESDtrackCuts.so"); // ######################################################## // definition of ESD track cuts AliESDtrackCuts* trackCuts = new AliESDtrackCuts(); trackCuts->DefineHistograms(4); trackCuts->SetMinNClustersTPC(50); trackCuts->SetMaxChi2PerClusterTPC(3.5); trackCuts->SetMaxCovDiagonalElements(2,2,0.5,0.5,2); trackCuts->SetRequireTPCRefit(kTRUE); trackCuts->SetMinNsigmaToVertex(3); trackCuts->SetAcceptKingDaughters(kFALSE); trackCuts->SetPRange(0.3); AliLog::SetClassDebugLevel("AliESDtrackCuts",1); // ######################################################## // definition of used pointers TFile* esdFile; TTree* esdTree; TBranch* esdBranch; AliESD* esd = 0; // ######################################################## // get the data dir Char_t execDir[256]; sprintf(execDir,gSystem->pwd()); TSystemDirectory* baseDir = new TSystemDirectory(".",dataDir); TList* dirList = baseDir->GetListOfFiles(); Int_t nDirs = dirList->GetEntries(); // go back to the dir where this script is executed gSystem->cd(execDir); // ######################################################## // loop over runs Int_t nRunCounter = 0; for (Int_t r=1; r<=nDirs; r++) { TSystemFile* presentDir = (TSystemFile*)dirList->At(r); if (!presentDir->IsDirectory()) continue; // first check that the files are there sprintf(str,"%s/%s",dataDir, presentDir->GetName()); if ((!gSystem->Which(str,"galice.root")) || (!gSystem->Which(str,"AliESDs.root"))) continue; if (nRunCounter++ >= nRuns) break; cout << "run #" << nRunCounter << endl; // ######################################################### // setup galice and runloader if (gAlice) { delete gAlice->GetRunLoader(); delete gAlice; gAlice=0; } sprintf(str,"%s/run%d/galice.root",dataDir,r); AliRunLoader* runLoader = AliRunLoader::Open(str); runLoader->LoadgAlice(); gAlice = runLoader->GetAliRun(); runLoader->LoadHeader(); // ######################################################### // open esd file and get the tree sprintf(str,"%s/run%d/AliESDs.root",dataDir,r); // close it first to avoid memory leak if (esdFile) if (esdFile->IsOpen()) esdFile->Close(); esdFile = TFile::Open(str); esdTree = (TTree*)esdFile->Get("esdTree"); if (!esdTree) continue; esdBranch = esdTree->GetBranch("ESD"); esdBranch->SetAddress(&esd); if (!esdBranch) continue; // ######################################################## // Magnetic field AliTracker::SetFieldMap(gAlice->Field(),kTRUE); // kTRUE means uniform magnetic field // ######################################################## // getting number of events Int_t nEvents = (Int_t)runLoader->GetNumberOfEvents(); Int_t nESDEvents = esdBranch->GetEntries(); if (nEvents!=nESDEvents) cout << " Warning: Different number of events from runloader and esdtree!!!" << nEvents << " / " << nESDEvents << endl; // ######################################################## // loop over number of events cout << " looping over events..." << endl; for(Int_t i=1; i<nEvents; i++) { esdBranch->GetEntry(i); runLoader->GetEvent(i); // ######################################################## // get the EDS vertex AliESDVertex* vtxESD = esd->GetVertex(); Double_t vtxSigma[3]; vtxESD->GetSigmaXYZ(vtxSigma); // ######################################################## // loop over esd tracks Int_t nTracks = esd->GetNumberOfTracks(); for (Int_t t=0; t<nTracks; t++) { AliESDtrack* esdTrack = esd->GetTrack(t); //trackCuts->AcceptTrack(esdTrack, vtxESD, esd->GetMagneticField()); trackCuts->AcceptTrack(esdTrack); } // end of track loop } // end of event loop } // end of run loop TFile* fout = new TFile("out.root","RECREATE"); trackCuts->SaveHistograms("esd_track_cuts"); fout->Write(); fout->Close(); } <commit_msg>changed to new library<commit_after>/* $Id$ */ testESDtrackCuts(Char_t* dataDir=, Int_t nRuns=10) { Char_t str[256]; gSystem->Load("libPWG0base.so"); // ######################################################## // definition of ESD track cuts AliESDtrackCuts* trackCuts = new AliESDtrackCuts(); trackCuts->DefineHistograms(4); trackCuts->SetMinNClustersTPC(50); trackCuts->SetMaxChi2PerClusterTPC(3.5); trackCuts->SetMaxCovDiagonalElements(2,2,0.5,0.5,2); trackCuts->SetRequireTPCRefit(kTRUE); trackCuts->SetMinNsigmaToVertex(3); trackCuts->SetAcceptKingDaughters(kFALSE); trackCuts->SetPRange(0.3); AliLog::SetClassDebugLevel("AliESDtrackCuts",1); // ######################################################## // definition of used pointers TFile* esdFile; TTree* esdTree; TBranch* esdBranch; AliESD* esd = 0; // ######################################################## // get the data dir Char_t execDir[256]; sprintf(execDir,gSystem->pwd()); TSystemDirectory* baseDir = new TSystemDirectory(".",dataDir); TList* dirList = baseDir->GetListOfFiles(); Int_t nDirs = dirList->GetEntries(); // go back to the dir where this script is executed gSystem->cd(execDir); // ######################################################## // loop over runs Int_t nRunCounter = 0; for (Int_t r=1; r<=nDirs; r++) { TSystemFile* presentDir = (TSystemFile*)dirList->At(r); if (!presentDir->IsDirectory()) continue; // first check that the files are there sprintf(str,"%s/%s",dataDir, presentDir->GetName()); if ((!gSystem->Which(str,"galice.root")) || (!gSystem->Which(str,"AliESDs.root"))) continue; if (nRunCounter++ >= nRuns) break; cout << "run #" << nRunCounter << endl; // ######################################################### // setup galice and runloader if (gAlice) { delete gAlice->GetRunLoader(); delete gAlice; gAlice=0; } sprintf(str,"%s/run%d/galice.root",dataDir,r); AliRunLoader* runLoader = AliRunLoader::Open(str); runLoader->LoadgAlice(); gAlice = runLoader->GetAliRun(); runLoader->LoadHeader(); // ######################################################### // open esd file and get the tree sprintf(str,"%s/run%d/AliESDs.root",dataDir,r); // close it first to avoid memory leak if (esdFile) if (esdFile->IsOpen()) esdFile->Close(); esdFile = TFile::Open(str); esdTree = (TTree*)esdFile->Get("esdTree"); if (!esdTree) continue; esdBranch = esdTree->GetBranch("ESD"); esdBranch->SetAddress(&esd); if (!esdBranch) continue; // ######################################################## // Magnetic field AliTracker::SetFieldMap(gAlice->Field(),kTRUE); // kTRUE means uniform magnetic field // ######################################################## // getting number of events Int_t nEvents = (Int_t)runLoader->GetNumberOfEvents(); Int_t nESDEvents = esdBranch->GetEntries(); if (nEvents!=nESDEvents) cout << " Warning: Different number of events from runloader and esdtree!!!" << nEvents << " / " << nESDEvents << endl; // ######################################################## // loop over number of events cout << " looping over events..." << endl; for(Int_t i=1; i<nEvents; i++) { esdBranch->GetEntry(i); runLoader->GetEvent(i); // ######################################################## // get the EDS vertex AliESDVertex* vtxESD = esd->GetVertex(); Double_t vtxSigma[3]; vtxESD->GetSigmaXYZ(vtxSigma); // ######################################################## // loop over esd tracks Int_t nTracks = esd->GetNumberOfTracks(); for (Int_t t=0; t<nTracks; t++) { AliESDtrack* esdTrack = esd->GetTrack(t); //trackCuts->AcceptTrack(esdTrack, vtxESD, esd->GetMagneticField()); trackCuts->AcceptTrack(esdTrack); } // end of track loop } // end of event loop } // end of run loop TFile* fout = new TFile("out.root","RECREATE"); trackCuts->SaveHistograms("esd_track_cuts"); fout->Write(); fout->Close(); } <|endoftext|>
<commit_before>/* * Copyright (C) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "modules/geolocation/GeolocationController.h" #include "core/inspector/InspectorController.h" #include "core/page/Page.h" #include "modules/geolocation/GeolocationClient.h" #include "modules/geolocation/GeolocationError.h" #include "modules/geolocation/GeolocationInspectorAgent.h" #include "modules/geolocation/GeolocationPosition.h" namespace WebCore { GeolocationController::GeolocationController(LocalFrame& frame, GeolocationClient* client) : PageLifecycleObserver(frame.page()) , m_client(client) , m_hasClientForTest(false) , m_isClientUpdating(false) , m_inspectorAgent() { // FIXME: Once GeolocationInspectorAgent is per frame, there will be a 1:1 relationship between // it and this class. Until then, there's one GeolocationInspectorAgent per page that the main // frame is responsible for creating. if (frame.isMainFrame()) { OwnPtr<GeolocationInspectorAgent> geolocationAgent(GeolocationInspectorAgent::create()); m_inspectorAgent = geolocationAgent.get(); frame.page()->inspectorController().registerModuleAgent(geolocationAgent.release()); } else { m_inspectorAgent = GeolocationController::from(frame.page()->mainFrame())->m_inspectorAgent; } m_inspectorAgent->AddController(this); if (!frame.isMainFrame()) { // internals.setGeolocationClientMock is per page. GeolocationController* mainController = GeolocationController::from(frame.page()->mainFrame()); if (mainController->hasClientForTest()) setClientForTest(mainController->client()); } } void GeolocationController::startUpdatingIfNeeded() { if (m_isClientUpdating) return; m_isClientUpdating = true; m_client->startUpdating(); } void GeolocationController::stopUpdatingIfNeeded() { if (!m_isClientUpdating) return; m_isClientUpdating = false; m_client->stopUpdating(); } GeolocationController::~GeolocationController() { ASSERT(m_observers.isEmpty()); if (page()) m_inspectorAgent->RemoveController(this); if (m_hasClientForTest) m_client->controllerForTestRemoved(this); } void GeolocationController::willBeDestroyed() { if (m_client) m_client->geolocationDestroyed(); } PassOwnPtr<GeolocationController> GeolocationController::create(LocalFrame& frame, GeolocationClient* client) { return adoptPtr(new GeolocationController(frame, client)); } void GeolocationController::addObserver(Geolocation* observer, bool enableHighAccuracy) { // This may be called multiple times with the same observer, though removeObserver() // is called only once with each. bool wasEmpty = m_observers.isEmpty(); m_observers.add(observer); if (enableHighAccuracy) m_highAccuracyObservers.add(observer); if (m_client) { if (enableHighAccuracy) m_client->setEnableHighAccuracy(true); if (wasEmpty && page() && page()->visibilityState() == PageVisibilityStateVisible) startUpdatingIfNeeded(); } } void GeolocationController::removeObserver(Geolocation* observer) { if (!m_observers.contains(observer)) return; m_observers.remove(observer); m_highAccuracyObservers.remove(observer); if (m_client) { if (m_observers.isEmpty()) stopUpdatingIfNeeded(); else if (m_highAccuracyObservers.isEmpty()) m_client->setEnableHighAccuracy(false); } } void GeolocationController::requestPermission(Geolocation* geolocation) { if (m_client) m_client->requestPermission(geolocation); } void GeolocationController::cancelPermissionRequest(Geolocation* geolocation) { if (m_client) m_client->cancelPermissionRequest(geolocation); } void GeolocationController::positionChanged(GeolocationPosition* position) { position = m_inspectorAgent->overrideGeolocationPosition(position); if (!position) { errorOccurred(GeolocationError::create(GeolocationError::PositionUnavailable, "PositionUnavailable").get()); return; } m_lastPosition = position; WillBeHeapVector<RefPtrWillBeMember<Geolocation> > observersVector; copyToVector(m_observers, observersVector); for (size_t i = 0; i < observersVector.size(); ++i) observersVector[i]->positionChanged(); } void GeolocationController::errorOccurred(GeolocationError* error) { WillBeHeapVector<RefPtrWillBeMember<Geolocation> > observersVector; copyToVector(m_observers, observersVector); for (size_t i = 0; i < observersVector.size(); ++i) observersVector[i]->setError(error); } GeolocationPosition* GeolocationController::lastPosition() { if (m_lastPosition.get()) return m_lastPosition.get(); if (!m_client) return 0; return m_client->lastPosition(); } void GeolocationController::setClientForTest(GeolocationClient* client) { m_client = client; m_hasClientForTest = true; client->controllerForTestAdded(this); } void GeolocationController::pageVisibilityChanged() { if (m_observers.isEmpty() || !m_client) return; if (page() && page()->visibilityState() == PageVisibilityStateVisible) startUpdatingIfNeeded(); else stopUpdatingIfNeeded(); } const char* GeolocationController::supplementName() { return "GeolocationController"; } void provideGeolocationTo(LocalFrame& frame, GeolocationClient* client) { Supplement<LocalFrame>::provideTo(frame, GeolocationController::supplementName(), GeolocationController::create(frame, client)); } } // namespace WebCore <commit_msg>Fix use-after-free in geolocation layout test code introduced in r175404.<commit_after>/* * Copyright (C) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "modules/geolocation/GeolocationController.h" #include "core/inspector/InspectorController.h" #include "core/page/Page.h" #include "modules/geolocation/GeolocationClient.h" #include "modules/geolocation/GeolocationError.h" #include "modules/geolocation/GeolocationInspectorAgent.h" #include "modules/geolocation/GeolocationPosition.h" namespace WebCore { GeolocationController::GeolocationController(LocalFrame& frame, GeolocationClient* client) : PageLifecycleObserver(frame.page()) , m_client(client) , m_hasClientForTest(false) , m_isClientUpdating(false) , m_inspectorAgent() { // FIXME: Once GeolocationInspectorAgent is per frame, there will be a 1:1 relationship between // it and this class. Until then, there's one GeolocationInspectorAgent per page that the main // frame is responsible for creating. if (frame.isMainFrame()) { OwnPtr<GeolocationInspectorAgent> geolocationAgent(GeolocationInspectorAgent::create()); m_inspectorAgent = geolocationAgent.get(); frame.page()->inspectorController().registerModuleAgent(geolocationAgent.release()); } else { m_inspectorAgent = GeolocationController::from(frame.page()->mainFrame())->m_inspectorAgent; } m_inspectorAgent->AddController(this); if (!frame.isMainFrame()) { // internals.setGeolocationClientMock is per page. GeolocationController* mainController = GeolocationController::from(frame.page()->mainFrame()); if (mainController->hasClientForTest()) setClientForTest(mainController->client()); } } void GeolocationController::startUpdatingIfNeeded() { if (m_isClientUpdating) return; m_isClientUpdating = true; m_client->startUpdating(); } void GeolocationController::stopUpdatingIfNeeded() { if (!m_isClientUpdating) return; m_isClientUpdating = false; m_client->stopUpdating(); } GeolocationController::~GeolocationController() { ASSERT(m_observers.isEmpty()); if (page()) m_inspectorAgent->RemoveController(this); if (m_hasClientForTest) m_client->controllerForTestRemoved(this); } void GeolocationController::willBeDestroyed() { if (m_client) m_client->geolocationDestroyed(); } PassOwnPtr<GeolocationController> GeolocationController::create(LocalFrame& frame, GeolocationClient* client) { return adoptPtr(new GeolocationController(frame, client)); } void GeolocationController::addObserver(Geolocation* observer, bool enableHighAccuracy) { // This may be called multiple times with the same observer, though removeObserver() // is called only once with each. bool wasEmpty = m_observers.isEmpty(); m_observers.add(observer); if (enableHighAccuracy) m_highAccuracyObservers.add(observer); if (m_client) { if (enableHighAccuracy) m_client->setEnableHighAccuracy(true); if (wasEmpty && page() && page()->visibilityState() == PageVisibilityStateVisible) startUpdatingIfNeeded(); } } void GeolocationController::removeObserver(Geolocation* observer) { if (!m_observers.contains(observer)) return; m_observers.remove(observer); m_highAccuracyObservers.remove(observer); if (m_client) { if (m_observers.isEmpty()) stopUpdatingIfNeeded(); else if (m_highAccuracyObservers.isEmpty()) m_client->setEnableHighAccuracy(false); } } void GeolocationController::requestPermission(Geolocation* geolocation) { if (m_client) m_client->requestPermission(geolocation); } void GeolocationController::cancelPermissionRequest(Geolocation* geolocation) { if (m_client) m_client->cancelPermissionRequest(geolocation); } void GeolocationController::positionChanged(GeolocationPosition* position) { position = m_inspectorAgent->overrideGeolocationPosition(position); if (!position) { errorOccurred(GeolocationError::create(GeolocationError::PositionUnavailable, "PositionUnavailable").get()); return; } m_lastPosition = position; WillBeHeapVector<RefPtrWillBeMember<Geolocation> > observersVector; copyToVector(m_observers, observersVector); for (size_t i = 0; i < observersVector.size(); ++i) observersVector[i]->positionChanged(); } void GeolocationController::errorOccurred(GeolocationError* error) { WillBeHeapVector<RefPtrWillBeMember<Geolocation> > observersVector; copyToVector(m_observers, observersVector); for (size_t i = 0; i < observersVector.size(); ++i) observersVector[i]->setError(error); } GeolocationPosition* GeolocationController::lastPosition() { if (m_lastPosition.get()) return m_lastPosition.get(); if (!m_client) return 0; return m_client->lastPosition(); } void GeolocationController::setClientForTest(GeolocationClient* client) { if (m_hasClientForTest) m_client->controllerForTestRemoved(this); m_client = client; m_hasClientForTest = true; client->controllerForTestAdded(this); } void GeolocationController::pageVisibilityChanged() { if (m_observers.isEmpty() || !m_client) return; if (page() && page()->visibilityState() == PageVisibilityStateVisible) startUpdatingIfNeeded(); else stopUpdatingIfNeeded(); } const char* GeolocationController::supplementName() { return "GeolocationController"; } void provideGeolocationTo(LocalFrame& frame, GeolocationClient* client) { Supplement<LocalFrame>::provideTo(frame, GeolocationController::supplementName(), GeolocationController::create(frame, client)); } } // namespace WebCore <|endoftext|>